1

I am writing an azure function using spring boot and i want to read a file form resources folder but every time getting null pointer Exception. please help me on this how i can fix this issue ? either i have to put the file in blob storage or something else is there in azure function to read file using java spring boot application ?

below is my handler class:

public class FunctionHandler extends AzureSpringBootRequestHandler<User, Greeting> {

    @FunctionName("generateSignature")
    public HttpResponseMessage execute(@HttpTrigger(name = "request", methods = { HttpMethod.GET,
                    HttpMethod.POST }, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<User>> request,
                    ExecutionContext context) throws InvalidKeyException, NoSuchAlgorithmException,
                    InvalidKeySpecException, SignatureException, IOException {
            User user = request.getBody().filter((u -> u.getName() != null)).orElseGet(() -> new User(request
                            .getQueryParameters()
                            .getOrDefault("name", "<no name supplied> please provide a name as "
                                            + "either a query string parameter or in a POST body")));
            context.getLogger().info("Greeting user name: " + user.getName());

            try {
                    InputStream resourceInputStream = new FileInputStream(
                                    FunctionHandler.class.getClassLoader().getResource("").getPath()
                                                    + "../../src/main/java/com/tomtom/resources/private_key.der");

                    DataInputStream dis = new DataInputStream(resourceInputStream);
                    byte[] privateBytes = new byte[resourceInputStream.available()];

                    dis.readFully(privateBytes);
                    dis.close();

                    PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privateBytes);
                    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                    RSAPrivateKey privateKey = (RSAPrivateKey) keyFactory.generatePrivate(privSpec);

                    Signature s = Signature.getInstance("SHA256withRSA");
                    s.initSign(privateKey);
                    s.update(user.getName().getBytes("UTF-8"));
                    byte[] binarySignature = s.sign();
                    String signature = DatatypeConverter.printBase64Binary(binarySignature);
                    context.getLogger().info("sign is: " + signature);

            } catch (IOException e) {
                    e.printStackTrace();
            }

            return request.createResponseBuilder(HttpStatus.OK).body(handleRequest(user, context))
                            .header("Content-Type", "application/json").build();
    }

}

my project structure

1 Answers1

1

Try with this code:

InputStream resourceInputStream = new FileInputStream(HelloFunction.class.getClassLoader().getResource("").getPath()+"../../src/main/java/com/example/resources/hello.json");

My source code structure is like below:

enter image description here


UPDATE:

String pathToResources = "hello.json";
// this is the path within the jar file
InputStream input = HelloHandler.class.getResourceAsStream("/resources/" + pathToResources);

// here is inside IDE
if (input == null) {
    input = HelloHandler.class.getClassLoader().getResourceAsStream(pathToResources);
}

// convert InputStream to String
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer)) != -1) {
    result.write(buffer, 0, length);
}

System.out.println(result.toString("UTF-8"));

enter image description here

unknown
  • 6,778
  • 1
  • 5
  • 14
  • This is working normally but if i use inside function call , then it is throwing java.io.FileNotFoundException : file:\E:\MyFunctionProject\target\azure-functionsmy-function-app-name\lib\log4j-api-2.13.3.jar!\META-INF\versions\9\..\..\src\main\java\com\example\resources\private_key.der (The filename, directory name, or volume label syntax is incorrect)[2020-11-23T11:28:31.760Z] Handler processing a request for: – Ram Krishna paul Nov 23 '20 at 11:30
  • Please see my update, I move the resource folder to **main**. – unknown Nov 24 '20 at 06:01
  • 1
    Thanks it's working now, after moving outside from package. – Ram Krishna paul Nov 24 '20 at 06:21