I Am new to jersey/JAX-RS implementation.
Please find below my jersey client code to download file:
Client client = Client.create();
WebResource wr = client.resource("http://localhost:7070/upload-0.0.1-SNAPSHOT/rest/files/download");
Builder wb=wr.accept("application/json,application/pdf,text/plain,image/jpeg,application/xml,application/vnd.ms-excel");
ClientResponse clientResponse= wr.get(ClientResponse.class);
System.out.println(clientResponse.getStatus());
File res= clientResponse.getEntity(File.class);
File downloadfile = new File("C://Data/test/downloaded/testnew.pdf");
res.renameTo(downloadfile);
FileWriter fr = new FileWriter(res);
fr.flush();
My Server side code is :
#Path("/download")
#GET
#Produces({"application/pdf","text/plain","image/jpeg","application/xml","application/vnd.ms-excel"})
public Response getFile()
{
File download = new File("C://Data/Test/downloaded/empty.pdf");
ResponseBuilder response = Response.ok((Object)download);
response.header("Content-Disposition", "attachment; filename=empty.pdf");
return response.build();
}
In my client code i am getting response as 200 OK,but i am unable to save my file on hard disk
In the below line i am mentioning the path and location where the files need to be saved.
Not sure whats going wrong here,any help would be appreciated.Thanks in advance!!
File downloadfile = new File("C://Data/test/downloaded/testnew.pdf");
For folks still looking for a solution, here is the complete code on how to save jaxrs response to a File.
public void downloadClient(){
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:7070/upload-0.0.1-SNAPSHOT/rest/files/download");
Response resp = target
.request("application/pdf,image/jpeg,application/xml,application/vnd.ms-excel")
.get();
if(resp.getStatus() == Response.Status.OK.getStatusCode())
{
InputStream is = resp.readEntity(InputStream.class);
fetchFeed(is);
//fetchFeedAnotherWay(is) //use for Java 7
IOUtils.closeQuietly(is);
System.out.println("the file details after call:"+downloadfile.getAbsolutePath()+", size is "+downloadfile.length());
}
else{
throw new WebApplicationException("Http Call failed. response code is"+resp.getStatus()+". Error reported is"+resp.getStatusInfo());
}
}
/**
* Store contents of file from response to local disk using java 7
* java.nio.file.Files
*/
private void fetchFeed(InputStream is){
File downloadfile = new File("C://Data/test/downloaded/testnew.pdf");
byte[] byteArray = IOUtils.toByteArray(is);
FileOutputStream fos = new FileOutputStream(downloadfile);
fos.write(byteArray);
fos.flush();
fos.close();
}
/**
* Alternate way to Store contents of file from response to local disk using
* java 7, java.nio.file.Files
*/
private void fetchFeedAnotherWay(InputStream is){
File downloadfile = new File("C://Data/test/downloaded/testnew.pdf");
Files.copy(is, downloadfile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
I don't know if Jersey let's you simply respond with a file like you have here:
File download = new File("C://Data/Test/downloaded/empty.pdf");
ResponseBuilder response = Response.ok((Object)download);
You can certainly use a StreamingOutput response to send the file from the server, like this:
StreamingOutput stream = new StreamingOutput() {
#Override
public void write(OutputStream os) throws IOException,
WebApplicationException {
Writer writer = new BufferedWriter(new OutputStreamWriter(os));
//#TODO read the file here and write to the writer
writer.flush();
}
};
return Response.ok(stream).build();
and your client would expect to read a stream and put it in a file:
InputStream in = response.getEntityInputStream();
if (in != null) {
File f = new File("C://Data/test/downloaded/testnew.pdf");
//#TODO copy the in stream to the file f
System.out.println("Result size:" + f.length() + " written to " + f.getPath());
}
This sample code below may help you.
https://stackoverflow.com/a/32253028/15789
This is a JAX RS rest service, and test client. It reads bytes from a file and uploads the bytes to the REST service. The REST service zips the bytes and sends it back as bytes to the client. The client reads the bytes and saves the zipped file.
I had posted this as a response to another thread.
Here's another way of doing it using Files.copy().
private long downloadReport(String url){
long bytesCopied = 0;
Path out = Paths.get(this.fileInfo.getLocalPath());
try {
WebTarget webTarget = restClient.getClient().target(url);
Invocation.Builder invocationBuilder = webTarget.request(MediaType.TEXT_PLAIN_TYPE);
Response response = invocationBuilder.get();
if (response.getStatus() != 200) {
System.out.println("HTTP status " response.getStatus());
return bytesCopied;
}
InputStream in = response.readEntity( InputStream.class );
bytesCopied = Files.copy(in, out, REPLACE_EXISTING);
in.close();
} catch( IOException e ){
System.out.println(e.getMessage());
}
return bytesCopied;
}
Related
Facing a problem while implementing a java-ws service for downloading a pdf file from another webservice. Below is the piece of code for the same.decode() is used because of the webservice(this java code is invoking) is responding with encoded binary-base-64. I could see the PDF is downloaded in the given location but when i open with pdf reader, it says the file is corrupt. Could you please help me ?
public DownloadFileResponse DownloadResponseMapper(Header header, DownloadDocumentResponseType response){
DownloadFileResponse result = new DownloadFileResponse();
result.setHeader(header);
Status status = new Status();
status.setStatusCode(String.valueOf(String.valueOf(response.getStatus().getStatusCode())));
status.setStatusMessage(response.getStatus().getMessage());
result.setStatus(status);
if(String.valueOf(String.valueOf(String.valueOf(response.getStatus().getStatusCode()))) != "0") {
String qNameFile = FileExchange.getProperty("fileSystem.sharedLocation") + "/" + "result.pdf";
try {
byte[] fileContent = FileUtil.decode(response.getFile());
System.out.println(response.getFile());
FileUtil.writeByteArraysToFile(qNameFile, fileContent);
} catch (Exception e) {
_logger.info(e.getStackTrace());
}
// calculate the hash of the file using two algorithm SHA-256/SHA-512
List<FileHashType> hashes = FileUtil.calculateHash(result.getFile());
result.setFileHash(hashes);
}
return result;
}
public static void writeByteArraysToFile(String fileName, byte[] content) throws IOException {
File file = new File(fileName);
BufferedOutputStream writer = new BufferedOutputStream(new FileOutputStream(file));
writer.write(content);
writer.flush();
writer.close();
}
I am trying to create a file upload API using Jersey. I would like to obtain details about the upload progress in the server side (is it possible?). Searching the web, the suggestion was to use stream to transfer the file. But... even was described below, the server just to execute the "putFile" method after the file arrives completely. Another problem is that these code only works to small files, when I try a file greater than 40mb
#Path("/file")
public class LargeUpload {
private static final String SERVER_UPLOAD_LOCATION_FOLDER = "/Users/diego/Documents/uploads/";
#PUT
#Path("/upload/{attachmentName}")
#Consumes(MediaType.APPLICATION_OCTET_STREAM)
public Response putFile(#PathParam("attachmentName") String attachmentName,
InputStream fileInputStream) throws Throwable {
String filePath = SERVER_UPLOAD_LOCATION_FOLDER + attachmentName;
saveFile(fileInputStream, filePath);
String output = "File saved to server location : ";
return Response.status(200).entity(output).build();
}
// save uploaded file to a defined location on the server
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();
}
}
public static void main(String[] args) throws FileNotFoundException {
ClientConfig config = new ClientConfig();
config.property(ClientProperties.CHUNKED_ENCODING_SIZE, 1024);
Client client = ClientBuilder.newClient(config);
File fileName = new File("/Users/diego/Movies/ff.mp4");
InputStream fileInStream = new FileInputStream(fileName);
String sContentDisposition = "attachment; filename=\"" + fileName.getName()+"\"";
Response response = client.target("http://localhost:8080").path("upload-controller/webapi/file/upload/"+fileName.getName()).
request(MediaType.APPLICATION_OCTET_STREAM).header("Content-Disposition", sContentDisposition).
put(Entity.entity(fileInStream, MediaType.APPLICATION_OCTET_STREAM));
System.out.println(response);
}
I'm trying to implement a method in my java based application that involves uploading a zip file to my server. Client is java, server is java (REST , jboss 7) . In the past I successfully managed to upload image files, but now, with a zip file i am having issues and my main doubt is if these issues are client related or server related (or both) .
So , my client looks like this
final HttpHeaders headers = HttpClientUtils.headersJSONAndAcceptJSON();
MultiValueMap<String, Object> requestMap = new LinkedMultiValueMap<String, Object>();
addMap("filename", filename, requestMap);
addMap("contenttype", contentType, requestMap);
addMap("type", type, requestMap);
try {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
int b = -1;
//file data is the inputstream created from the File
while ( (b = filedata.read())>= 0 ) {
bout.write(b);
}
ByteArrayResource rs = new ByteArrayResource( bout.toByteArray() ){
#Override
public String getFilename() {
return "";
}
};
addMap("resource", rs, requestMap);
} catch (IOException e1) {
throw new IllegalStateException("Error");
}
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
headers.setAccept(Arrays.asList(HttpClientUtils.mtypeJSONUtf8()));
final String url = this.baseURL + summaryURL;
try {
ResponseEntity<Summary> rEntity = restTemplate.exchange(
url,
HttpMethod.POST,
HttpClientUtils.entity(headers, requestMap),
Summary.class
(...)
and meanwhile on the server side I have
#POST
#Path("/")
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces("application/json; charset=UTF-8")
public Summary addImportedSummary(#MultipartForm FileUploadFormObj imp)
{
Summary importedSummary = new Summary();
Map<String , String> newpath = new HashMap<String, String>();
if(imp.getFileData() != null)
{
ZipInputStream zip = new ZipInputStream(imp.getFileData());
ZipEntry entry;
try {
while ((entry = zip.getNextEntry()) != null)
{
if(entry.getName().endsWith(".html") || entry.getName().endsWith(".htm"))
{
if(entry.getSize() > 0)
{
StringWriter writer = new StringWriter();
IOUtils.copy(zip, writer, "UTF-8");
String content = writer.toString();
//do something with the content
}
}
}
zip.close();
} catch (IOException e) {
throw new BadRequestException("Error " + e);
}
}
The problem happens when I try to copy the file content with IOUtils or any other reader. I always get the exception
ZipException too many length or distance symbols
Now, I think the problem might be in the way I am sending the data due to the file being a zip but I don't know exactly where the problem is. Did everyone ever ran into a similar problem?
Related to this question which is about how to send a binary file to a client. I am doing this, actually my method #Produces("application/zip"), and it works well for the browser client. Now I'm trying to write some automated tests against the rest service, using the Wink client. So my question is not how to send the file to the client, but for how to consume the file, as a java rest client (in this case Apache Wink).
My resource method looks something like the below... Once I have a Wink ClientResponse object, how can I get the file from it so I can work with it?
#GET
#Path("/file")
#Produces("application/zip")
public javax.ws.rs.core.Response getFile() {
filesToZip.put("file.txt", myText);
ResponseBuilder responseBuilder = null;
javax.ws.rs.core.Response response = null;
InputStream in = null;
try {
in = new FileInputStream( createZipFile( filesToZip ) );
responseBuilder = javax.ws.rs.core.Response.ok(in, MediaType.APPLICATION_OCTET_STREAM_TYPE);
response = responseBuilder.header("content-disposition", "inline;filename="file.zip").build();
} catch( FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
return response;
The method that actually creates the zip file looks like this
private String createZipFile( Map<String,String> zipFiles ) {
ZipOutputStream zos = null;
File file = null;
String createdFileCanonicalPath = null;
try {
// create a temp file -- the ZIP Container
file = File.createTempFile("files", ".zip");
zos = new ZipOutputStream( new FileOutputStream(file));
// for each entry in the Map, create an inner zip entry
for (Iterator<Map.Entry<String, String>> it = zipFiles.entrySet().iterator(); it.hasNext();){
Map.Entry<String, String> entry = it.next();
String innerFileName = entry.getKey();
String textContent = entry.getValue();
zos.putNextEntry( new ZipEntry(innerFileName) );
StringBuilder sb = new StringBuilder();
byte[] contentInBytes = sb.append(textContent).toString().getBytes();
zos.write(contentInBytes, 0, contentInBytes.length);
zos.closeEntry();
}
zos.flush();
zos.close();
createdFileCanonicalPath = file.getCanonicalPath();
} catch (SecurityException se) {
se.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (zos != null) {
zos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return createdFileCanonicalPath;
}
You can consume it simply as input stream and use ZipInputStream to unzip it.
Here's example using Apache HTTP Client:
HttpClient httpclient = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
get.addHeader(new BasicHeader("Accept", "application/zip"));
HttpResponse response = httpclient.execute(get);
InputStream is = response.getEntity().getContent();
ZipInputStream zip = new ZipInputStream(is);
I have a restfull service , in that service i should send one inputstream object to the client. So i wrote the following code...in service method..
#GET
#Path("/getFile")
#Produces("application/pdf")
public InputStream getFile() throws Exception {
FileInputStream fin = null;
FileOutputStream fout = null;
DataInputStream dis = null;
System.out.println("getFile called in server...");
File serverFile = null;
System.out.println("getfile called..");
try {
serverFile = new File("E:\\Sample2.txt");
fin = new FileInputStream(serverFile);
dis = new DataInputStream(fin);
fin.close();
// dis.close();
} catch (Exception e) {
System.out.println("Exception in server appl..***************");
e.printStackTrace();
}
return dis;
}
In my client application im calling this service as...
String clientURL = "http://xxxxxxx:xxxx/RestfullApp02/resources/LoadFile";
Client client = Client.create();
WebResource webResource = client.resource(clientURL);
InputStream ob = webResource.path("getFile").get(InputStream.class);
But i unable to get the response , it sending 500 error.. like below errror....
com.sun.jersey.api.client.UniformInterfaceException: GET http://myIp:myport/RestfullApp02/resources/LoadFile/getFile returned a response status of 500
Help Me
Please refer the below link, I feel you can solve the issue by it.
http://wpcertification.blogspot.in/2011/11/returning-binary-file-from-rest-service.html