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();
}
Related
Getting response from the POST api call from which getting byte[] which i am writing using output stream but xslx file getting corrupted and PDF out as blank. Belo is the common code that i use to write a file.
public File writeToFile(String fileName, byte[] fileContent) {
var outputFile = new File("path", fileName);
try (var outStream = new FileOutputStream(outputFile)) {
outStream.write(fileContent);
outStream.flush();
} catch (Exception e) {
throw new IOException("Error writing to file: " + outputFile.getAbsolutePath());
}
return outputFile;
}
Thanks in Advance
I'm using this within an application where writing to a file is not possible. The data is always in streams. I get the XLSX file in an inputstream and I would like to set a password and write it to an outputstream.
public void encrptXslxFile(InputStream inStream, OutputStream outStream){
POIFSFileSystem fs = null;
EncryptionInfo info = null;
OutputStream fos;
OPCPackage opc = null;
try {
info = new EncryptionInfo(EncryptionMode.agile);
Encryptor enc = info.getEncryptor();
enc.confirmPassword("coffee");
//inStream = new FileInputStream("C:\\ProjectWork\\Community\\excelfile.xlsx");
fs = new POIFSFileSystem();
opc = OPCPackage.open(inStream); //from parameter
OutputStream os = enc.getDataStream(fs);
opc.save(os);
os.close();
//fos = new FileOutputStream("C:\\ProjectWork\\Community\\excelfilepwd.xlsx");
//fs.writeFilesystem(fos);
//fos.close();
fs.writeFilesystem(outStream); // from parameter
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
While reading from the file and writing to the file, it encrypts fine. But if I use the function and then get the outputstream, and later write it, it creates a zero kb file.
Is this even possible?
I tested with the code below to makes sure the inputstream is good.
public void encrptXslxFile(InputStream inStream, OutputStream outStream){
try {
IOUtils.copy(inStream, outStream);
} catch (IOException e) {
e.printStackTrace();
}
}
I was able to write the outputstream to a file.
Since I cannot create files and POI internally uses files, I had to specifically set the temp directory for POI to use.
TempFile.setTempFileCreationStrategy(new TempFileCreationStrategy() {
#Override
public File createTempFile(String prefix, String suffix) throws IOException {
// check dir exists, make if doesn't
if(!fileTempDir.exists()){
fileTempDir.mkdir();
fileTempDir.deleteOnExit();
}
File newFile = File.createTempFile(prefix, suffix, fileTempDir);
return newFile;
}
#Override
public File createTempDirectory(String strPath) throws IOException {
if(!fileTempDir.exists()){
fileTempDir.mkdir();
fileTempDir.deleteOnExit();
return fileTempDir;
}else {
return Files.createTempDirectory(strPath).toFile();
}
}
});
This worked for me.
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
I am creating Restful web service that accepts any file and saves it into filesystem. I am using Dropwizard to implement the service and Postman/RestClient to hit the request with data. I am not creating multipart (form-data) request.
Every thing is working fine except the file saved has first character missing. Here is my code for calling the service method and saving it into file system:
Input Request:
http://localhost:8080/test/request/Sample.txt
Sample.txt
Test Content
Rest Controller
#PUT
#Consumes(value = MediaType.WILDCARD)
#Path("/test/request/{fileName}")
public Response authenticateDevice(#PathParam("fileName") String fileName, #Context HttpServletRequest request) throws IOException {
.......
InputStream inputStream = request.getInputStream();
writeFile(inputStream, fileName);
......
}
private void writeFile(InputStream inputStream, String fileName) {
OutputStream os = null;
try {
File file = new File(this.directory);
file.mkdirs();
if (file.exists()) {
os = new FileOutputStream(this.directory + fileName);
logger.info("File Written Successfully.");
} else {
logger.info("Problem Creating directory. File can not be saved!");
}
byte[] buffer = new byte[inputStream.available()];
int n;
while ((n = inputStream.read(buffer)) != -1) {
os.write(buffer, 0, n);
}
} catch (Exception e) {
logger.error("Error in writing to File::" + e);
} finally {
try {
os.close();
inputStream.close();
} catch (IOException e) {
logger.error("Error in closing input/output stream::" + e);
}
}
}
In output, file is saved but first character from the content is missing.
Output:
Sample.txt:
est Content
In above output file, character T is missing and this happens for all the file formats.
I don't know what point I am missing here.
Please help me out on this.
Thank You.
I have a problem with file encoding. I have a method which exports my DB to a XML in a format I created. The problem is that the file is created with ANSI encoding and I need UTF-8 encoding (some spanish characters aren't shown propperly on ANSI).
The XML file is generated from a StringBuilder object: I write the data from my DB to this StringBuilder object and when I have copied all the data I create the file.
Any help is gratefully received. Thanks in advace.
Edit: This is part of my source:
XMLBuilder class:
...
public XmlBuilder() throws IOException {
this.sb = new StringBuilder();
}
...
public String xmlBuild() throws IOException{
this.sb.append(CLOSE_DB);
return this.sb.toString();
}
...
Service class where I generate the XML file:
XmlBuilder xml = new XmlBuilder();
... (adding to xml)...
xmlString = xml.build();
file = createXml(xmlString);
...
createXml:
public File createXml(String textToFile) {
File folder = new File("xml/exported/");
if (!folder.exists()) {
folder.mkdirs();
}
file = new File("xml/exported/exportedData.xml");
try (FileOutputStream fop = new FileOutputStream(file)) {
// if file doesn't exists, then create it
if (!file.exists()) {
file.createNewFile();
}
//if file exists, then delete it and create it
else {
file.delete();
file.createNewFile();
}
// get the content in bytes
byte[] contentInBytes = textToFile.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
return file;
}
File file = new File("file.xml");
Writer writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
writer.write("<file content>");
writer.close();