ListResourceBundle and MissingResourceException - java

I'm working on a project that involves loading up a ResourceBundle. More explicitly, I've created a class that extends ListResourceBundle. The class is called Resources.java. It compiles fine and everything, but the MissingResourceException keeps popping up every time I try to load up the class:
All my source files are in package chapter31. When making this call with or without the "chapter31" in the string, always results in a MissingResourceException. My IDE is Eclipse. I've been playing around with this one problem for two days. I even tried changing the version of Eclipse. I'm at the end of my rope. What can I do in Eclipse to ensure that the getBundle() method can see the class. I don't know how it can miss it. It's in the same package! Please advise.
Alikas
package chapter31;
import java.applet.Applet;
import java.applet.AudioClip;
import java.util.ListResourceBundle;
import java.util.ResourceBundle;
import javax.swing.ImageIcon;
public class Resources extends ListResourceBundle {
Object contents[][];
public Resources() {
AudioClip clip = Applet.newAudioClip(getClass().getResource("/E31_10/audio/us.mid"));
ImageIcon image = new ImageIcon(getClass().getResource("/E31_10/image/us.gif"));
contents = new Object[3][2];
contents[0] = new Object[] {"clip", clip};
contents[1] = new Object[] {"icon", image};
contents[3] = new Object[] {"delay", new Integer(68000)};
}
protected Object[][] getContents() {
return contents;
}
public static void main(String[] args) {
ResourceBundle res = ResourceBundle.getBundle("chapter31.Resources");
}
}

The MissingResourceException is misleading here. Your problem may be caused by two other problems:
The resources in the following two lines cannot be found:
AudioClip clip =
Applet.newAudioClip(getClass().getResource("/E31_10/audio/us.mid"));
ImageIcon image = new ImageIcon(getClass().getResource("/E31_10/image/us.gif"));
If the first one is not the problem, there is a second problem:
You have a wrong array index contents[3] which will cause ArrayIndexOutOfBoundsException and this will also cause the misleading MissingResourceException to be thrown. If you can find this exception in your exception stack trace, your problem is here. Change it to contents[2] will solve the problem.
Note: The reason you are seeing MissingResourceException is ultimately caused by the class loader cannot create an instance of the Resources class due to the problems pointed out above. If you had put the contents array initialization codes in a separate method instead of the constructor, you may not get this exception at the object initialization phase. Of course, other exceptions will pop out later when you try to call getObject method.

Are you trying to load a message properties file called "chapter31.Resources"? If so then in Eclipse you can try the below:
Click on "Debug Configuration..."
Find the launcher you are using to execute the main method for Resources
Click on the Classpath tab
Click on "User Entries" and then Click the "Advanced" button
Select "Add External Folder" and choose the folder the "chapter31.Resources" .
ResourceBundle.getBundle() method is looking for the file in your classpath . if this file is not in your classpath it won't be able to find it.
The steps above adds the folder that "chapter31.Resources" to your classpath.
If this still does not work you can try passing the full path of the file to ResourceBundle.getResource().

Related

InputStream gives IllegalArgumentException for just the jar file [duplicate]

