how to zip file download without real file - java

I make zip download.
My code works correctly.
Here is my code.
package com.example.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.example.common.CommonException;
import net.lingala.zip4j.ZipFile;
#Controller
#RequestMapping("/example")
public class ExampleController {
#RequestMapping(value="/myDownload", method = RequestMethod.GET)
public ResponseEntity<byte[]> myDownload(HttpServletRequest request) throws CommonException {
HttpHeaders headers = new HttpHeaders();
ResponseEntity<byte[]> result = null;
try {
ClassPathResource myShareDir1CPR = new ClassPathResource("static/share1");
ClassPathResource myShareDir2CPR = new ClassPathResource("static/share2");
ClassPathResource myShareDir3CPR = new ClassPathResource("static/share3");
ClassPathResource myShareDir4CPR = new ClassPathResource("static/share4");
File share1Dir = myShareDir1CPR.getFile();
File share2Dir = myShareDir2CPR.getFile();
File share3Dir = myShareDir3CPR.getFile();
File share4Dir = myShareDir4CPR.getFile();
ZipFile zipFile = new ZipFile("myTempFile.zip");
zipFile.addFolder(share1Dir);
zipFile.addFolder(share2Dir);
zipFile.addFolder(share3Dir);
zipFile.addFolder(share4Dir);
byte[] binaryData = IOUtils.toByteArray(new FileInputStream(zipFile.getFile()));
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=output_file.zip;");
result = new ResponseEntity<byte[]>(binaryData, headers, HttpStatus.OK);
} catch (IOException e) {
// TODO Auto-generated catch block
throw new CommonException(e.getMessage());
}
return result;
}
}
But I don't want to leave the file on the server.
What I have done is:
File createTempFile = File.createTempFile("test", ".zip");
ZipFile zipFile = new ZipFile(createTempFile);
However, an error occurs:
Zip file size less than minimum expected zip file size. Probably not a zip file or a corrupted zip file

Related

File Upload Using Rest API Client in JAVA

