Use images in Java Beans - java

I try to create a PDF with iText within my JSP-Application and want to insert an image.
The file is located in my webapp-directory under:
http://localhost:8087/Buran/Symbols/Logos/dobi1.jpg
It's no problem to use it in html or jsp-files but within the bean it just does not work. To get the correct path by trial and error I created a test-file to see from which directory I had to start. Unfortunately that's not really what I expected it to be:
./apache-tomcat-7.0.41/bin/testfile.test
I got a recommendation to use:
private final String dobiurl = "/Buran/Symbols/Logos/dobi1.jpg";
URLConnection connection;
/**/
try {
connection = new URL(dobiurl).openConnection();
} catch (IOException ex) {
Logger.getLogger(Etikette.class.getName()).log(Level.SEVERE, null, ex);
}
But just cause errors...

Related

Why do I get NullPointerException when trying to access resource file?

I want to make so a file in the program is packaged in the jar file because it is needed in my program. It is the firebase credentials file. I read that I need to add it to the resource folder but now I cannot access it because I get NullPointerException. I think the path is valid and everything seems okay but I get null every time. Here is the code:
ClassLoader classLoader = EmailSender.class.getClassLoader();
File file = new File(Objects.requireNonNull(classLoader.getResource("/parkingsystem-cf164-firebase-adminsdk-5jjuk-2be72bfcce.json")).getFile());
And here is the code structure:
code structure
If there is another method to add file to jar I am open to hear it, it is just what I found on the Internet but it does not work for me. Any help is appreciated!
Edit: So apparently it works when the / is removed but then I need to convert it to FileInputStream and there I get FileNotFoundExcpetion. The rest of the code:
FileInputStream serviceAccount = null;
try {
serviceAccount = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
FirebaseOptions options = null;
try {
options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.fromStream(serviceAccount))
.build();
} catch (IOException e) {
e.printStackTrace();
}

Can static content on spring-boot-web application be dynamic (refreshed)?