The line persistenceProperties.load(is); is throwing a nullpointerexception in the following method. How can I resolve this error?
public void setUpPersistence(){
final Properties persistenceProperties = new Properties();
InputStream is = null;
try {
is = getClass().getClassLoader().getResourceAsStream("src/test/samples/persistence.properties");
persistenceProperties.load(is);
}catch (IOException ignored) {}
finally {
if (is != null) {try {is.close();} catch (IOException ignored) {}}
}
entityManagerFactory = Persistence.createEntityManagerFactory(
"persistence.xml", persistenceProperties);
}
I have tried to experiment with this by moving the class that contains the method to various other locations within the application structure, and also by changing the line of code preceding the error in the following ways:
is = getClass().getClassLoader().getResourceAsStream("persistence.properties");
is = getClass().getClassLoader().getResourceAsStream("/persistence.properties");
is = getClass().getClassLoader().getResourceAsStream("/src/test/samples/persistence.properties");
is = getClass().getClassLoader().getResourceAsStream("other/paths/after/moving/persistence.properties");
But the error is still thrown every time the method is called.
Here is a printscreen of the directory structure of the eclipse project. The class containing the method is called TestFunctions.java, and the location of persistence.properties is shown:
**EDIT: **
As per feedback below, I changed the method to:
public void setUpPersistence(){
final Properties persistenceProperties = new Properties();
InputStream is = null;
try {
is = getClass().getClassLoader().getResourceAsStream("persistence.properties");
persistenceProperties.load(is);
}catch (IOException i) {i.printStackTrace();}
finally {
if (is != null) {try {is.close();} catch (IOException ignored) {}}
}
entityManagerFactory = Persistence.createEntityManagerFactory(
"persistence.xml", persistenceProperties);
}
I also moved mainTest.TestFunctions.java to src/test/java. Together, these all cause the following new stack trace:
Exception in thread "main" java.lang.NoClassDefFoundError: maintest/TestFunctions
at maintest.Main.main(Main.java:7)
Caused by: java.lang.ClassNotFoundException: maintest.TestFunctions
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
... 1 more
Short answer:
Move persistence.properties to src/main/resources, have both Main.java and TestFunctions.java in src/main/java, and use
getClass().getClassLoader().getResourceAsStream("persistence.properties");
to load the properties file.
Long answer with an explanation:
As others have hinted at - in a Maven project structure, you (typically) have two directory trees: /src/main and /src/test. The general intent is that any "real" code, resources, etc should go in /src/main, and items that are test-only should go in /src/test. When compiled and run, items in the test tree generally have access to items in the main tree, since they're intended to test the stuff in main; items in the main tree, however, do not typically have access to items in the test tree, since it's generally a bad idea to have your "production" code depending on test stuff. So, since Main.java depends on TestFunctions.java, and TestFunctions.java depends on persistence.properties, if Main is in src/main then both TestFunctions and persistence.properties need to be as well.
Two things:
First, try a path of test/samples/... or /test/samples/...
Secondly, and much more importantly, don't ever, ever, ever write this:
try {
// some stuff
} catch (IOException ignored) {}
All this says is: do some stuff, and if it goes wrong, then fail silently. That is never the right thing to do: if there's a problem, you want to know about it, rather than madly rushing on as if nothing had happened. Either do some sensible processing in your catch block, or else don't have the try/catch and add a throws IOException to your method signature so it can propagate upwards.
But at the moment, you're just sweeping things under the carpet.
ClassLoader.getResourceAsStream() loads resources as it does for loading classes. It thus loads them from the runtime classpath. Not from the source directories in your project.
Your class Main is in the package maintest, and its name is thus maintest.Main. I know that without even seeing the code because Main.java is under a directory named maintest, which is at directly under a source directory.
The persistence.properties file is directly under a source directory (src/test/resources). At runtime, it's thus at the root of the classpath, in the default package. Its name is thus persistence.properties, and not src/test/samples/peristence.properties. So the code should be
getClass().getClassLoader().getResourceAsStream("persistence.properties");
Nothing will ever be loadable from the samples directory, since thisdirectory is not under any source directory, and is thus not compiled by Eclipse, and is thus not available to the ClassLoader.
I will try to make it more Simple for this Question!
Here your main class is in src/main/java as you mentioned, so you should create another source for storing your properties file saying src/main/resources which you had already done and just store your properties file in this source, so in Run time it will directly refer this path and access the file,
You can add this piece of code as well to access the properties file
is = ClassLoader.getSystemResourceAsStream("your_properties_file");
and you can use load(is) accordingly.
To Conclude
If your main class is in src/main/java then you should keep your properties file in src/main/resources and use the respective snippet to load this.
OR
If your main class is in src/test/java then you should keep your properties file in src/test/resources and use the respective snippet to load this.
Your IDE works with two different scopes:
production scope: src/main/java + src/main/resources folders and
test scope: src/test/java + src/test/resources
Seems you are trying to execute you program from production scope, while persistence.properties file is placed into test scope.
How to fix:
Place your test into src/test/java or
Move persistence.properties into src/main/resources
InputStream is = this.getClass().getResourceAsStream("/package_name/property file name")
PropertyFileOject.load(is)
In my case error was due to maven was not treating my config folder inside src/main/java as source folder.
Recreated config package in src/main/java ..Copied files to it and re-compiled using maven. Files were there in target directory and hence in war. Error resolved.
I recently had the same problem and came upon the solution that I had to put my resources in a path the same way organized as where was getClass().getResourceAsStream(name) situated. And I still had a problem after doing that. Later on, I discovered that creating a package org.smth.smth only had created a folder named like that "org.smth.smth" and not a folder org with a folder smth and a folder inside smth... So creating the same path structure solved my problem. Hope this explanation is understandable enough.

