Reading from a file but getting null in java - java

I want to read from a file and store it in a string.
This is my method:
public static String createJsonFileFromNode(String filename, JsonNode root) {
String dirName = "src/test/resources/json/";
File dir = new File (dirName);
File actualFile = new File (dir, filename);
try (Writer writer = new BufferedWriter(new OutputStreamWriter (
new FileOutputStream(actualFile), "utf-8")))
{
writer.write(String.valueOf(root));
log.info(actualFile.getPath());
String updatedJson = FileUtils.readFileToString(actualFile, "UTF-8");
return updatedJson;
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
return "";
} catch (FileNotFoundException e) {
e.printStackTrace();
return "";
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
I have two problems in the above method:
In String dirName = "src/test/resources/json/" I am passing an entire path, which I dont want to. I want to pass it as "/json/"
updatedJson is retuning null even though the file is getting saved to the particular direction. Not sure what is going on. Can someone please help me?
Thank you.

Related

Uncompressing base64 gzip on S3 and saving to local file system

I am a Java bonehead/newbie so please be gentle. I have two functions which I realize are somewhat incompatible:
saveS3toFilesystem - takes a InputStream from AWS S3 and saves it to the local filesystem as a file
decompress - takes a string and decodes the base64 encoding and the decompresses the gzip compression.
I really want these two to work in concert to achieve the result of the file saved to the filesystem being the uncompressed file but I realize that my "decompress" function should probably be changed to receive a stream rather than a string but sadly I'm just a "cutter and paster" in the world of Java these days.
Here are my two functions as they are now:
private void saveS3toFilesystem(String filename, String bucketName, String localFilename) {
S3Object obj = s3.getObject(bucketName, filename);
InputStream in = obj.getObjectContent();
try {
Files.createDirectories(Paths.get(localFilename.replace(this.FILE_EXTENSION, "")));
Files.copy(in, Paths.get(localFilename));
this.logger.log("Input file has been placed in local filesystem for ITMS to pick up: " + localFilename + "\n");
} catch (IOException err) {
this.logger.log("There was a problem saving the file to " + localFilename);
err.printStackTrace();
} finally {
try {
in.close();
} catch (IOException err) {
err.printStackTrace();
}
}
return;
}
and then ...
private String decompress(String compressedZip) {
byte[] decodedBytes = Base64.getDecoder().decode(compressedZip);
String result = null;
GZIPInputStream zip = null;
try {
zip = new GZIPInputStream(new ByteArrayInputStream(decodedBytes));
result = IOUtils.toString(zip);
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(zip);
}
return result;
}
Can anyone please help me to achieve the dream? Happy to do it with streams, strings, or any method that will work. Sadly I can't afford atm to up my Java skills enough to grok the solution myself.
Many thanks in advance.
Based on the following APIs :
Base64.Decoder and GZIPInputStream (look at the wrap method on the former and the constructors on the latter), the decompress method can be overloaded as follows:
private String decompress(InputStream compressedStream) {
InputStream decodingStream = Base64.getDecoder().wrap(compressedStream);
String result = null;
GZIPInputStream zip = null;
try {
zip = new GZIPInputStream(decodingStream);
result = IOUtils.toString(zip);
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(zip);
}
return result;
}
And finally, the changes to saveS3toFilesystem are as follows :
private void saveS3toFilesystem(String filename, String bucketName, String localFilename) {
S3Object obj = s3.getObject(bucketName, filename);
InputStream in = obj.getObjectContent();
// decoding the inputstream via decode into a string, which is then
// used in order to create an inputstream of decoded data
InputStream decodedStream =
new ByteArrayInputStream(decompress(in).getBytes(StandardCharsets.UTF_8));
try {
Files.createDirectories(Paths.get(localFilename.replace(this.FILE_EXTENSION, "")));
Files.copy(decodedStream, Paths.get(localFilename));
this.logger.log("Input file has been placed in local filesystem for ITMS to pick up: " + localFilename + "\n");
} catch (IOException err) {
this.logger.log("There was a problem saving the file to " + localFilename);
err.printStackTrace();
} finally {
try {
in.close();
} catch (IOException err) {
err.printStackTrace();
}
}
return;
}

How to create KMZ file from KML on the fly using Java

I am trying to create kmz file from kml file on the fly and render it as a stream of bytes in web application.
But when I downloaded generated kmz file, I couldn't open it using archive manager on Ubuntu.
I view similar questions on this site, but it don't work.
Can someone help me and explain what I do wrong?!
This is my code.
#Public public void retrieveKmlInOldFormat() {
File file = new File(Play.applicationPath+"/"+Play.configuration.getProperty("web.content", "../bspb-web")+"/map/map.kml");
String kmlFileContent = null;
try {
String kmlUrl = file.toURI().toURL().toString();
kmlFileContent = BSPBKml2OldFormatConverter.toOldKml(
kmlParserLocal.load(kmlUrl));
} catch (MalformedURLException e) {
e.printStackTrace();
}
String zippedFileName = "old_fmt_map.kmz";
String zippedKml = compressKmlFile(kmlFileContent,zippedFileName);
response.setContentTypeIfNotSet("application/vnd.google-earth.kmz");
renderBinary(new ByteArrayInputStream(zippedKml.getBytes()),zippedFileName);
return;
}
Compress method code:
private String compressKmlFile(String kmlFileContent,String zipEntryName){
String zippedContent = null;
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
ZipOutputStream zipStream = new ZipOutputStream(new
BufferedOutputStream(byteStream));
ZipEntry zipEntry = null;
zipEntry = new ZipEntry("doc.kml");
try {
zipEntry.setSize(kmlFileContent.getBytes("UTF-8").length);
zipStream.putNextEntry(zipEntry);
zipStream.write(kmlFileContent.getBytes("UTF-8"));
zipStream.closeEntry();
zippedContent = new String(byteStream.toByteArray(),"UTF-8");
} catch (IOException e) {
logger.error("Error while zipping kml file content");
}
finally {
try {
byteStream.close();
zipStream.close();
} catch (IOException e) {
logger.error(e.getMessage());
}
}
return zippedContent;
}
The problem is about downloaded corrupted kmz archive. This problem can be resolved by using output stream of http response as constructor argument for ZipOutputStream class.
Solution is in this code.
#Public public void retrieveKmlInOldFormat(){
File file = new File(Play.applicationPath+"/"+Play.configuration.getProperty("web.content", "../bspb-web")+"/map/map.kml");
String kmlFileContent = null;
try {
String kmlUrl = file.toURI().toURL().toString();
kmlFileContent = BSPBKml2OldFormatConverter.toOldKml(kmlParserLocal.load(kmlUrl));
} catch (MalformedURLException e) {
e.printStackTrace();
}
response.setContentTypeIfNotSet("application/vnd.google-earth.kmz");
response.setHeader("Content-Disposition", "attachment; filename=\"old_fmt_map.kmz\"");
renderAsKmz(response, kmlFileContent,"old_fmt_map.kml");
return;
}
private void renderAsKmz(Response response,String kmlFileContent,String zipEntryName){
ZipOutputStream zipStream = new ZipOutputStream(response.out);
ZipEntry zipEntry = new ZipEntry(zipEntryName);
try {
zipStream.putNextEntry(zipEntry);
zipStream.write(kmlFileContent.getBytes());
} catch (IOException e) {
logger.error("Error while zipping kml file content : " + e.getMessage());
}
finally {
try {
zipStream.closeEntry();
zipStream.close();
} catch (IOException e) {
logger.error("Error while closing zipped stream : " + e.getMessage());
}
}

XmlReader returning null on all occasions

i have a code which is to get dat from active mq and display the data on Rss feed, but the code give me no data on the feed, i get an empty list and the reason seems to be that XmlReader reader= null; i have set this line an dthe reder seems to be null during the whole execution.
public List<RssFeedMessage> readRssFeeds(#PathVariable String sourceName) {
XmlReader reader = null;
RssFeedMessage rssFeedMessage = null;
StringBuffer feedUrl = new StringBuffer("http://").append(ipaddress).append(":")
.append(port).append("/admin/queueBrowse/").append(sourceName).append("?view=rss&feedType=rss_2.0");
List<RssFeedMessage> rssFeedMessages = new ArrayList<RssFeedMessage>();
try {
URL url = new URL(feedUrl.toString());
reader = new XmlReader(url);
SyndFeed feedMsg = new SyndFeedInput().build(reader);
List<SyndEntry> feedEntries = feedMsg.getEntries();
for (SyndEntry entry : feedEntries) {
rssFeedMessage = new RssFeedMessage();
rssFeedMessage.setTitle(entry.getTitle());
rssFeedMessage.setDescription(entry.getDescription().getValue());
rssFeedMessage.setDate(OptimerUtil.simpleDateHourTimeInd.format(entry.getPublishedDate()));
rssFeedMessages.add(rssFeedMessage);
}
} catch(IOException e){
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (FeedException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
}
return rssFeedMessages;
}
}
it just exits coz reader remains null the wole time an i get io exception on reader = new XmlReader(url);
Check what feedUrl contains in line URL url = new URL(feedUrl.toString());
There is probably a problem with the string.
Also, make you you manage conditions like String equals null or unreachable, before parsing it

save a created propertyfile in specific folder

How can I save a prop file in a specific folder for example,
now it is saved in the root I guess, but it needs to be in the same folder as the class where it is created.
I also want to know how to load it. If it possible to load a properties file easily from the root then it is okay as well to save it in the root.
code creating the file, first 2 lines with // ( = make code work now without using prop file), class name = Providers
public static DataAccessProvider createProvider (URL url) {
//MovieDAOOnline mdaoOn = new MovieDAOOnline();
//mdaoOn.setUrl(url);
Properties prop = new Properties();
OutputStream output = null;
try {
output = new FileOutputStream("config.properties");
// set the properties value
prop.setProperty("uri", url.toString());
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return new OnlineProvider();
}
code for getting the file, first line in comment needs to be changed to get uri from propertie:
public Movie getMovie(int id) throws DataAccessException{
//StringBuilder builder = new StringBuilder(url.toString());
builder.append("movies.xml");
MovieConfigRead mcr = new MovieConfigRead();
List<Movie> film = null;
try {
film = mcr.geefMovies(builder.toString());
} catch (JAXBException e) {
throw new DataAccessException();
} catch (MalformedURLException e) {
throw new DataAccessException();
}
for (Movie movie : film) {
if (movie.getId() == id) {
return movie;
}
}
return null;
}

Unable to Encoding UTF-8

i have an very strange behavoir in my android app.
The user have three ways to write a file: Excel, txt and pdf.
In my string it is possible that i have character just like this: "ä", "ß".
For the excel and txt File i use the following code to write:
FileWriter fWriter;
try
{
String extr = sdCard.toString();
File mFolder = new File(extr + "/" + FileUtil.TEST_DICTONARY);
if (!mFolder.exists())
{
mFolder.mkdir();
}
File mFile = new File(mFolder.getAbsolutePath(), FileUtil.TEXT_FILENAME);
mFile.delete();
String appDataToWrite = createAppDataToWriteToFile(appData, resources);
fWriter = new FileWriter(mFile, false);
fWriter.write(appDataToWrite);
fWriter.flush();
fWriter.close();
}
catch (NotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
This works perfect, the encoding is i excepted. If i use the same for the pdf file then it's not the right encoding. After searching in SO i use the following:
try
{
String extr = sdCard.toString();
File mFolder = new File(extr + "/" + FileUtil.TEST_DICTONARY);
if (!mFolder.exists())
{
mFolder.mkdir();
}
File mFile = new File(mFolder.getAbsolutePath(), FileUtil.PDF_FILENAME);
mFile.delete();
String appDataToWrite = createAppDataToWriteToPdf(appData, resources);
FileOutputStream fos = new FileOutputStream(mFile, false);
OutputStreamWriter char_output = new OutputStreamWriter(fos, Charset.forName("UTF-8").newEncoder());
char_output.write(appDataToWrite);
char_output.flush();
char_output.close();
}
catch (NotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
I have no idea why this getting wrong. For your information, I'm using the following library for generating the pdf http://coderesearchlabs.com/androidpdfwriter/
I have debug the code and a can see that the OutputStreamWriter getting the right input.
Any suggestions?
Thanks,
Manu

Categories