The system cannot find the path specified in my Java JAR file - file

I am running a jar file .spring code for backend and react js for frontend. The code below works perfect for frontend and backend apart but what do you do if it is a jar . Only recieving "cant find file"
#RequestMapping(value = "/getPdf/{userType}/{userRoll}/{trainingFileName}", method = RequestMethod.GET)
public ResponseEntity<InputStreamResource> getPdf(#PathVariable("userType") String userType,
#PathVariable("userRoll") String userRoll,
#PathVariable("trainingFileName") String trainingFileName) throws IOException {
String fileName =trainingFileName + ".pdf";
String filePath = "TrainingDocuments/" +userType+"/"+userRoll+"/"+ trainingFileName+ "/"+ fileName;
File file = new File(filePath);
HttpHeaders headers = new HttpHeaders();
headers.add("content-disposition", "inline;filename=" +fileName);
InputStreamResource resource = new InputStreamResource(new FileInputStream(file));
return ResponseEntity.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.parseMediaType("application/pdf"))
.body(resource);
}

Related

Cannot open downloaded zip file from rest endpoint using file-saver

Here is the backend code for the download endpoint:
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ZipOutputStream zipOut = new ZipOutputStream(byteArrayOutputStream);
for (Long id : ids) {
// Get the "generated" file using the id
zipOut.putNextEntry(new ZipEntry(generated.getName() + ".doc"));
InputStream inputStream = new ByteArrayInputStream(generated.getFile().getBytes(1, (int)generated.getFile().length()));
IOUtils.copy(inputStream, zipOut);
zipOut.closeEntry();
}
zipOut.close();
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=File.zip");
byte[] zipBytes = byteArrayOutputStream.toByteArray();
OutputStream outputStream = response.getOutputStream();
outputStream.write(zipBytes);
outputStream.close();
response.flushBuffer();
And for the frontend, I am using axios and file-saver
import { saveAs } from "file-saver";
request.then((response: any) => {
const blob = new Blob([response.data], { type: "application/zip" });
saveAs(blob, "Report.zip");
});
I can download the zip file, but when I tried to open, I got the follwing error:
"An attempt was made to move the file pointer before the beginning of the file"
NOTE: There is no error on the backend. The zip file is downloaded successfully. But upon opening the zip file, the error pops up.
Please, try to rewrite it like that:
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=File.zip");
ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream());
for (Long id : ids) {
// Get the "generated" file using the id
zipOut.putNextEntry(new ZipEntry(generated.getName() + ".doc"));
InputStream inputStream = new ByteArrayInputStream(generated.getFile().getBytes(1, (int)generated.getFile().length()));
IOUtils.copy(inputStream, zipOut);
zipOut.closeEntry();
}
zipOut.close();
response.flushBuffer();

Exception in Service NOW attachment API invocation-- Premature end of chunk coded message body: closing chunk expected

I am using HttpClient to send POST multipart request, using the below code
String apiUrl = API_URL_DEV;
String name = API_USER_DEV;
String password = API_PASSWORD_DEV;
String authString = name + ":" + password;
String encoding = Base64.getEncoder().encodeToString(authString.getBytes());
apiUrl = "https://<servicenow host>/api/now/attachment/upload";
try {
Header header = new BasicHeader(HttpHeaders.CONTENT_TYPE, "multipart/form-data");
Header header2 = new BasicHeader(HttpHeaders.ACCEPT, "application/json");
Header header3 = new BasicHeader(HttpHeaders.AUTHORIZATION, "Basic " + encoding);
List<Header> headers = new ArrayList<Header>();
headers.add(header);
headers.add(header2);
headers.add(header3);
HttpHost proxy = new HttpHost("xxxx", 8080, "http");
CloseableHttpClient client = HttpClientBuilder.create()
.setDefaultHeaders(headers)
.setProxy(proxy)
.build();
HttpPost post = new HttpPost(apiUrl);
String textFileName = "C:/Heena_Code/Test.xlsx";
File file = new File(textFileName);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
StringBody stringBody1 = new StringBody("change_request", ContentType.MULTIPART_FORM_DATA);
StringBody stringBody2 = new StringBody("a81c6a1ddb2948d04af824f4059619a9", ContentType.MULTIPART_FORM_DATA);
builder.addPart("table_name", stringBody1);
builder.addPart("table_sys_id", stringBody2);
builder.addPart("uploadFile", fileBody);
HttpEntity entity = builder.build();
post.setEntity(entity);
// Execute HTTP Post Request
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = client.execute(post, responseHandler); -----> exception here
System.out.println(responseBody);
Getting exception
Severe: org.apache.http.ConnectionClosedException: Premature end of chunk coded message body: closing chunk expected
at org.apache.http.impl.io.ChunkedInputStream.getChunkSize(ChunkedInputStream.java:263)
at org.apache.http.impl.io.ChunkedInputStream.nextChunk(ChunkedInputStream.java:222)
at org.apache.http.impl.io.ChunkedInputStream.read(ChunkedInputStream.java:183)
at org.apache.http.impl.io.ChunkedInputStream.read(ChunkedInputStream.java:210)
at org.apache.http.impl.io.ChunkedInputStream.close(ChunkedInputStream.java:312)
at org.apache.http.impl.execchain.ResponseEntityProxy.streamClosed(ResponseEntityProxy.java:142)
at org.apache.http.conn.EofSensorInputStream.checkClose(EofSensorInputStream.java:228)
at org.apache.http.conn.EofSensorInputStream.close(EofSensorInputStream.java:172)
at org.apache.http.client.entity.LazyDecompressingInputStream.close(LazyDecompressingInputStream.java:97)
at org.apache.http.util.EntityUtils.consume(EntityUtils.java:90)
at org.apache.http.impl.client.AbstractResponseHandler.handleResponse(AbstractResponseHandler.java:69)
at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:66)
at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:52)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:223)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:165)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:140)
I changed my approach and used a MultiPartUtility class to fire request through HTTPUrlConnection passing two form fields in text/plain format and the file in application/octetstream format and binary encoding