how to make java use the newest version of a file

I have this problem that i have a program that writes and creates a .java file and puts it in my package folder, after this it takes the information from the .java file and uses it in it self. (it creates a new class with a method that i then import).
The problem is that if it wont work until i with eclipse update the "self created file". is there a way to make my main file update the "self created file".
Sorry if this is a duplicate. I just couldn't find it any where.
my code:
package dk.Nicolai.Bonde;
import java.io.*;
public class main {
public String outputString ="Math.sqrt(25)" ;
static String outputPath ="src/output.txt";
/**
* #param args
* #throws UnsupportedEncodingException
* #throws FileNotFoundException
*/
public static void main(String[] args) throws IOException{
new main().doit(args);
}
public void doit(String[] args) throws IOException{
PrintWriter writer = new PrintWriter("src/dk/Nicolai/Bonde/calculate.java", "UTF-8");
writer.println("package dk.Nicolai.Bonde;");
writer.println("public class calculate{");
writer.println("public void calc(){");
writer.println("System.out.println("+outputString+");");
writer.println("}");
writer.println("}");
writer.flush();
writer.close();
calculate calcObj = new calculate();
calcObj.calc();
}
}
Your main mistake is that you expected that it's during runtime automagically compiled into a .class file after save (which a sane IDE such as Eclipse is doing automatically for you behind the scenes everytime you press Ctrl+S). This is thus not true. During runtime, you need to compile it yourself by JavaCompiler and then load by URLClassLoader. A concrete example is given in this related question&answer: How do I programmatically compile and instantiate a Java class?
You'll in the concrete example also notice that you can't do just a new calculate(); thereafter. The classpath won't be auto-refreshed during runtime or so. You'd need to do a Class#forName(), passing the FQN and the URLClassLoader. E.g.
Calculate calculate = (Calculate) Class.forName("com.example.Calculate", true, classLoader);
Your other mistake is that you're relying on the disk file system's current working directory always being the Eclipse project's source root folder. This is not robust. This folder is not present at all when building and distributing the application. You should instead write the file to a fixed/absolute folder elsewhere outside the IDE project's structure. This is also covered in the aforelinked answer.
No, you cannot. You have to manually update resources in Eclipse. Although you can write a plugin for Eclipse which runs your file and update resources.
Eclipse uses directories and files to store its resources but is not direct representation of file system.
Your code could not work, because
calculate is required at compile time of main. You supply it at runtime.
calculate.java will not compiled, so even other techniques to dynamically load classes will not work
If you want to build classes at runtime, consider to use the reflexion API

Boilerpipe Starter issue

