i need to export a csv file in txt; i wanna use a pipe for separate fields.
My code is something like
String[] x = {its1, its2, its3, its4, its5 };
i need: {its1| its2| its3| its4| its5 }
ps. i'm in the controller of course.
#Controller
public class CSVFileDownloadController
{ #RequestMapping(value ="/downloadCSV")
public void downloadCSV(HttpServletResponse response) throws IOException {
String csvFileName = "books.csv";
response.setContentType("text/csv");
// creates mock data
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"",
csvFileName);
response.setHeader(headerKey, headerValue);
List<Book> listBooks = Arrays.asList();
// uses the Super CSV API to generate CSV data from the model data
ICsvBeanWriter csvWriter = new CsvBeanWriter(response.getWriter(),
CsvPreference.STANDARD_PREFERENCE);
String[] header = { "Title", "Description", "Author", "Publisher",
"isbn", "PublishedDate", "Price" };
csvWriter.writeHeader(header);
for (Book aBook : listBooks) {
csvWriter.write(aBook, header);
}
csvWriter.close();
}
}
Solved thanks #M.Deinum
You could join the array:
String result = String.join("|", x);
So I am using Java for my Server and Angular for the Client. I am currently working on a feature where you can select multiple files from a table and when you press on download, it generates a zip file and downloads it to your browser. As of right now, the server now creates the zip file and I can access it in the server files. All that is left to do is to make it download on the client's browser. (the zip file is deleted after the client downloads it)
After doing some research, I found out that you can use a fileOutputStream to do this. I also saw some tools like retrofit... I am using REST and this is what my code looks like. How would I achieve my goal as simply as possible?
Angular
httpGetDownloadZip(target: string[]): Observable<ServerAnswer> {
const params = new HttpParams().set('target', String(target)).set('numberOfFiles', String(target.length));
const headers = new HttpHeaders().set('token', this.tokenService.getStorageToken());
const options = {
headers,
params,
};
return this.http
.get<ServerAnswer>(this.BASE_URL + '/files/downloadZip', options)
.pipe(catchError(this.handleError<ServerAnswer>('httpGetZip')));
}
Java zipping method
public void getDownloadZip(String[] files, String folderName) throws IOException {
[...] // The method is huge but basically I generate a folder called "Download/" in the server
// Zipping the "Download/" folder
ZipUtil.pack(new File("Download"), new File("selected-files.zip"));
// what do I return ???
return;
}
Java context
server.createContext("/files/downloadZip", new HttpHandler() {
#Override
public void handle(HttpExchange exchange) throws IOException {
if (!handleTokenPreflight(exchange)) { return; }
System.out.println(exchange.getRequestURI());
Map<String, String> queryParam = parseQueryParam(exchange.getRequestURI().getQuery());
String authToken = exchange.getRequestHeaders().getFirst("token");
String target = queryParam.get("target") + ",";
String[] files = new String[Integer.parseInt(queryParam.get("numberOfFiles"))];
[...] // I process the data in this entire method and send it to the previous method that creates a zip
Controller.getDownloadZip(files, folderName);
// what do I return to download the file on the client's browser ????
return;
}
});
A possible approach to successfully download your zip file can be the described in the following paragraphs.
First, consider returning a reference to the zip file obtained as the compression result in your downloadZip method:
public File getDownloadZip(String[] files, String folderName) throws IOException {
[...] // The method is huge but basically I generate a folder called "Download/" in the server
// Zipping the "Download/" folder
File selectedFilesZipFile = new File("selected-files.zip")
ZipUtil.pack(new File("Download"), selectedFilesZipFile);
// return the zipped file obtained as result of the previous operation
return selectedFilesZipFile;
}
Now, modify your HttpHandler to perform the download:
server.createContext("/files/downloadZip", new HttpHandler() {
#Override
public void handle(HttpExchange exchange) throws IOException {
if (!handleTokenPreflight(exchange)) { return; }
System.out.println(exchange.getRequestURI());
Map<String, String> queryParam = parseQueryParam(exchange.getRequestURI().getQuery());
String authToken = exchange.getRequestHeaders().getFirst("token");
String target = queryParam.get("target") + ",";
String[] files = new String[Integer.parseInt(queryParam.get("numberOfFiles"))];
[...] // I process the data in this entire method and send it to the previous method that creates a zip
// Get a reference to the zipped file
File selectedFilesZipFile = Controller.getDownloadZip(files, folderName);
// Set the appropiate Content-Type
exchange.getResponseHeaders().set("Content-Type", "application/zip");
// Optionally, if the file is downloaded in an anchor, set the appropiate content disposition
// exchange.getResponseHeaders().add("Content-Disposition", "attachment; filename=selected-files.zip");
// Download the file. I used java.nio.Files to copy the file contents, but please, feel free
// to use other option like java.io or the Commons-IO library, for instance
exchange.sendResponseHeaders(200, selectedFilesZipFile.length());
try (OutputStream responseBody = httpExchange.getResponseBody()) {
Files.copy(selectedFilesZipFile.toPath(), responseBody);
responseBody.flush();
}
}
});
Now the problem is how to deal with the download in Angular.
As suggested in the previous code, if the resource is public or you have a way to manage your security token, including it as a parameter in the URL, for instance, one possible solution is to not use Angular HttpClient but an anchor with an href that points to your ever backend handler method directly.
If you need to use Angular HttpClient, perhaps to include your auth tokens, then you can try the approach proposed in this great SO question.
First, in your handler, encode to Base64 the zipped file contents to simplify the task of byte handling (in a general use case, you can typically return from your server a JSON object with the file content and metadata describing that content, like content-type, etcetera):
server.createContext("/files/downloadZip", new HttpHandler() {
#Override
public void handle(HttpExchange exchange) throws IOException {
if (!handleTokenPreflight(exchange)) { return; }
System.out.println(exchange.getRequestURI());
Map<String, String> queryParam = parseQueryParam(exchange.getRequestURI().getQuery());
String authToken = exchange.getRequestHeaders().getFirst("token");
String target = queryParam.get("target") + ",";
String[] files = new String[Integer.parseInt(queryParam.get("numberOfFiles"))];
[...] // I process the data in this entire method and send it to the previous method that creates a zip
// Get a reference to the zipped file
File selectedFilesZipFile = Controller.getDownloadZip(files, folderName);
// Set the appropiate Content-Type
exchange.getResponseHeaders().set("Content-Type", "application/zip");
// Download the file
byte[] fileContent = Files.readAllBytes(selectedFilesZipFile.toPath());
byte[] base64Data = Base64.getEncoder().encode(fileContent);
exchange.sendResponseHeaders(200, base64Data.length);
try (OutputStream responseBody = httpExchange.getResponseBody()) {
// Here I am using Commons-IO IOUtils: again, please, feel free to use other alternatives for writing
// the base64 data to the response outputstream
IOUtils.write(base64Data, responseBody);
responseBody.flush();
}
}
});
After that, use the following code in you client side Angular component to perform the download:
this.downloadService.httpGetDownloadZip(['target1','target2']).pipe(
tap((b64Data) => {
const blob = this.b64toBlob(b64Data, 'application/zip');
const blobUrl = URL.createObjectURL(blob);
window.open(blobUrl);
})
).subscribe()
As indicated in the aforementioned question, b64toBlob will look like this:
private b64toBlob(b64Data: string, contentType = '', sliceSize = 512) {
const byteCharacters = atob(b64Data);
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, {type: contentType});
return blob;
}
Probably you will need to slightly modify the httpGetDownloadZip method in your service to take into account the returned base 64 data - basically, change ServerAnswer to string as the returned information type:
httpGetDownloadZip(target: string[]): Observable<string> {
const params = new HttpParams().set('target', String(target)).set('numberOfFiles', String(target.length));
const headers = new HttpHeaders().set('token', this.tokenService.getStorageToken());
const options = {
headers,
params,
};
return this.http
.get<string>(this.BASE_URL + '/files/downloadZip', options)
.pipe(catchError(this.handleError<ServerAnswer>('httpGetZip')));
}
You could try using responseType as arraybuffer.
Eg:
return this.http.get(URL_API_REST + 'download?filename=' + filename, {
responseType: 'arraybuffer'
});
In My Project including both front end (angular) and back end (java).
We used the below solution ( hope it work for you ):
Angular:
https://github.com/eligrey/FileSaver.js
let observable = this.downSvc.download(opts);
this.handleData(observable, (data) => {
let content = data;
const blob = new Blob([content], { type: 'application/pdf' });
saveAs(blob, file);
});
Java:
public void download(HttpServletRequest request,HttpServletResponse response){
....
response.setHeader("Content-Disposition",
"attachment;filename=\"" + fileName + "\"");
try (
OutputStream os = response.getOutputStream();
InputStream is = new FileInputStream(file);) {
byte[] buf = new byte[1024];
int len = 0;
while ((len = is.read(buf)) > -1) {
os.write(buf, 0, len);
}
os.flush();
}
You can still use HttpServletRequest on the server...
Then get its OutputStream and write to it.
#RequestMapping(method = RequestMethod.POST , params="action=downloadDocument")
public String downloadDocument(#RequestParam(value="documentId", required=true) String documentId,
HttpServletRequest request,
HttpServletResponse response )
{
try {
String docName = null;
String documentSavePath = getDocumentSavePath();
PDocument doc = mainService.getDocumentById(iDocumentId);
if(doc==null){
throw new RuntimeException("document with id: " + documentId + " not found!");
}
docName = doc.getName();
String path = documentSavePath + ContextUtils.fileSeperator() + docName;
response.setHeader("Content-Disposition", "inline;filename=\"" + docName + "\"");
OutputStream out = response.getOutputStream();
response.setContentType("application/word");
FileInputStream stream = new FileInputStream(path);
IOUtils.copy(stream, out);
out.flush();
out.close();
} catch(FileNotFoundException fnfe){
logger.error("Error downloading document! - document not found!!!! " + fnfe.getMessage() , fnfe);
} catch (IOException e) {
logger.error("Error downloading document!!! " + e.getMessage(),e);
}
return null;
}
I use MimeMessageHelper.
I try send this code:
public void sendingMessage(String toAddress, List<String> list) throws MessagingException {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setTo(toAddress);
for (String properties : list) {
String[] split = properties.split("_");
String name = split[0];
String quantity = split[1];
String photo = split[2];
//FileSystemResource file = new FileSystemResource(new File(imagePath+photo));
//helper.addAttachment("ThankYou.jpg", file);
helper.setText(name+" - "+quantity+"pieces.");
helper.setText(quantity);
helper.setSentDate(new Date());
helper.setText("<img src='+imagePath+photo+'>"+"---"+name+"****"+quantity, true);
}
I recieve List<String> list, as:
[glenDev_5_whisky/glenDeveron.jpg, Tomintoul_3_whisky/Tomintoul.jpg, Alfa Suf_5_whisky/OldPulteney.jpg]
I have two problems:
I don't recieve image if I use
helper.setText("<img src='+imagePath+photo+'>"+"---"+name+"****"+quantity, true);
But if I use this code:
FileSystemResource file = new FileSystemResource(new File(imagePath+photo));
helper.addAttachment("ThankYouForTheOrder.jpg", file);
I receive all images from List<String> list
I can't understand how I can will send several image+name+ some text, that will describe this image.
For example: One image, his name and describe, another image his name and describe... etc.
I have created an XML using STAX and XMLStreamWriter. It works fine.
I need to merge two xml together. The problem that I am facing is the patient Pojo returns me XML containing all the patient information is below
<Patient>
<SocialSecurity>3333344</SocialSecurity>
<Name>
<LastName>pillai</LastName>
<FirstName>dhanya</FirstName>
<Name>
<Patient>
I need to add this into existing XML after <proID> like merging.
<?xml version="1.0" ?>
<Validate>
<proID>123</prodID>
</Validate>
Please advice
The answer is as below
public static void main(String[] args) throws Throwable {
XMLEventWriter eventWriter;
XMLEventFactory eventFactory;
XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
eventWriter = outputFactory.createXMLEventWriter(bos);
eventFactory = XMLEventFactory.newInstance();
XMLEvent newLine = eventFactory.createDTD("\n");
// Create and write Start Tag
StartDocument startDocument = eventFactory.createStartDocument();
eventWriter.add(startDocument);
eventWriter.add(newLine);
StartElement configStartElement = eventFactory.createStartElement("","","Message");
eventWriter.add(configStartElement);
eventWriter.add(newLine);
XMLInputFactory inputFactory = XMLInputFactory.newFactory();
PatientDetails patientDetails= new PatientDetails();// Here I have called an POJO that return String and we add
String xml = patientDetails.getPatientDetails();
Source src = new StreamSource(new java.io.StringReader(xml));
XMLEventReader test = inputFactory.createXMLEventReader(src);
while(test.hasNext()){
XMLEvent event= test.nextEvent();
//avoiding start(<?xml version="1.0"?>) and end of the documents;
if (event.getEventType()!= XMLEvent.START_DOCUMENT && event.getEventType() != XMLEvent.END_DOCUMENT)
eventWriter.add(event);
// eventWriter.add(newLine);
test.close();
} //end of while
eventWriter.add(eventFactory.createEndElement("", "", "Message"));
eventWriter.add(newLine);
eventWriter.add(eventFactory.createEndDocument());
eventWriter.close();
System.out.println(bos.toString());
}//end of main
I am writing a program in Java (I am using Ubuntu). I am using Jodconverter to convert the document to PDF. I have to convert the document to landscape mode but I have read that Jodconverter doesn't support orientation changes. I also tried with OpenOffice API but I am facing the same issue.
Is there any Java library that does conversion to landscape?
From a similar question regarding using Jodconverter with an Open Office document:
http://groups.google.com/group/jodconverter/browse_thread/thread/dc96df64c7d60ada/c1692fee92513b7a
Short answer: you can't. The page orientation is a property of the
document (menu Format > Page in Calc), not a PDF export option. So it
should be set already in the XLS document.
Export to PDF and then use a PDF library like PDFbox to rotate the pages by 90 degrees.
Try PDPage.setRotation(int) on all pages (PDDocument.getDocumentCatalog().getAllPages()).
I have found the solution. I have converted document to landscape pdf using open office API for java. Here is the code for the same.
System.out.println("starting...");
String oooExeFolder = "/usr/lib/openoffice/program";
XComponentContext xContext = BootstrapSocketConnector.bootstrap(oooExeFolder);
XMultiComponentFactory xMCF = xContext.getServiceManager();
Object oDesktop = xMCF.createInstanceWithContext("com.sun.star.frame.Desktop", xContext);
XComponentLoader xCLoader = (XComponentLoader) UnoRuntime.queryInterface(XComponentLoader.class, oDesktop);
System.out.println("loading ");
PropertyValue[] printerDesc = new PropertyValue[1];
printerDesc[0] = new PropertyValue();
printerDesc[0].Name = "PaperOrientation";
printerDesc[0].Value = PaperOrientation.LANDSCAPE;
// Create a document
XComponent document = xCLoader.loadComponentFromURL(loadUrl, "_blank", 0, printerDesc);
// Following property will convert doc into requested orientation.
XPrintable xPrintable = (XPrintable) UnoRuntime.queryInterface(XPrintable.class, document);
xPrintable.setPrinter(printerDesc);
PropertyValue[] conversionProperties = new PropertyValue[3];
conversionProperties[1] = new PropertyValue();
conversionProperties[1].Name = "FilterName";
conversionProperties[1].Value = "writer_pdf_Export";//
conversionProperties[0] = new PropertyValue();
conversionProperties[0].Name = "Overwrite ";
conversionProperties[0].Value = new Boolean(true);
System.out.println("closing");
XStorable xstorable = (XStorable) UnoRuntime.queryInterface(XStorable.class, document);
xstorable.storeToURL(storeUrl, conversionProperties);
System.out.println("closing");
XCloseable xcloseable = (XCloseable) UnoRuntime.queryInterface(XCloseable.class, document);
xcloseable.close(false);
Try overriding OfficeDocumentConverter
OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager) {
private Map<String, Object> createDefaultLoadProperties() {
Map<String, Object> loadProperties = new HashMap<String, Object>();
loadProperties.put("Hidden", true);
loadProperties.put("ReadOnly", true);
loadProperties.put("UpdateDocMode", UpdateDocMode.QUIET_UPDATE);
return loadProperties;
}
#Override
public void convert(File inputFile, File outputFile, DocumentFormat outputFormat) throws OfficeException {
String inputExtension = FilenameUtils.getExtension(inputFile.getName());
DocumentFormat inputFormat = getFormatRegistry().getFormatByExtension(inputExtension);
inputFormat.setLoadProperties(Collections.singletonMap("PaperOrientation", PaperOrientation.LANDSCAPE));
StandardConversionTask conversionTask = new StandardConversionTask(inputFile, outputFile, outputFormat) {
#Override
protected void modifyDocument(XComponent document) throws OfficeException {
PropertyValue[] printerDesc = OfficeUtils.toUnoProperties(Collections.singletonMap("PaperOrientation", PaperOrientation.LANDSCAPE));
XPrintable xPrintable = cast(XPrintable.class, document);
try {
xPrintable.setPrinter(printerDesc);
} catch (com.sun.star.lang.IllegalArgumentException e) {
logger.error(e.getMessage());
}
super.modifyDocument(document);
}
};
conversionTask.setDefaultLoadProperties(createDefaultLoadProperties());
conversionTask.setInputFormat(inputFormat);
officeManager.execute(conversionTask);
}
};