Google App Engine ApiProxy delegate NullPointerException on saving file - java

I'm trying to save a file to Google App Engine and following their documentation, but constantly getting the NullPointerException on the CreateOrReplace method line. Already figured it out that gcsService is created. Any ideas?
public String getFileUrl(MultipartFile file) throws CustomException {
String unique = UUID.randomUUID().toString();
String fileName = unique + ".jpeg";
GcsFilename gcsFilename = new GcsFilename("MY_BUCKET", fileName);
try {
GcsOutputChannel outputChannel = GcsServiceFactory.createGcsService().createOrReplace(gcsFilename, GcsFileOptions.getDefaultInstance());
copy(file.getInputStream(), Channels.newOutputStream(outputChannel));
} catch (IOException e) {
e.printStackTrace();
}
ImagesService imagesService = ImagesServiceFactory.getImagesService();
ServingUrlOptions options = ServingUrlOptions.Builder
.withGoogleStorageFileName("/gs/MY_BUCKET/" + fileName)
.secureUrl(true);
return imagesService.getServingUrl(options);
}
Included dependency:
<dependency>
<groupId>com.google.appengine.tools</groupId>
<artifactId>appengine-gcs-client</artifactId>
<version>0.7</version>
</dependency>
And getting the:
RetryHelper(32.34 s, 6 attempts, com.google.appengine.tools.cloudstorage.GcsServiceImpl$1#74c3f0b0): Too many failures, giving up
With the exception in the log:
c.g.a.tools.cloudstorage.RetryHelper : RetryHelper(1.386 s, x attempts, com.google.appengine.tools.cloudstorage.GcsServiceImpl$1#6bd1dbe9): Attempt #x failed [java.io.IOException: java.lang.NullPointerException], sleeping for x ms
Thanks in advance!
Edit:
Found that ApiProxy class in com.google.apphosting.api on
public static ApiProxy.Delegate getDelegate() {
return delegate;
}
returns NULL.
Any ideas?

Related

Showing an image on broswer using #ResponseBody in spring boot

Hello i have this code to display an immage saved on my filesystem on broswer:
#GetMapping(value = "/prova/img/{id}", produces = MediaType.IMAGE_JPEG_VALUE)
public #ResponseBody byte[] getImageWithMediaType(#PathVariable String id) throws IOException {
String path = uploadFolderPath +"/"+ id;
if(Files.exists(Paths.get(path)) && !Files.isDirectory(Paths.get(path))) {
InputStream in = getClass().getResourceAsStream(path);
return IOUtils.toByteArray(in);
}else {
return null; //this is just for example it should never get here
}
I'm getting this error:
Cannot invoke "java.io.InputStream.read(byte[])" because "input" is null
Any suggestion?
Your code first tests that your input exists (as a File) and is not a directory, then you go ahead and try to read it as a resource from the class path using getClass().getResourceAsStream(path). This is usually not what you want.
Try instead InputStream in = new FileInputStream(path);.
Like this:
if (Files.exists(Paths.get(path)) && !Files.isDirectory(Paths.get(path))) {
InputStream in = new FileInputStream(path);
return IOUtils.toByteArray(in);
}
PS: If you are on Java 9 or later, you don't need the IOUtils dependency, simply use readAllBytes. And as you already use Files and Path, we can clean up the code a bit like this:
Path filePath = Paths.get(path);
if (Files.exists(filePath) && !Files.isDirectory(filePath)) {
InputStream in = Files.newInputStream(filePath, StandardOpenOption.READ);
return in.readAllBytes();
}

Unable to attach file to issue in jira via rest api Java

I want to attach multiple files to issue. I'm able to create issue successfully however i am facing problem in attaching documents after creating issue. I have referred to this link SOLVED: attach a file using REST from scriptrunner
I am getting 404 error even though issue exists and also user has all the permissions.
File fileToUpload = new File("D:\\dummy.txt");
InputStream in = null;
try {
in = new FileInputStream(fileToUpload);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
HttpResponse < String > response3 = Unirest
.post("https://.../rest/api/2/issue/test-85/attachments")
.basicAuth(username, password).field("file", in , "dummy.txt")
.asString();
System.out.println(response3.getStatus());
here test-85 is a issueKey value.
And i am using open-unirest-java-3.3.06.jar. Is the way i am attaching documents is correct?
I am not sure how open-unirest manages its fields, maybe it tries to put them as json field, rather than post content.
I've been using Rcarz's Jira client. It's a little bit outdated but it still works.
Maybe looking at its code will help you, or you can just use it directly.
The Issue class:
public JSON addAttachment(File file) throws JiraException {
try {
return restclient.post(getRestUri(key) + "/attachments", file);
} catch (Exception ex) {
throw new JiraException("Failed add attachment to issue " + key, ex);
}
}
And in RestClient class:
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
public JSON post(String path, File file) throws RestException, IOException, URISyntaxException {
return request(new HttpPost(buildURI(path)), file);
}
private JSON request(HttpEntityEnclosingRequestBase req, File file) throws RestException, IOException {
if (file != null) {
File fileUpload = file;
req.setHeader("X-Atlassian-Token", "nocheck");
MultipartEntity ent = new MultipartEntity();
ent.addPart("file", new FileBody(fileUpload));
req.setEntity(ent);
}
return request(req);
}
So I'm not sure why you're getting a 404, Jira is sometime fuzzy and not really clear about its error, try printing the full error, or checking Jira's log if you can. Maybe it's just the "X-Atlassian-Token", "nocheck", try adding it.

Error : Failed to load PDF document using google cloud StorageOptions for SignUrl

I am trying to get PDF document from Web API using google cloud SignUrl, and want to show in app. Getting "Error : Failed to load PDF document".
I follow for signurl :- https://cloud.google.com/storage/docs/access-control/signed-urls
This below code working fine for images file.
I try commented in code.
Its code getting signurl for all files and pdf file also, but I am unable to figure out that how is it get pdf file for view?
Please go through my code:
ControllerClass :-
class ControllerClass{
public Result show(String fileName) throws IOException {
return redirect(mModelService.getSignedUrl(fileName));
// -- TRY other way to get pdf file.
//return redirect(mModelService.getSignedUrl(userId,fileName));
// .withHeader("Content-Type","application/pdf");
// .as("application/octet-stream");
}
}
Get Signed Url :-
public String getSignedUrl(String fileName) throws IOException {
String remotePath = filePath(fileName);
BlobId blobId = BlobId.of("gcsBucket", remotePath);
Blob blob = getStorage().get(blobId);
if(blob != null && blob.exists()){
URL url = blob.signUrl(ttlMinutes, TimeUnit.MINUTES, SignUrlOption.httpMethod(HttpMethod.GET)
);
return url.toString();
}
Get Storage :-
public com.google.cloud.storage.Storage getStorage() {
if(storage == null) {
synchronized (lock) {
if(storage == null) {
storage = StorageOptions.getDefaultInstance().getService();
}
}
}
return storage;
}
// -- TRY other way to get pdf file.
public String getSignedUrl(String fileName) throws IOException {
BlobId blobId = BlobId.of(gcsBucket, remotePath);
BlobInfo blobInfo = BlobInfo.newBuilder(blobId)
/*.setContentType("application/doc")*/
/*.setContentType("application/pdf")*/
/*.setContentType("application/octet-stream")*/
.build();
URL url = cloudStorageFactory.getStorage().signUrl(blobInfo,ttlMinutes, TimeUnit.MINUTES, SignUrlOption.httpMethod(HttpMethod.GET)
// ,SignUrlOption.withContentType()
);
return url.toString();
}

IllegalArgumentException: Jetty ALPN/NPN has not been properly configured

I'm trying to use google vision in google api, however I have the following problem:
jun 07, 2017 8:50:00 AM io.grpc.internal.ChannelExecutor drain
ADVERTÊNCIA: Runnable threw exception in ChannelExecutor
java.lang.IllegalArgumentException: Jetty ALPN/NPN has not been
properly configured. at
io.grpc.netty.GrpcSslContexts.selectApplicationProtocolConfig(GrpcSslContexts.java:174)
at io.grpc.netty.GrpcSslContexts.configure(GrpcSslContexts.java:151)
at io.grpc.netty.GrpcSslContexts.configure(GrpcSslContexts.java:139)
at io.grpc.netty.GrpcSslContexts.forClient(GrpcSslContexts.java:109)
at
io.grpc.netty.NettyChannelBuilder.createProtocolNegotiatorByType(NettyChannelBuilder.java:335)
at
io.grpc.netty.NettyChannelBuilder.createProtocolNegotiator(NettyChannelBuilder.java:308)
at
io.grpc.netty.NettyChannelBuilder$NettyTransportFactory$DynamicNettyTransportParams.getProtocolNegotiator(NettyChannelBuilder.java:499)
at
io.grpc.netty.NettyChannelBuilder$NettyTransportFactory.newClientTransport(NettyChannelBuilder.java:448)
at
io.grpc.internal.CallCredentialsApplyingTransportFactory.newClientTransport(CallCredentialsApplyingTransportFactory.java:61)
at
io.grpc.internal.InternalSubchannel.startNewTransport(InternalSubchannel.java:209)
at
io.grpc.internal.InternalSubchannel.obtainActiveTransport(InternalSubchannel.java:186)
at
io.grpc.internal.ManagedChannelImpl$SubchannelImplImpl.obtainActiveTransport(ManagedChannelImpl.java:806)
at
io.grpc.internal.GrpcUtil.getTransportFromPickResult(GrpcUtil.java:568)
at
io.grpc.internal.DelayedClientTransport.reprocess(DelayedClientTransport.java:296)
at
io.grpc.internal.ManagedChannelImpl$LbHelperImpl$5.run(ManagedChannelImpl.java:724)
at io.grpc.internal.ChannelExecutor.drain(ChannelExecutor.java:87)
at
io.grpc.internal.ManagedChannelImpl$LbHelperImpl.runSerialized(ManagedChannelImpl.java:715)
at
io.grpc.internal.ManagedChannelImpl$NameResolverListenerImpl.onUpdate(ManagedChannelImpl.java:752)
at io.grpc.internal.DnsNameResolver$1.run(DnsNameResolver.java:174)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
I'm trying to run the api's own sample code, below:
public class QuickstartSample {
public static void main(String... args) throws Exception {
// Instantiates a client
ImageAnnotatorClient vision = ImageAnnotatorClient.create();
// The path to the image file to annotate
String fileName = "./resources/wakeupcat.jpg";
// Reads the image file into memory
Path path = Paths.get(fileName);
byte[] data = Files.readAllBytes(path);
ByteString imgBytes = ByteString.copyFrom(data);
// Builds the image annotation request
List<AnnotateImageRequest> requests = new ArrayList<>();
Image img = Image.newBuilder().setContent(imgBytes).build();
Feature feat = Feature.newBuilder().setType(Type.LABEL_DETECTION).build();
AnnotateImageRequest request = AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
requests.add(request);
// Performs label detection on the image file
BatchAnnotateImagesResponse response = vision.batchAnnotateImages(requests);
List<AnnotateImageResponse> responses = response.getResponsesList();
for (AnnotateImageResponse res : responses) {
if (res.hasError()) {
System.out.printf("Error: %s\n", res.getError().getMessage());
return;
}
for (EntityAnnotation annotation : res.getLabelAnnotationsList()) {
annotation.getAllFields().forEach((k, v) -> System.out.printf("%s : %s\n", k, v.toString()));
}
}
}
}
I'm using the following dependencies:
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-vision</artifactId>
<version>v1-rev357-1.22.0</version>
</dependency>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-vision</artifactId>
<version>0.17.2-beta</version>
</dependency>
Has anyone ever had this problem?
I've actually discovered that to run the api, you must necessarily be in a web context and also be running the application on a Jetty server

gwt load generated class on server side

I have custom class generator. in this generator I creating two classes
public class WsRpcServerGenerator extends Generator{
#Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException {
JClassType classType;
try {
classType = context.getTypeOracle().getType(typeName);
SourceWriter src;
try {
// generating first file xxxAsync for client
src = generateMethod( classType, context, logger);
// generating second class for server side
SourceWriter src2 = generateMethodArgs( classType, context, logger);
if (src2!=null)
src2.commit(logger);
} catch (Exception e) {}
// returning first class for client
if (src == null)return typeName + "__AsyncWsRpcGenerated";
src.commit(logger);
return typeName + "__AsyncWsRpcGenerated";
} catch (NotFoundException e) {}
}
}
I use
TestObject obj = GWT.create(TestObject.class);
This is work. gwt generated two files. and first is loaded in client.
But I dont know how I can load second file on server side. If I refreshing project in eclipse for visibility generated classes, class is loaded with test=Class.forName("com.xxx.TestObject__ArgsGenerated");. but I not wont refreshing project, its library.
Thanks
What Im looking how do it default gwtRpc, gwtRpc save info about rpc serialization policy, what Im saving to class com.xxx.TestObject__ArgsGenerated, to plain text file to web directory.
So I must go this way.
in my generator I must create resource file, and put serialization policy there.
public class WsRpcServerGenerator extends Generator{
#Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName) throws UnableToCompleteException {
JClassType classType;
try {
classType = context.getTypeOracle().getType(typeName);
SourceWriter src;
try {
// generating first file xxxAsync for client
src = generateMethod( classType, context, logger);
// generating file to war directorz
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(baos, SerializationPolicyLoader.SERIALIZATION_POLICY_FILE_ENCODING);
TypeOracle oracle = context.getTypeOracle();
PrintWriter pw = new PrintWriter(osw);
// generate content here
pw.close();
byte[] serializationPolicyFileContents = baos.toByteArray();
String serializationPolicyName = Util.computeStrongName(serializationPolicyFileContents);
String serializationPolicyFileName = SerializationPolicyLoader.getSerializationPolicyFileName(serializationPolicyName);
OutputStream os = context.tryCreateResource(logger, serializationPolicyFileName);
if (os != null) {
os.write(serializationPolicyFileContents);
GeneratedResource resource = ctx.commitResource(logger, os);
}
// returning first class for client
if (src == null)return typeName + "__AsyncWsRpcGenerated";
src.commit(logger);
return typeName + "__AsyncWsRpcGenerated";
} catch (NotFoundException e | IOException e) {}
}
}
reading policy on server side
HttpServlet servlet;
String modulename; // sended from client GWT.getModuleBaseURL() reolacing host
Sending serialiyationpolicyid; // from generated xxxAsync
// Open the RPC resource file and read its contents.
InputStream is=servlet.getServletContext().getResourceAsStream(modulename+"/"+serialiyationpolicyid+".rpc");
// read policy
Im found the solution and make own compiler inspirated by original gwt ClassSourceFileComposerFactory
Generator source
usage
DynamicJavaFileObject composer = new DynamicJavaFileObject("com.xxx","ClassName");
composer.setSuperclass("superclass");
composer.addImport(GWT.class.getCanonicalName());
SourceWriter writer = composer.getSourceWriter();
writer.println("public String test(){return \"test\"}");
writer.commit(logger);
Now I can find class on server side
Class.forName("com.xxx.ClassName");

Categories

Resources