I am new to boilerpipe. I tried to run sample code given on their website:
import java.net.URL;
import de.l3s.boilerpipe.extractors.ArticleExtractor;
import de.l3s.boilerpipe.extractors.DefaultExtractor;
public class TESTURLBOILERPIPE {
public static void main(String[] arges) throws Exception
{
final URL url = new URL(
"http://www.l3s.de/web/page11g.do?sp=page11g&link=ln104g&stu1g.LanguageISOCtxParam=en");
ArticleExtractor ae = new ArticleExtractor();
System.out.println(ae.INSTANCE.getText(url));
}
}
I have added all the required jar files to the class path, however I get the exception:
Exception in thread "main" java.lang.IllegalArgumentException: usage: supply url to fetch
at org.jsoup.helper.Validate.isTrue(Validate.java:45)
at org.jsoup.examples.HtmlToPlainText.main(HtmlToPlainText.java:26)
I don't know Boilerpipe, but are you sure you are trying to run the correct Java class? The stack trace looks like you are trying to run HtmlToPlainText (without arguments, thus the exception), but from the code you posted I think you would like to run your TESTURLBOILERPIPE class.
Try using a python wrapper. It takes care of all the dependencies, though you might have to install jpype manually (that source code is on sourceforge).
https://github.com/misja/python-boilerpipe

can I load user packages into eclipse to run at start up and how?

