Nullpointer exception soapui file upload call - java

I have to upload a file using soap ui.Below is my service code.It executes fine if call using jersey.But when i try to call using soapui null pointer exception occurs.
I call the fileupload service in soap ui like below
Create Rest Project:
Add the Url:
http://localhost:8080/FileService/Services/HomeService/testupload
file file:c:\\1.wav
#POST
#Path("testupload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces(MediaType.TEXT_PLAIN)
public String uploadFile(#FormDataParam("file") InputStream fis,
#FormDataParam("file") FormDataContentDisposition fdcd) {
OutputStream outpuStream = null;
String fileName = fdcd.getFileName();
String filePath = FOLDER_PATH + fileName;
try {
int read = 0;
byte[] bytes = new byte[1024];
outpuStream = new FileOutputStream(new File(filePath));
while ((read = fis.read(bytes)) != -1) {
outpuStream.write(bytes, 0, read);
}
outpuStream.flush();
outpuStream.close();
} catch(IOException iox){
iox.printStackTrace();
} finally {
if(outpuStream != null){
try{outpuStream.close();} catch(Exception ex){}
}
}
return "File Upload Successfully !!";
}
How to fix this issue? Any help will be greatly appreciated!!!

Related

Using relative path to store the uploaded file in java using Jersey