Spring Boot endpoint for downloading File automatically

I want to make a Spring Boot endpoint for downloading file. I Have tried this things but the file does not download automatically... I get only file content in the body...
#RequestMapping(value = "/files", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
#ResponseBody
public ResponseEntity<FileSystemResource> getFile(#RequestParam(name = "start") String start) {
return new ResponseEntity<>(new FileSystemResource(myService.makeFile(start)),
HttpStatus.OK);
}
Another one that I have tried is this:
#RequestMapping(value = "/download", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public String download(HttpServletResponse response, #RequestParam(name = "start") String start)
{
response.setContentType("application/force-download");
FileReader fr = new FileReader(myService.makeFile(start));
return IOUtils.toString(fr);
}
I have read that MediaType.APPLICATION_OCTET_STREAM_VALUE will force it to download but nothing happened in my case.
You are on the right track, you just need to set one response header Content-Disposition to attachment; filename=YOUR_FILE_NAME.
Try This:
#RequestMapping(value = "/files", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public FileSystemResource getFile(#RequestParam(name = "start") String start, HttpServletResponse response) {
response.setHeader("Content-Disposition", "attachment; filename=" + "YOUR_FILE_NAME");
return new FileSystemResource(myService.makeFile(start));
}

Hack to upload a file from Java backend to a remote server over HTTP using Rest API.

My file resides on some location on my machine say C://users//abc.txt and i want to write a java program to transfer this file using REST API over HTTP. I used MockHttpServelet Request to create the request, but somehow i am unable to transfer the file
Use HttpClient:
String url = "http://localhost:8080/upload"; // Replace with your target 'REST API' url
String filePath = "C://users//abc.txt";
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpPost httpPost = new HttpPost(url);
FileEntity entity = new FileEntity(new File(filePath), ContentType.TEXT_PLAIN);
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost);
System.out.println(httpResponse.getStatusLine().getStatusCode()); // Check HTTP code
} finally {
httpClient.close();
}
With Authentication:
String url = "http://localhost:8080/upload"; // Replace with your target 'REST API' url
String filePath = "C://users//abc.txt";
String username = "username"; // Replace with your username
String password = "password"; // Replace with your password
RequestConfig requestConfig =
RequestConfig.custom().
setAuthenticationEnable(true).
build();
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(
AuthScope.ANY,
new UsernamePasswordCredential(username, password));
CloseableHttpClient httpClient =
HttpClients.custom().
setDefaultRequestConfig(requestConfig).
setDefaultCredentialsProvider(credentialsProvider).
build();
try {
HttpPost httpPost = new HttpPost(url);
FileEntity entity = new FileEntity(new File(filePath), ContentType.TEXT_PLAIN);
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost);
System.out.println(httpResponse.getStatusLine().getStatusCode()); // Check HTTP code
} finally {
httpClient.close();
}
String location="C:\\Usersabc.img";
Path path = Paths.get(location);
String name=location.substring(location.lastIndexOf("\\")+1);
MultipartEntity multipart= new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
try {
multipart.addPart("image", new ByteArrayBody(Files.readAllBytes(path), ContentType.APPLICATION_OCTET_STREAM.getMimeType(),name));
}
catch (IOException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}

How can I send a file from the server to client using REST (JAX-RS Jersey)?

I want to send a file from my server side (EJB) using REST Jersey (JAX-RS).
I am trying with the following code,
Public Response getFiles() {
File file = new File(fileName);
FileOutputStream dest = new FileOutputStream(file);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
out.putNextEntry(new ZipEntry(fileName));
final ResponseBuilder response = Response.ok(out);
response.header("Content-Type", "*/*");
response.header("Content-Disposition", "attachment; filename=" + file.getName() + ".zip");
return response.build();
}
But I am getting the exception message
type class java.util.zip.ZipOutputStream, and MIME media type */* was not found
SEVERE: The registered message body writers compatible with the MIME media type are:
Also tried with "Content-Type" , "application/octet-stream", "application/x-www-form-urlencoded" and multipart/form-data
But none of them is working.
Use application/zip.
#GET
#Produces("application/zip")
public Response getZip() {
final File f = new File("/tmp/foo.zip");
ResponseBuilder response = Response.ok((Object) f);
response.header("Content-Disposition", "attachment; filename=" + f.getName());
return response.build();
}
application/octet-stream + gzip
#GET
#Path("/getFiles")
#Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response getFiles() {
StreamingOutput stream = new StreamingOutput() {
#Override
public void write(OutputStream output) throws IOException, WebApplicationException {
String filePath = "/yourFile.pdf";
java.nio.file.Path path = Paths.get(filePath);
byte[] data = Files.readAllBytes(path);
output.write(data);
output.flush();
}
};
return Response.ok(stream).build();
}
and a jersey filter added to web.xml
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
<param-value>com.sun.jersey.api.container.filter.GZIPContentEncodingFilter</param-value>
</init-param>
when making the request:
send a header of "Accept" with value of "application/octet-stream"
and a header of "Accept-Encoding" with value of "gzip"

Resources