I am new to java and to the eclipse IDE.
I am running Eclipse
Eclipse SDK
Version: 3.7.1
Build id: M20110909-1335
On a windows Vista machine.
I am trying to learn from the book Thinking in Java vol4.
The author uses his own packages to reduce typing. However the author did not use Eclipse and this is where the problem commes in..
This is an example of the code in the book.
import java.util.*;
import static net.mindview.util.print.*;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("hello world");
print("this does not work");
}
this is the contents of print.Java
//: net/mindview/util/Print.java
// Print methods that can be used without
// qualifiers, using Java SE5 static imports:
package net.mindview.util;
import java.io.*;
public class Print {
// Print with a newline:
public static void print(Object obj) {
System.out.println(obj);
}
// Print a newline by itself:
public static void print() {
System.out.println();
}
// Print with no line break:
public static void printnb(Object obj) {
System.out.print(obj);
}
// The new Java SE5 printf() (from C):
public static PrintStream
printf(String format, Object... args) {
return System.out.printf(format, args);
}
} ///:~
The error I get the most is in the statement.
Import static net.mindview.util.print.*;
On this staement the Eclipse IDE says it cannot resolve net
also on the
print("this does not work");
The Eclipse IDE says that the class print() does not exist for the class HelloWorld.
I have been trying to get these to work, but with only limited success, The autor uses another 32 of these packages through the rest of the book.
I have tried to add the directory to the classpath, but that seems to only work if you are using the JDK compiler. I have tried to add them as libraries and i have tried importing them into a package in a source file in the project. I have tried a few other things but cant remember them all now.
I have been able to make one of the files work, the print.java file I gave the listing for in this message. I did that by creating a new source folder then making a new package in that foldeer then importing the print.java file into the package.
But the next time I try the same thing it does not work for me.
What I need is a way to have eclipse load all these .java files at start up so when I need them for the exercises in the book they will be there and work for me, or just an easy way to make them work everytime.
I know I am not the only one that has had this problem I have seen other questions about it on google searches and they were also asking about the Thinking In Java book.
I have searched this site and others and am just not having any luck.
Any help with this or sugestions are welcome and very appreciated.
thank you
Ok I have tried to get this working as you said, I have started a new project and I removed the static from the import statement, I then created a new source folder, then I created a new package in the source folder. Then I imported the file system and selected the the net.mindview.util folder.
Now the immport statement no longer gives me an error. But the the print statement does, the only way to make the print statement work is to use its fully qualified name. Here is the code.
import net.mindview.util.*;
public class Hello2 {
public static void main(String[] args) {
Hello2 test = new Hello2();
System.out.println();
print("this dooes not work");
net.mindview.util.Print.print("this stinks");
}
}
The Error on the print statement is:
The method print(String) is undefined for the type Hello2
and if I try to run it the error I get is:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method print(String) is undefined for the type Hello2
at Hello2.main(Hello2.java:6)
The Statement::::: net.mindview.util.Print.print("this stinks") is the fully qualified print statement and it does not throw an error but it does totally defeat the purpose of the print.java file..
If you have any questions please ask Ill get back to you as soon as I can.
I've had similar issues. I solved it by following the steps below:
Click File->New->Java Project. Fill in UtilBuild for the ProjectName. Chose the option "Use project folder as root and click 'Finish'.
Right-click on UtilBuild in the PackageExplorer window and click New->package. For the Package Name, fill in net.mindview.util
Navigate within the unzipped Thinking In Java (TIJ) folder to TIJ->net\mindview\util. Here you will find all the source code (.java) files for util.
Select all the files in the net\mindview\util folder and drag them to the net.mindview.util package under UtilBuild in Eclipse. Chose the 'Copy Files' option and hit 'OK'.
You will probably already have the 'Build Automatically' option checked. If not, go to Project and click 'Build Automatically'. This will create the .class files from the .java source files.
In Eclipse, right-click on the project you were working on (the one where you couldn't get that blasted print() method to work!) Click Properties and Java Build Path->Libraries. Click 'Add Class Folder...' check the box for UtilBuild (the default location for the .class files).
I think the confusion here arises due to CLASSPATH. If you use Eclipse to build and run your code then Eclipse manages your CLASSPATH. (You don't have to manually edit CLASSPATH in the 'Environment Variables' part of your computer properties, and doing so changes nothing as far as Eclipse Build and Run are concerned.)
In order to call code that exists outside your current project (I will name this 'outside code' for convenience) you need to satisfy three things:
A. You need to have the .class files for that code (as .class files or inside a JAR)
B. You need to indicate in your source code where to look for the 'outside code'
C. You need to indicate where to start looking for the 'outside code'
In order to satisfy these requirements, in this example we:
A. Build the project UtilBuild which creates the .class files we need.
B. Add the statement import static net.mindview.util.Print.*; in our code
C. Add the Class Folder library in Eclipse (Java Build Path->Libraries).
You can investigate the effect of Step C by examining the .classpath file that lives directly in your project folder. If you open it in notepad you will see a line similar to the following:
<classpathentry kind="lib" path="/UtilBuild>
You should combine this with your import statement to understand where the compiler will look for the .class file. Combining path="/UtilBuild" and import static net.mindview.util.Print.*; tells us that the compiler will look for the class file in:
UtilBuild/net/mindview/util
and that it will take every class that we built from the Print.java file (Print.*).
NOTE:
There is no problem with the keyword static in the statement
import static net.mindview.util.Print.*;
static here just means that you don't have to give specify the class name from Print.java, just the methods that you want to call. If we omit the keyword static from the import statement, then we would need to qualify that print() method with the class it belongs to:
import net.mindview.util.Print.*;
//...
Print.print("Hello");
which is slightly more verbose than what is achieved with the static import.
OPINION:
I think most people new to Java will use Eclipse at least initially. The Thinking in Java book seems to assume you will do things via command line (hence it's guidance to edit environment variables in order to update CLASSPATH). This combined with using the util folder code from very early in the book I think is a source of confusion to new learners of the language. I would love to see all the source code organised into an Eclipse project and available for download. Short of that, it would be a nice touch to include the .class files in just the 'net/mindview/util' folder so that things would be a little easier.
U should import package static net.mindview.util not static net.mindview.util.Print
and you should extend the class Print to use its method.......
You should remove the static keyword from your import decleration, this: import static net.mindview.util.print.*; becomes this: import net.mindview.util.print.*;
If that also does not work, I am assuming you did the following:
Create your own project;
Start copying code directly from the book.
The problem seems to be that this: package net.mindview.util; must match your folder structure in your src folder. So, if your src folder you create a new package and name it net.mindview.util and in it you place your Print class, you should be able to get it working.
For future reference, you should always make sure that your package decleration, which is at the top of your Java class, matches the package in which it resides.
EDIT:
I have seen your edit, and the problem seems to have a simple solution. You declare a static method named print(). In java, static methods are accessed through the use of ClassName.methodName(). This: print("this dooes not work"); will not work because you do not have a method named print which takes a string argument in your Hello2 class. In java, when you write something of the sort methodName(arg1...), the JVM will look for methods with that signature (method name + parameters) in the class in which you are making the call and any other classes that your calling class might extend.
However, as you correctly noted, this will work net.mindview.util.Print.print("this stinks");. This is because you are accessing the static method in the proper way, meaning ClassName.methodName();.
So in short, to solve your problem, you need to either:
Create a method named print which takes a string argument in your Hello2 class;
Call your print method like so: Print.print("this stinks");
Either of these two solutions should work for you.
In my case I've dowloaded and decompressed the file TIJ4Example-master.zip. in eclipse workspace folder. The three packages : net.mindview.atunit, net.mindview.simple and net.mindview.util are in this point of the project :
and java programs runs with no problems (on the right an example of /TIJ4Example/src/exercises/E07_CoinFlipping.java)

method must call super() error in Netbeans

Recently I've made a Netbeans project and I am using SVN along with it. I am seeing duplicate class error, and in the console it says
java.lang.VerifyError: (class: pie/chart/explorer/PieChartExplorer, method: <init> signature: ()V) Constructor must call super() or this()
Could not find the main class: pie.chart.explorer.PieChartExplorer. Program will exit.
Exception in thread "main" Java Result: 1
Here is PieChartExplorer.java:
package pie.chart.explorer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class PieChartExplorer extends JFrame implements ActionListener {
JTextField one = new JTextField(10);
JTextField two = new JTextField(10);
JTextField three = new JTextField(10);
JButton sub = new JButton("Click to be amazed");
public PieChartExplorer() {
super("Pie Chart Explorer");
setSize(300,100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FlowLayout flo = new FlowLayout();
setLayout(flo);
setVisible(true);
add(one);
add(two);
add(three);
sub.addActionListener(this);;
add(sub);
}
public static void main(String[] args) {
PieChartExplorer app = new PieChartExplorer();
}
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(source == sub) {
try {
Pie show = new Pie(Float.parseFloat(one.getText()),Float.parseFloat(two.getText()),Float.parseFloat(three.getText()));
} catch(Exception ex) {
JOptionPane.showMessageDialog(this, "Please check entered data");
}
}
}
}
I have tried:
Clean and Rebuild project
Making sure that I have called super in all constructors
How can this be fixed? Code for download.
I found that renaming the package did not work, the old package was still there.
The problem for me started when I copied a package from another application into the current application, which already had a package with the same name. I was trying to add some missing classes to the package. After I did that, the error started.
To resolve it, I deleted the entire package from the target web app and did a clean and build. Then I copied the source package into the target application. No errors.
I saw these symptoms just the other day.
I had I file I had been editing and decided I wanted to split my changes into 2 commits. I went to the directory containing my file "x/y/Z.java", made a directory in "x/y" named "backup", moved "Z.java" there, and pulled a fresh copy from version control. Note all of this was done outside the IDE.
Back in the IDE I merged in the changes for the first commit and when I built I got the duplicate class message for "Z.java".
When I copied the source to "backup" I did it outside the IDE and it still had the original package "x.y" as did my newly edited "Z.java". NB would not compile the new "Z.java" because it could see it had already created "x.y.Z.class" (from "x/y/backup/Z.java").
There are 2 ways to fix this:
Rename "x/y/backup/Z.java" to "x/y/backup/Z.java.backup". (Prevent the backup copy from being compiled.)
Change the package in "x/y/backup/Z.java" from "x.y" to "x.y.backup". (Make the backup create a different class file.)
After making either of these changes, perform a "clean and build". Note: simply building will not fix the problem, you need to perform a clean to remove the rogue class file.
Note: #1 was done by renaming Z.java from the command line, not within NB. NB will not let you change the file extension.
Cleaning and Building solves the problem
If you still have the problem, this is how I solved it..
In my case I changed the class with main method later and the initial class was still referenced in the proporties file.
Change that setting, clean and build.. It worked for me...
In my case, i had the same problem in a Web application after making an external copy of a POJO and manually editing it outside NETBEANS. The problem actually was what the others suggested in other answers about a conflict in the already compiled .class files.
What i did to overcome this was simply delete the folder webAppname/WEB-INF/classes (where compiled classes reside) and then do a Clean and Build
Hope this helps someone

Categories