I have created a client rest api to upload a file on the api endpoints. But this is giving me error:
Exception in thread "main" org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyWriter not found for media type=multipart/form-data, type=class org.glassfish.jersey.media.multipart.FormDataMultiPart, genericType=class org.glassfish.jersey.media.multipart.FormDataMultiPart.
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor$TerminalWriterInterceptor.aroundWriteTo(WriterInterceptorExecutor.java:191)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:139)
at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1005)
at org.glassfish.jersey.client.ClientRequest.writeEntity(ClientRequest.java:430)
at org.glassfish.jersey.client.HttpUrlConnector._apply(HttpUrlConnector.java:287)
at org.glassfish.jersey.client.HttpUrlConnector.apply(HttpUrlConnector.java:200)
at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:215)
at org.glassfish.jersey.client.JerseyInvocation$1.call(JerseyInvocation.java:635)
at org.glassfish.jersey.client.JerseyInvocation$1.call(JerseyInvocation.java:632)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:421)
at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:632)
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:392)
at org.glassfish.jersey.client.JerseyInvocation$Builder.post(JerseyInvocation.java:301)
at Test.main(Test.java:35)
Here is my client rest api code:
import java.io.File;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import org.glassfish.jersey.media.multipart.MultiPart;
import org.glassfish.jersey.media.multipart.MultiPartFeature;
import org.glassfish.jersey.media.multipart.file.FileDataBodyPart;
public class Test {
public void configureClient(ClientConfig config) {
config.register(MultiPartFeature.class);
}
public static void main(String[] args) {
Client client = ClientBuilder.newClient().register(MultiPart.class);
WebTarget server = client.target("http://localhost:8080/repositories/file/upload");
FileDataBodyPart filePart = new FileDataBodyPart("file", new File("C:\\Users\\kunal\\Downloads\\JWTUtility.java"));
filePart.setContentDisposition(FormDataContentDisposition.name("file").fileName("JWTUtility.java").build());
MultiPart multipartEntity = new FormDataMultiPart().bodyPart(filePart);
Response result = server.request().post(Entity.entity(multipartEntity, multipartEntity.getMediaType()));
System.out.println(result.getStatus());
System.out.println(result.readEntity(String.class));
result.close();
//assertEquals(Response.Status.OK.getStatusCode(), result.getStatus());
}
}
API Endpoint code:
package com.howtodoinjava.jersey;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
#Path("/upload")
public class JerseyService
{
#POST
#Path("/pdf")
#Consumes({MediaType.MULTIPART_FORM_DATA})
public Response uploadPdfFile( #FormDataParam("file") InputStream fileInputStream,
#FormDataParam("file") FormDataContentDisposition fileMetaData) throws Exception
{
String UPLOAD_PATH = "D://Test/";
try
{
int read = 0;
byte[] bytes = new byte[1024];
OutputStream out = new FileOutputStream(new File(UPLOAD_PATH + fileMetaData.getFileName()));
while ((read = fileInputStream.read(bytes)) != -1)
{
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e)
{
throw new WebApplicationException("Error while uploading file. Please try again !!");
}
return Response.ok("Data uploaded successfully !!").build();
}
}
In the client side, you need to add support for the multipart/form-data feature which will register the needed reader and writer:
public class Test {
public void configureClient(ClientConfig config) {
config.register(MultiPartFeature.class);
}
public static void main(String[] args) {
DefaultClientConfig config = new DefaultClientConfig();
configureClient(config);
Client client = ClientBuilder.newClient(config);
WebTarget server = client.target("http://localhost:8080/repositories/file/upload");
// or alternatively at the WebTarget level
// server.register(MultiPartFeature.class);
// ...
}
}

Spring boot data not uploaded

I build spring boot application, but the problem is I want to upload images on the web browser but it does not work, I run the app on IntelliJ IDEA, here is the code: https://github.com/rmalav15/siamese-tf-java
please help, here is the code that backs the error (Unable to Enroll Due to some error)
package com.tensorflow.siamese.controllers;
import com.tensorflow.siamese.models.User;
import com.tensorflow.siamese.services.EnrollmentService;
import com.tensorflow.siamese.services.ImageProcessingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
#RestController
#RequestMapping("/enroll")
#Slf4j
public class EnrollmentController {
#Value("${images.save.path:src/main/resources/Images}")
private String path;
#Autowired
private EnrollmentService enrollmentService;
#RequestMapping(value = "/new", method = RequestMethod.POST)
ResponseEntity enrollNew(#RequestParam("name") String name,
#RequestParam("files") List<MultipartFile> images) {
try {
List<Path> imagePaths = new ArrayList<>();
for (MultipartFile file : images) {
imagePaths.add(ImageProcessingService.write(file, path));
}
User user = enrollmentService.enrollNew(imagePaths, name);
return ResponseEntity.ok(user);
} catch (Exception e) {
log.debug("Exception in enrollNew Apia", e);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Unable to Enroll Due to some error.");
}
}
}

How to convert HTML to PDF with working hyperlinks using docx4j?

I used Eclipse Luna 64bit, Maven, docx4j API for PDF conversion, template letter format on which I want my HTML code. This template is saved in my database.
I want to include a hyperlink in the PDF, so my users can on click this link and open it in their browser.
This is my main class:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.model.SelectItem;
import org.apache.commons.lang.StringUtils;
import org.docx4j.Docx4J;
import org.docx4j.XmlUtils;
import org.docx4j.convert.in.xhtml.XHTMLImporterImpl;
import org.docx4j.jaxb.Context;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.relationships.Namespaces;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.docx4j.wml.Body;
import org.docx4j.wml.BooleanDefaultTrue;
import org.docx4j.wml.Document;
import org.docx4j.wml.P;
import org.docx4j.wml.PPrBase;
import org.docx4j.wml.R;
import org.docx4j.wml.Text;
import org.primefaces.context.RequestContext;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.primefaces.model.UploadedFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LetterMaintenanceBean extends BaseManagedBean implements
Serializable {
public StreamedContent previewLetter() {
String content = this.letter.getHtmlContent();
String regex = "<a href=(\"[^\"]*\")[^<]*</a>"; //Digvijay
Pattern p = Pattern.compile(regex); //Digvijay
System.out.println("p: "+p);
Matcher m = p.matcher(content); //Digvijay
System.out.println("m: "+m);
content = m.replaceAll("<strong><u><span style=\"color:#0099cc\">$1</span></u></strong>"); //Digvijay
System.out.println("regex1: "+regex); //Digvijay
Map<String, String> previewExamples = this.getPreviewExamples(this.letter.getMessageTypeCode());
for (Entry<String, String> example : previewExamples.entrySet()) {
if (StringUtils.isNotBlank(example.getKey()) && StringUtils.isNotBlank(example.getValue())) {
content = content.replace(example.getKey(), example.getValue());
System.out.println("content after map date");
}
}
System.out.println("content1:: "+content);
if (!content.startsWith("<div>")) {
content = "<div>" + content + "</div>";
}
// Docx4j does not understand HTML codes for special characters. So replacing with Unicode values.
content = content.replace(" ", " ");
content = content.replace("’", "’");
content = content.replaceAll("</p>", "</p><br/>");
content = content.replaceAll("\"</span>", "</span>");
InputStream stream = null;
try {
System.out.println("content:"+content);
if (this.letter.getHtmlContent().getBytes() != null && this.letter.getWfTemplateId() != null) {
stream = new ByteArrayInputStream(this.HTMLToPDF(content.getBytes(), this.letter.getWfTemplateId()));
} else {
stream = new ByteArrayInputStream(this.HTMLToPDFWithoutTemplate(content.getBytes()));
}
StreamedContent file = new DefaultStreamedContent(stream, "application/pdf", this.letter.getLetterName() + ".pdf");
return file;
} catch (LetterMaintenanceException e) {
this.processServiceException(e);
StreamedContent file = new DefaultStreamedContent(
new ByteArrayInputStream(
"Unable to process your request. If the problem persists, please contact application support."
.getBytes()), "application/pdf", "error" + ".pdf");
return file;
} catch (Exception e) {
this.processGenericException(e);
StreamedContent file = new DefaultStreamedContent(
new ByteArrayInputStream(
"Unable to process your request. If the problem persists, please contact application support."
.getBytes()), "application/pdf", "error" + ".pdf");
return file;
}
}
This is my HTMLToPDF() method:
private byte[] HTMLToPDF(final byte[] htmlContent, final String templateId)
throws Docx4JException, LetterMaintenanceException {
LetterMaintenanceDelegate letterMaintenanceDelegate = new LetterMaintenanceDelegate();
Template template = letterMaintenanceDelegate.retrieveTemplateById(templateId);
if (template == null || template.getContent() == null) {
throw new LetterMaintenanceException("Could not retrieve template");
}
InputStream is = new ByteArrayInputStream(template.getContent());
WordprocessingMLPackage templatePackage = WordprocessingMLPackage.load(is);
// Convert HTML to docx
XHTMLImporterImpl XHTMLImporter = new XHTMLImporterImpl(templatePackage);
XHTMLImporter.setHyperlinkStyle("Hyperlink");
templatePackage
.getMainDocumentPart()
.getContent()
.addAll(XHTMLImporter.convert(new ByteArrayInputStream(htmlContent), null));
// Add content of content docx to template
templatePackage.getMainDocumentPart().getContent().addAll(templatePackage.getMainDocumentPart().getContent());
// Handle page breaks
templatePackage = this.handlePagebreaksInDocx(templatePackage);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Docx4J.toPDF(templatePackage, baos);
return baos.toByteArray();
}
}
In this code I am trying to convert HTML (with href tag) to PDF file and in the PDF output the hyperlink must work.
The current output of this program is a PDF but there are no working links in it.
How can I activate my links?

Java jax - rs program to accept files from external systems

I am trying to create a simple Java Jax-RS based webservice which accepts the file in a byte[] format or as a blob and pushes it to an FTP folder. This service is used by Salesforce to push files to directories via this Java API. For testing i have hosted this application in https://ftptransfer.herokuapp.com/myresource
I need to create a class which basically accepts files from external systems
package com.example;
import javax.ws.rs.Consumes;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.ws.rs.POST;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.media.multipart.FormDataContentDisposition;
import org.glassfish.jersey.media.multipart.FormDataParam;
#Path("sendFiles")
public class FileTransfer {
#POST
#Consumes({MediaType.MULTIPART_FORM_DATA})
public String uploadPdfFile( )
{
return "Uploaded successfully";
}
}
Can some help with any good reference to achieve this, as i have tried many approaches from different blogs but none helped me much.
I am able to achieve this in the following way
import org.apache.commons.net.ftp.FTPClient;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import javax.ws.rs.Consumes;
import javax.ws.rs.Path;
import java.io.InputStream;
import javax.ws.rs.POST;
#Path("sendFiles")
public class FileTransfer {
#POST
#Path("file")
#Consumes("*/*")
public String uploadPdfFile(InputStream fileInputStream)
{
FTPClient client = new FTPClient();
boolean login;
FileInputStream fis = null;
int read = 0;
byte[] bytes = new byte[1024];
OutputStream out;
try {
File file=new File("testhm001.txt");
out = new FileOutputStream(file);
while ((read = fileInputStream.read(bytes)) != -1)
{
out.write(bytes, 0, read);
}
out.flush();
out.close();
InputStream in = new FileInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder out1 = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
out1.append(line);
}
return "done";
}
}

UIMA Pipeline with Stanford NER

I have integrated Stanford NER in UIMA and developed a pipeline.
The pipeline contains a FileSystemCollectionReader,an NERAnnotator and a CasConsumer but the output so come isn't desired. In my input directory i have two files and after running the pipeline, i get two files as ouput but the second file is getting merged with the first file in second ouput. I don't know what's happening here.
The code for CasConsumer:
`
package org.gds.uima;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import org.apache.uima.UimaContext;
import org.apache.uima.analysis_component.AnalysisComponent_ImplBase;
import org.apache.uima.analysis_component.CasAnnotator_ImplBase;
import org.apache.uima.analysis_component.JCasAnnotator_ImplBase;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.cas.CAS;
import org.apache.uima.cas.CASException;
import org.apache.uima.cas.Type;
import org.apache.uima.cas.text.AnnotationFS;
import org.apache.uima.fit.component.CasConsumer_ImplBase;
import org.apache.uima.fit.component.JCasConsumer_ImplBase;
import org.apache.uima.fit.descriptor.ConfigurationParameter;
import org.apache.uima.fit.util.CasUtil;
import org.apache.uima.jcas.JCas;
import org.apache.uima.resource.ResourceInitializationException;
public class CasConsumer extends JCasConsumer_ImplBase
{
public final static String PARAM_OUTPUT="outputDir";
#ConfigurationParameter(name = PARAM_OUTPUT)
private String outputDirectory;
public final static String PARAM_ANNOTATION_TYPES = "annotationTypes";
enter code here
#ConfigurationParameter(name = PARAM_ANNOTATION_TYPES,defaultValue="String")
public List<String> annotationTypes;
public void initialize(final UimaContext context) throws ResourceInitializationException
{
super.initialize(context);
}
#Override
public void process(JCas jcas)
{
String original = jcas.getDocumentText();
try
{
String onlyText="";
JCas sofaText = jcas.getView(NERAnnotator.SOFA_NAME);
onlyText = sofaText.getDocumentText();
String name = UUID.randomUUID().toString().substring(20);
File outputDir = new File(this.outputDirectory+"/"+name);
System.out.print("Saving file to "+outputDir.getAbsolutePath());
FileOutputStream fos = new FileOutputStream(outputDir.getAbsoluteFile());
PrintWriter pw = new PrintWriter(fos);
pw.println(onlyText);
pw.close();
}
catch(CASException cae)
{
System.out.println(cae);
}
catch(FileNotFoundException fne)
{
System.out.print(fne);
}
}
}
`
}

Categories