I am still searching around this subject, but I cannot find a simple solution, and I don't sure it doesn't exist.
Part 1
I have a service on my application that's generating an excel doc, by the dynamic DB data.
public static void
notiSubscribersToExcel(List<NotificationsSubscriber>
data) {
//generating the file dynamically from DB's data
String prefix = "./src/main/resources/static";
String directoryName = prefix + "/documents/";
String fileName = directoryName + "subscribers_list.xlsx";
File directory = new File(directoryName);
if (! directory.exists()){
directory.mkdir();
// If you require it to make the entire directory path including parents,
// use directory.mkdirs(); here instead.
}
try (OutputStream fileOut = new FileOutputStream(fileName)) {
wb.write(fileOut);
fileOut.close();
wb.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Part 2
I want to access it from the browser, so when I call it will get downloaded.
I know that for the static content, all I need to do is to call to the file, from the browser like that:
http://localhost:8080/documents/myfile.xlsx
After I would be able to do it, all I need is to create link to this url from my client app.
The problem -
Currently if I call to the file as above, it will download only the file which have been there in the compiling stage, but if I am generating a new files after the app is running the content won't be available.
It seems that the content is (as it's called) "static" and cannot be changed after startup.
So my question is
is there is a way to define a folder on the app structure that will be dynamic? I just want to access the new generated file.
BTW I found this answer and others which doing configuration methods, or web services, but I don't want all this. And I have tried some of them, but the result is the same.
FYI I don't bundle my client app with the server app, I run them from different hosts
The problem is to download the file with the dynamic content from a Spring app.
This can be solved with Spring BOOT. Here is the solution as shown in this illustration - when i click Download report, my app generates a dynamic Excel report and its downloaded to the browser:
From a JS, make a get request to a Spring Controller:
function DownloadReport(e){
//Post the values to the controller
window.location="../report" ;
}
Here is the Spring Controller GET Method with /report:
#RequestMapping(value = ["/report"], method = [RequestMethod.GET])
#ResponseBody
fun report(request: HttpServletRequest, response: HttpServletResponse) {
// Call exportExcel to generate an EXCEL doc with data using jxl.Workbook
val excelData = excel.exportExcel(myList)
try {
// Download the report.
val reportName = "ExcelReport.xls"
response.contentType = "application/vnd.ms-excel"
response.setHeader("Content-disposition", "attachment; filename=$reportName")
org.apache.commons.io.IOUtils.copy(excelData, response.outputStream)
response.flushBuffer()
} catch (e: Exception) {
e.printStackTrace()
}
}
This code is implemented in Kotlin - but you can implement it as easily in Java too.

Android - Unhandled java.net.MalformedURLException

I'm getting a MalformedURLException some code in my Android Studio project. My aim is to get and display an image from a web page, and the URL seems to be fine, but it's giving me this error.
I have already put the code in a try,catch, but that is still giving me the error.
Here is the code to grab the image and display it:
try
{
url = new URL(items.get(position).getLink());
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
}
catch (IOException e)
{
throw new RuntimeException("Url Exception" + e);
}
holder.itemTitle.setText(items.get(position).getTitle());;
holder.itemHolder.setBackgroundDrawable(new BitmapDrawable(bmp));
items.get(position).getLink() is meant to get the link that is being displayed in a ListView, but even something like URL url = new URL("https://www.google.com") doesn't work.
Thanks.
your url is formatted without the protocol at the beginning try
url = new URL("http://"+items.get(position).getLink());
sometimes the url string may have special characters, in which case you need to encode it properly please see this.
And also, the url you posted in the comment is not an image.
it is exception beacuse of url class
add antoher catch like
catch (MalformedURLException e) {
e.printStackTrace();
}
Just click alt+enter and then import try catch section... this helped me...

Writing to a file inside of a jar

I am having a problem writing to a .xml file inside of my jar. When I use the following code inside of my Netbeans IDE, no error occurs and it writes to the file just fine.
public void saveSettings(){
Properties prop = new Properties();
FileOutputStream out;
try {
File file = new File(Duct.class.getResource("/Settings.xml").toURI());
out = new FileOutputStream(file);
prop.setProperty("LAST_FILE", getLastFile());
try {
prop.storeToXML(out,null);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.toString());
}
try {
out.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.toString());
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.toString());
}
}
However, when I execute the jar I get an error saying:
IllegalArguementException: uri is not hierachal
Does anyone have an idea of why it's working when i run it in Netbeans, but not working when i execute the jar. Also does anyone have a solution to the problem?
The default class loader expects the classpath to be static (so it can cache heavily), so this approach will not work.
You can put Settings.xml in the file system if you can get a suitable location to put it. This is most likely vendor and platform specific, but can be done.
Add the location of the Settings.xml to the classpath.
I was also struggling with this exception. But finally found out the solution.
When you use .toURI() it returns some thing like
D:/folderName/folderName/Settings.xml
and hence you get the exception "URI is not hierarchical"
To avoid this call the method getPath() on the URI returned, which returns something like
/D:/folderName/folderName/Settings.xml
which is now hierarchical.
In your case, the 5th line in your code should be
File file = new File(Duct.class.getResource("/Settings.xml").toURI().getPath());

Accessing a PDF in Jar

I'm creating a Java application using Netbeans. From the 'Help' Menu item, I'm required to open a PDF file. When I run the application via Netbeans, the document opens, but on opening via the jar file, it isn't opening. Is there anything that can be done?
m_aboutItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Runtime rt = Runtime.getRuntime();
URL link2=getClass().getResource("/newpkg/Documentation.pdf");
String link=link2.toString();
link=link.substring(6);
System.out.println(link);
System.out.println(link2);
String link3="E:/new/build/classes/newpkg/Documentation.pdf";
try {
Process proc = rt.exec("rundll32.exe url.dll,FileProtocolHandler " + link3);
} catch (IOException ex) {
Logger.getLogger(Menubar1.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
The two outputs are as follows:
E:/new/build/classes/newpkg/Documentation.pdf
file:/E:/new/build/classes/newpkg/Documentation.pdf
Consider the above code snippet. On printing 'link',we can see that it is exactly same as the hard coded 'link3'. On using the hard coded 'link3' , the PDF file gets opened from jar application. But when we use link, though it is exactly same as 'link3', the PDF doesn't open.
This is most likely related to the incorrect PDF resource loading. In the IDE you have the PDF file either as part of the project structure or with a directly specified relative path. When a packaged application is running it does not see the resource.
EDIT:
Your code reveals the problem as I have described. The following method could be used to properly identify resource path.
public static URL getURL(final String pathAndFileName) {
return Thread.currentThread().getContextClassLoader().getResource(pathAndFileName);
}
Pls refer to this question, which might provide additional information.
Try out this:
m_aboutItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
URL link2=Menubar1.class.getResource("/newpkg/Documentation.pdf");
String link=link2.toString();
link=link.substring(6);
System.out.println(link);
File file=new File(link);
System.out.println(file);
try {
desktop.open(file);
} catch (IOException ex) {
Logger.getLogger(Menubar1.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});

Categories