I am able to save image file in c://temp/images locally. But I want it in Project folder itself. Here is my code
#Path("/files")
public class FileUpload {
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
#FormDataParam("file") InputStream uploadedInputStream,
#FormDataParam("file") FormDataContentDisposition fileDetail) {
String uploadedFileLocation = "C://temp/images" + fileDetail.getFileName();
// save it
writeToFile(uploadedInputStream, uploadedFileLocation);
String output = uploadedFileLocation;
return Response.status(200).entity(output).build();
}
// save uploaded file to new location
private void writeToFile(InputStream uploadedInputStream,
String uploadedFileLocation) {
try {
OutputStream out = new FileOutputStream(new File(
uploadedFileLocation));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
When I tried to replace file location with /resources/Images/,I am getting file not found exception.

png file Uploading Restful Web Service java

I try to write an image file uploading post method for my web service. Here is my post method. The image file can be uploaded into post method but can not converted into Image type.
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces("text/html")
public Response uploadFile(#FormDataParam("file") File file2) throws IOException {
InputStream IS = null;
String output = "";
try {
IS = new FileInputStream(file2);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
try {
if (file2 != null && IS != null) {
Image img = ImageIO.read(IS);
if (img != null) {
output = "image file transmission sucessed";
} else {
String out = convertStreamToString(IS);
output = "file uploaded into post method, however can not transfer it into image type "+
"\n"+ out;
}
} else if (file2 == null) {
output = "the file uploaded into post method is null";
}
} catch (IOException e) {
e.printStackTrace();
}
return Response.status(200).entity(output).build();
}
static String convertStreamToString(java.io.InputStream is) {
java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
The "file uploaded into post method, however can not transfer it into image type "+"\n"+ out; message is shown. The reason I believe is the inputStream contants extral file information + the content of the image. When I try to convert the inputStream back to Image, I need to find a way to get rid of the extra info passed.
here is my new reversion:
#POST
#Path("/images")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response imageUpload(
#FormDataParam("image") InputStream hereIsImage,
#FormDataParam("image") FormDataContentDisposition hereIsName) {
String path = "f://";
if (hereIsName.getSize() == 0) {
return Response.status(500).entity("image parameter is missing")
.build();
}
String name = hereIsName.getFileName();
path += name;
try {
OutputStream out = new FileOutputStream(new File(path));
int read;
byte[] bytes = new byte[1024];
while ((read = hereIsImage.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
return Response.status(500)
.entity(name + " was not uploaded\n" + e.getMessage())
.build();
}
return Response.status(200).entity(name + " was uploaded").build();
}
However, when I upload the image, an error pops up:
[ERROR] An exception occurred during processing of the au.edu.rmit.srtwebservice.util.rest.testWS class. This class is ignored.
com/sun/jersey/core/header/FormDataContentDisposition
the testWS.calss is where my method is.
public Response uploadFile(#FormDataParam("file") File file2)
File input may not work because you most likely be sending an octet stream from your client. So try using InputStream as the input type and hopefully it should work.
public Response uploadFile(#FormDataParam("file") InputStream file2)

PlayFramework. How to upload a photo using an external endpoint?

How do I upload a photo using a URL in the playframework?
I was thinking like this:
URL url = new URL("http://www.google.ru/intl/en_com/images/logo_plain.png");
BufferedImage img = ImageIO.read(url);
File newFile = new File("google.png");
ImageIO.write(img, "png", newFile);
But maybe there's another way. In the end I have to get the File and file name.
Example controller:
public static Result uploadPhoto(String urlPhoto){
Url url = new Url(urlPhoto); //doSomething
//get a picture and write to a temporary file
File tempPhoto = myUploadPhoto;
uploadFile(tempPhoto); // Here we make a copy of the file and save it to the file system.
return ok('something');
}
To get that photo you can use The play WS API, the code behind is an example extracted from the play docs in the section Processing large responses, I recommend you to read the full docs here
final Promise<File> filePromise = WS.url(url).get().map(
new Function<WSResponse, File>() {
public File apply(WSResponse response) throws Throwable {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = response.getBodyAsStream();
// write the inputStream to a File
final File file = new File("/tmp/response.txt");
outputStream = new FileOutputStream(file);
int read = 0;
byte[] buffer = new byte[1024];
while ((read = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, read);
}
return file;
} catch (IOException e) {
throw e;
} finally {
if (inputStream != null) {inputStream.close();}
if (outputStream != null) {outputStream.close();}
}
}
}
);
Where url is :
String url = "http://www.google.ru/intl/en_com/images/logo_plain.png"
This is as suggested in play documentation for large files:
*
When you are downloading a large file or document, WS allows you to
get the response body as an InputStream so you can process the data
without loading the entire content into memory at once.
*
Pretty much the same as the above answer then some...
Route: POST /testFile 'location of your controller goes here'
Request body content: {"url":"http://www.google.ru/intl/en_com/images/logo_plain.png"}
Controller(using code from JavaWS Processing large responses):
public static Promise<Result> saveFile() {
//you send the url in the request body in order to avoid complications with encoding
final JsonNode body = request().body().asJson();
// use new URL() to validate... not including it for brevity
final String url = body.get("url").asText();
//this one's copy/paste from Play Framework's docs
final Promise<File> filePromise = WS.url(url).get().map(response -> {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = response.getBodyAsStream();
final File file = new File("/temp/image");
outputStream = new FileOutputStream(file);
int read = 0;
byte[] buffer = new byte[1024];
while ((read = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, read);
}
return file;
} catch (IOException e) {
throw e;
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}); // copy/paste ended
return filePromise.map(file -> (Result) ok(file.getName() + " saved!")).recover(
t -> (Result) internalServerError("error -> " + t.getMessage()));
}
And that's it...
In order to serve the file after the upload phase you can use this answer(I swear I'm not promoting myself...): static asset serving from absolute path in play framework 2.3.x

Local upload file via rest web service

I am using the code in this link http://www.mkyong.com/webservices/jax-rs/file-upload-example-in-jersey/ to upload a file.In this example I have to pass from a html page to specify the file to upload but I want to to acceed to it when I call the webservice by its path ( s.thing like that : http://*****:8080/RESTfulExample/file/upload/C://image.png)
Are there any suggestions to this issue? Please help!
That is what i did till now to solve it
#Path(value="/files")
public class upload {
#POST
#Path(value = "upload/{path}")
#Consumes("image/jpg")
public Response uploadPng(#PathParam("path") String path, File file) throws IOException {
file = new File("path");
String uploadedFileLocation = "C:/Users/Desktop/" + file.getName();
DataInputStream diStream =new DataInputStream(new FileInputStream(file));
long len = (int) file.length();
byte[] fileBytes = new byte[(int) len];
int read = 0;
int numRead = 0;
while (read < fileBytes.length && (numRead =
diStream.read(fileBytes, read,fileBytes.length - read)) >= 0) {
read = read + numRead;
}
writeToFile(diStream, uploadedFileLocation);
System.out.println("File uploaded to : " + uploadedFileLocation);
return Response.status(200).entity(file).build();
}
private void writeToFile(InputStream uploadedInputStream,
String uploadedFileLocation) {
try {
OutputStream out =new FileOutputStream(new File(uploadedFileLocation));
int read = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream(new File(uploadedFileLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}}}
But I have an 405 error now !!
EDIT
#Path(value= "/up")
public class upload {
private static final String SERVER_UPLOAD_LOCATION_FOLDER = "C://Users/Marwa/Desktop/mafile.png";
#POST
#Path(value="upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public String uploadFile(#FormDataParam("file") InputStream fileInputStream) {
String filePath = SERVER_UPLOAD_LOCATION_FOLDER ;
System.out.println("*****serverpath********");
saveFile(fileInputStream, filePath);
String output = "File saved to server location : " + filePath;
return output;
}
private void saveFile(InputStream uploadedInputStream,String serverLocation) {
try {
OutputStream outpuStream = new FileOutputStream(new File(serverLocation));
int read = 0;
byte[] bytes = new byte[1024];
outpuStream = new FileOutputStream(new File(serverLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
outpuStream.write(bytes, 0, read);}
outpuStream.flush();
outpuStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I think you'd just call http://example.com/file/upload and post the file there with the browser (with JavaScript) or some other client. For example, you could test it with curl
curl -i -F "file=#/home/user1/Desktop/test.jpg" http://example.com/file/upload
Do you need the file path for something on the server side? If you need the path on the server side for some reason, you could just add a #PathParam.
#POST
#Path("/upload/{path}")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
#PathParam("path") String path,
#FormDataParam("file") InputStream uploadedInputStream,
#FormDataParam("file") FormDataContentDisposition fileDetail) {
...
}
You could also try leaving off #consumes or using a specific type like #consumes("image/jpg"). For example:
#POST
#Path("/upload/{path}")
#Consumes("image/jpg")
public Response uploadFile(
#PathParam("path") String path,
InputStream uploadedInputStream) {
...
}

java development setting path in linux

i have development a simple webservices to upload a image to computer in linux. it have some problem the saving file location. when i summit the image, it become no response And i already import all require package.
#Path("/files")
public class V1_status {
/**
* Upload a File
*/
#POST
#Path("/upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public String uploadFile(
#FormDataParam("file") InputStream uploadedInputStream,
#FormDataParam("file") FormDataContentDisposition fileDetail){
saveToDisk(uploadedInputStream, fileDetail);
return"File uploaded successfully!";
}
// save uploaded file to a defined location on the server
private void saveToDisk(InputStream uploadedInputStream,FormDataContentDisposition fileDetail
) {
String uploadedFileLocation= "/home/fairlady/Pictures" +fileDetail.getFileName();
try {
OutputStream out= new FileOutputStream(new File(uploadedFileLocation));
int read = 0;
byte[] bytes = new byte[1024];
out= new FileOutputStream(new File(uploadedFileLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In this line
String uploadedFileLocation= "/home/fairlady/Pictures" +fileDetail.getFileName();
you are missing a forward slash after Pictures
try
String uploadedFileLocation= "/home/fairlady/Pictures/"+fileDetail.getFileName();

Categories

Resources