The api server cannot create the file when receives a put request - rest

I am new in APIs. I have a java api server. In put method on server side, i receive a string and i create a arff file using that string. then i do some process on that file and return the result which is another string.
The problem is that when i do a put request the file is not created in local path, but when i run the code on a local application for test the file is created so the code works.
I have to generate a file of that string because i am using a machine learning algorithm that only works with files.Does anyone know why is that?
the method Classify text is called in put method in server side
public static int ClassifyText(String trained_model, String text) throws FileNotFoundException, IOException, Exception {
String evaluation_file = "..\toBeClassified_text.arff";
//create a arff file for the text
FileWriter fileWriter = new FileWriter(new File(evaluation_file));
PrintWriter printWriter = new PrintWriter(fileWriter);

The problem is solved by modifiying thisline:
String evaluation_file = "D:\toBeClassified_text.arff";

Related

How to download pdf file using Feign Client?

In our project we are using feign client to make a call to third party service. For content type application/json it’s working fine. But we have a requirement where a third party service URL return pdf file and that time we are getting exception.
Due to security reason I can not paste the logs and code but if any one share me the code to download a pdf file from feign client that would be very helpful to me.
Thanks in advance!!
You could use byte[] as return type.
#FeignClient(url = "url", name = "name")
public interface SomeFeignClient {
#GetMapping("/give-me-a-pdf")
byte[] getPDF();
}
Your service would simply call
public byte[] getPDF() {
return SomeFeignClient.getPDF();
}
Now with the bytes array you could perform any operation you want, for example saving the file using
FileUtils.writeByteArrayToFile(new File("pathname"), resource);
or provide an endpoint to download the file (Spring boot can return pretty much anything without use of any external library)
#GetMapping("/pdf")
ResponseEntity getPDF() {
byte[] resource = SomeFeignClient.getPDF();
return ResponseEntity.ok()
.contentLength(resource.length)
.contentType(MediaType.APPLICATION_PDF)
.body(resource);
}

How to close InputStream which fed into Response(jax.rs)

#GET
#Path("/{id}/content")
#Produces({ "application/octet-stream" })
public Response getDocumentContentById(#PathParam("id") String docId) {
InputStream is = getDocumentStream(); // some method which gives stream
ResponseBuilder responseBuilder = Response.ok(is);
responseBuilder.header("Content-Disposition", "attachment; filename=" + fileName);
return responseBuilder.build();
}
Here how can I close the InputStream is ? If something(jax.rs) closes automatically. Please give me some information. Thank you.
When you're wanting to stream a custom response, the most reliable way I've found is to return an object that contains the InputStream (or which can obtain the stream in some other way at some point), and to define a MessageBodyWriter provider that will do the actual streaming at the right time.
For example, this code is part of Apache Taverna, and it streams back the zipped contents of a directory. All that the main code needs to do to use it is to return a ZipStream as the response (which can be packaged in a Response or not) and to ensure that it is dealing with returning the application/zip content type. The final point to note is that since this is dealing with CXF, you need to manually register the provider; unlike with Glassfish, they are not automatically picked up. This is a good thing in sophisticated scenarios, but it does mean that you need to do the registration.

Jclouds swift api upload object directly from inputstream

The following snippet uploads files to object store without any problem
public void uploadObjectFromStream(String container, String name, InputStream stream) {
SwiftApi swiftApi = getApi();
createContainerIfAbsent(container, swiftApi);
ObjectApi objectApi = swiftApi.getObjectApiForRegionAndContainer(REGION, container);
Payload payload = new InputStreamPayload(stream);
objectApi.put(name, payload, PutOptions.Builder.metadata(ImmutableMap.of("X-Object-Meta-key1", "value3", "X-Object-Meta-key2", "test"))); // test
}
If I try to upload ~10Mb file I get error
o.j.h.i.HttpWire [SLF4JLogger.java:56] over limit 10485760/262144: wrote temp file
java.lang.OutOfMemoryError: Java heap space
The question is if I can upload object from input stream to object store without saving the stream in application memory or file system.
jclouds does not buffer InputStream unless you enable wire logging. Generally this should be disabled unless you are debugging an issue.

AXIS 2 : java.lang.ClassCastException: com.sun.org.apache.xerces.internal.dom.DeferredElementNSImpl cannot be cast to org.apache.axiom.om.OMElement

I am using AXIS2 as client for handling SOAP response. The client stubs are generated using WSDL2JAVA command. To solve an issue, I am trying to read an xml response stored in .xml file in the generated stub, and assign to SOAPEnvelope. Below is the code written to load .xml content :
InputStream is = new ByteArrayInputStream((sb.toString()).getBytes());
javax.xml.parsers.DocumentBuilderFactory factory = avax.xml.parsers.DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
javax.xml.parsers.DocumentBuilder builder = null;
builder = factory.newDocumentBuilder();
org.w3c.dom.Document doc = builder.parse(is);
System.out.println("Got Document ..............");
is.close();
org.apache.axis2.saaj.util.SAAJUtil su = new org.apache.axis2.saaj.util.SAAJUtil();
org.apache.axiom.soap.SOAPEnvelope _returnEnv1 = su.getSOAPEnvelopeFromDOOMDocument(doc);
Am getting ClassCastException at the last line in the code (assigning to SOAPEnvelope).
Can someone please help me with this.
Axis2clients are used to send requests and receive response. Why are you trying to load response from a file? You should receive the response from the backend service. Check this guide to get to know about the clientapi. You can find detail guide in axis2 documentation also.

How to retrieve inputStream from the server using fileUploader and GWT 2.4?

I have a fileUploader widget that I'm using to select an xml file. I then have a button that calls my handler in the viewImpl class when the user submits the selected file. If I understand things correctly, from there I do a submit from the formPanel and the file is on the server.
#UiHandler("calculateComplexityButton")
void onClickCalculateComplexity(ClickEvent e){
formPanel.submit();
//How do I get the inputStream back to here????
presenter.getTask(inputStream);
}
My problem is how do I get the inputStream off the server? I tried using an RPC call for all this, but when I try to get the inputStream I'm not pulling anything off the server. I tried:
inputStream = request.getInputStream();
but it appears to be empty. Any ideas on this?
I dropped the RPC code and used a simple HTTPRequest I found here. That gets me to the servlet, but the request doesn't have the file stream. When I reach this line in the code:
FileItemIterator iter = upload.getItemIterator(request); //Nothing is here in iter.
You can not make an upload via RPC, thats why you have to submit your form to a servlet.
final FormPanel form = new FormPanel();
form.setEncoding(FormPanel.ENCODING_MULTIPART);
form.setMethod(FormPanel.METHOD_POST);
form.setAction("/upload");
So, when you do form.submit() it will send your file to the Action(Servlet). In the server side you can use the lib form apache (commons-fileupload). You have many different way to get your file, you can save on disk, read on memory....