can't solve this error with json object - java

i write this code to read json data , and there is an error when run the code
first this is the code i write ( i changed the code to correct the json string but the problem still exist )
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
public class defaults {
public static void main(String[] args) {
String jsonTxt = "{lhs: \"100 Euros\",rhs: \"128.551738 Australian dollars\",error: \"\",icc: true}";
JSONObject json = (JSONObject) JSONSerializer.toJSON( jsonTxt );
String title = json.getString("title");
System.out.println( "title: " + title );
}
}
and i have found this error when run the code
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/lang/exception/NestableRuntimeException
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source).....
the error gone away if i remove lines that talks about json

You're missing the Apache Commons lang library from your classpath.
If you ever are stumped by a NoClassDefFoundError try plugging the class name into jarFinder - that will tell you jar files where the class can be found.

String jsonTxt = "{'lhs': '100 Euros','rhs':'128.551738 Australian dollars','error':'','icc': 'true'}";
JSONObject json = (JSONObject) JSONSerializer.toJSON( jsonTxt );
System.out.println( "lhs: " + json.getString("lhs") );
System.out.println( "rhs: " + json.getString("rhs") );
System.out.println( "error: " + json.getString("error") );
System.out.println( "icc: " + json.getString("icc") );
OUTPUT:
lhs: 100 Euros
rhs: 128.551738 Australian dollars
error:
icc: true
you can give the json string with double quotes(") or single quotes(') or key without quotes. All works.
you need following jars:
1. commons-lang-2.4.jar
2. ezmorph-1.0.jar
3. json-lib-0.9.jar
for adding the jars through eclipse:
1.right click on project folder
2.click on prperties
3.select "java build path"
4.select libraries tab
5.click on "Add External jars"
6.Browse your jars, select and click ok.

You have a hanging "," after 'true'.
And technically strings and property names in JSON should use double quotes, not single quotes.

You doesn't have Apache commons-lang in your runtime classpath.

Related

Eclipse not seeing java file properties

I'm doing internationalisation in Java.
I've created two files: MessageBundle_en_US.properties and MessageBundle_en_IN.properties.
MessageBundle_en_US.properties:
greeting=Hello, how are you?
MessageBundle_en_IN.properties
greeting=Halo, apa
And finally, here's the main class:
import java.util.*;
public class InternationalizationDemo {
public static void main(String[] args) {
ResourceBundle bundle =
ResourceBundle.getBundle("MessageBundle", Locale.US);
System.out.println(
"Message in "
+ Locale.US
+ ": "
+ bundle.getString("greeting")
);
//changing the default locale to indonasian
Locale.setDefault(new Locale("in", "ID"));
bundle = ResourceBundle.getBundle("MessageBundle");
System.out.println(
"Message in "
+ Locale.getDefault()
+ ": "
+ bundle.getString("greeting")
);
}
}
And I receive the following error stacktrace:
Exception in thread "main" java.util.MissingResourceException: Can't find bundle for base name MessageBundle, locale en_US
at java.base/java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:2055)
at java.base/java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1689)
at java.base/java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1593)
at java.base/java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1556)
at java.base/java.util.ResourceBundle.getBundle(ResourceBundle.java:932)
at provame.InternationalizationDemo.main(InternationalizationDemo.java:8)
UPDATE
I've found the reason it was unable to see the file, first of all you need to put *properties file in the same directory as the main class, as the kind people suggested in the comments, and you should adjust the call to the file like that:
projectName/propertiesFileName
This was all.
Place your *.properties files in the same folder as InternationalizationDemo.java
Rename: MessageBundle_en_IN.properties to: MessageBundle_in_ID.properties

NoClassDefFoundError for Birt Class EngineException

Has anyone added the Birt Library to a project's build path successfully?
I installed Birt in Eclipse using Help-->Install New Software and copy paste the link for Birt 4.2.2 from the official website. Birt was downloaded from the internet and a new perspective appeared, namely Report Design. Apart from it no Library, no nothing. So I designed my report and started writing Java code in order to do a PDF export of my report, as I found on the internet. I wrote the following:
// Export Birt report
String format = HTMLRenderOption.OUTPUT_FORMAT_PDF;
EngineConfig config = new EngineConfig( );
config.setEngineHome( "C:\\Tools\\Eclipse\\plugins\\org.eclipse.birt.report.viewer_4.2.2.v201302041142\\birt" );
HTMLEmitterConfig hc = new HTMLEmitterConfig( );
HTMLCompleteImageHandler imageHandler = new HTMLCompleteImageHandler( );
hc.setImageHandler( imageHandler );
config.setEmitterConfiguration( HTMLRenderOption.OUTPUT_FORMAT_HTML, hc );
ReportEngine engine = new ReportEngine( config );
IReportRunnable report = null;
String reportFilepath = "C:/Workspace/reports/new_report.rptdesign";
try {
report = engine.openReportDesign( reportFilepath );
}
catch ( EngineException e ) {
System.err.println( "Report " + reportFilepath + " not found!\n" );
engine.destroy( );
return;
}
IRunAndRenderTask task = engine.createRunAndRenderTask( report );
HTMLRenderOption options = new HTMLRenderOption( );
options.setOutputFormat( format );
options.setOutputFileName( "C:/Workspace/reports/output.pdf" );
task.setRenderOption( options );
task.setParameterValues( parametersMap );
try {
task.run( );
}
catch ( EngineException e1 ) {
System.err.println( "Report " + reportFilepath + " run failed.\n" );
System.err.println( e1.toString( ) );
}
engine.destroy( );
return;
Of course no Birt Library is set in my Build Path, so all Birt objects were red. I manually added all Birt jars that existed in Eclipse's plugins folder and all the reds disappeared. It seemed that everything was going great. When I run it I get:
java.lang.NoClassDefFoundError: org/eclipse/birt/report/engine/api/EngineException
while the org.eclipse.birt.report.engine.api package exists in my Build Path
and the EngineException.class exist in the package. I am feeling that there are jar files that I am missing.
I have searched for a solution in Birt home page and found nothing. Most tutorials have instructions regarding how to build a report. But nothing regarding how to get the library up and running with Java.
Is there a standard or automatic or official way to add Birt Library to Eclipse? It is made by Eclipse. It shouldn't be so difficult. Any help will be appreciated.
Have you read this page -> http://wiki.eclipse.org/Servlet_Example_(BIRT)_2.1
Maybe you can find some hints there.

Pig - Unhandled internal error NoClassDefFoundException

I had a specific filtering problem (described here: Pig - How to manipulate and compare dates?), so as we told me, I decided to write my own filtering UDF. Here is the code:
import java.io.IOException;
import org.apache.pig.FilterFunc;
import org.apache.pig.data.Tuple;
import org.joda.time.*;
import org.joda.time.format.*;
public class DateCloseEnough extends FilterFunc {
int nbmois;
/*
* #param nbMois: if the number of months between two dates is inferior to this variable, then we consider that these two dates are close
*/
public DateCloseEnough(String nbmois_) {
nbmois = Integer.valueOf(nbmois_);
}
public Boolean exec(Tuple input) throws IOException {
// We're getting the date
String date1 = (String)input.get(0);
// We convert it into date
final DateTimeFormatter dtf = DateTimeFormat.forPattern("MM yyyy");
LocalDate d1 = new LocalDate();
d1 = LocalDate.parse(date1, dtf);
d1 = d1.withDayOfMonth(1);
// We're getting today's date
DateTime today = new DateTime();
int mois = today.getMonthOfYear();
String real_mois;
if(mois >= 1 && mois <= 9) real_mois = "0" + mois;
else real_mois = "" + mois;
LocalDate d2 = new LocalDate();
d2 = LocalDate.parse(real_mois + " " + today.getYear(), dtf);
d2 = d2.withDayOfMonth(1);
// Number of months between these two dates
String nb_months_between = "" + Months.monthsBetween(d1,d2);
return (Integer.parseInt(nb_months_between) <= nbmois);
}
}
I created a Jar file of this code from Eclipse.
I'm filtering my data with these lines of piglatin code:
REGISTER Desktop/myUDFs.jar
DEFINE DateCloseEnough DateCloseEnough('12');
experiences1 = LOAD '/home/training/Desktop/BDD/experience.txt' USING PigStorage(',') AS (id_cv:int, id_experience:int, date_deb:chararray, date_fin:chararray, duree:int, contenu_experience:chararray);
experiences = FILTER experiences1 BY DateCloseEnough(date_fin);
I'm launching my program with this linux command:
pig -x local "myScript.pig"
And I get this error:
2013-06-19 07:27:17,253 [main] INFO org.apache.pig.Main - Logging error messages to: /home/training/pig_1371652037252.log
2013-06-19 07:27:17,933 [main] ERROR org.apache.pig.tools.grunt.Grunt - ERROR 2998: Unhandled internal error. org/joda/time/ReadablePartial Details at logfile: /home/training/pig_1371652037252.log
I checked into the log file and I saw this:
Pig Stack Trace
ERROR 2998: Unhandled internal error. org/joda/time/ReadablePartial
java.lang.NoClassDefFoundError: org/joda/time/ReadablePartial
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:247)
at org.apache.pig.impl.PigContext.resolveClassName(PigContext.java:441)
at org.apache.pig.impl.PigContext.instantiateFuncFromSpec(PigContext.java:471)
at org.apache.pig.impl.PigContext.instantiateFuncFromAlias(PigContext.java:544)
at org.apache.pig.impl.logicalLayer.parser.QueryParser.EvalFuncSpec(QueryParser.java:4834)
at org.apache.pig.impl.logicalLayer.parser.QueryParser.PUnaryCond(QueryParser.java:1949)
at org.apache.pig.impl.logicalLayer.parser.QueryParser.PAndCond(QueryParser.java:1790)
at org.apache.pig.impl.logicalLayer.parser.QueryParser.POrCond(QueryParser.java:1734)
at org.apache.pig.impl.logicalLayer.parser.QueryParser.PCond(QueryParser.java:1700)
at org.apache.pig.impl.logicalLayer.parser.QueryParser.FilterClause(QueryParser.java:1548)
at org.apache.pig.impl.logicalLayer.parser.QueryParser.BaseExpr(QueryParser.java:1276)
at org.apache.pig.impl.logicalLayer.parser.QueryParser.Expr(QueryParser.java:893)
at org.apache.pig.impl.logicalLayer.parser.QueryParser.Parse(QueryParser.java:682)
at org.apache.pig.impl.logicalLayer.LogicalPlanBuilder.parse(LogicalPlanBuilder.java:63)
at org.apache.pig.PigServer$Graph.parseQuery(PigServer.java:1031)
at org.apache.pig.PigServer$Graph.registerQuery(PigServer.java:981)
at org.apache.pig.PigServer.registerQuery(PigServer.java:383)
at org.apache.pig.tools.grunt.GruntParser.processPig(GruntParser.java:717)
at org.apache.pig.tools.pigscript.parser.PigScriptParser.parse(PigScriptParser.java:273)
at org.apache.pig.tools.grunt.GruntParser.parseStopOnError(GruntParser.java:166)
at org.apache.pig.tools.grunt.GruntParser.parseStopOnError(GruntParser.java:142)
at org.apache.pig.tools.grunt.Grunt.exec(Grunt.java:89)
at org.apache.pig.Main.main(Main.java:320)
Caused by: java.lang.ClassNotFoundException: org.joda.time.ReadablePartial
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
... 24 more
I tried to modify my PIG_CLASSPATH variable but i figured out that this variable doesn't exist at all (some other pig scripts are working though).
Do you have an idea to solve te problem ?
Thanks.
At first, you need to tell Pig which jar you are using. See this answer: how to include external jar file using PIG. Configure build path to add it in eclipse is not enough. Eclipse will not help you generate the correct jar.
Secondly, String nb_months_between = "" + Months.monthsBetween(d1,d2); is wrong. You can use int nb_months_between = Months.monthsBetween(d1,d2).getMonths();. If you read the Months.toString, it returns "P" + String.valueOf(getValue()) + "M";. So you can not use this value and want to convert it to a int.
u need this package: org/joda/time/ReadablePartial
can find here: jarfinder
download the joda-time-1.5.jar. Add to your project, this to should resolve.

Java System Parameter causing NoClassDefFoundError

I have a class which takes in various system parameters and prints them out:
public class Test_Class {
public static void main(String[] args){
String fooA = System.getProperty("fooA");
String fooB = System.getProperty("fooB");
String fooC = System.getProperty("fooC");
System.out.println("System Properties:\n"+fooA+"\n"+foob+"\n"+fooC+"\n");
}
}
Then, using IntelliJ, pass in the VM Parameters as such:
-DfooA="StringA" -DfooB="StringB" -DfooC="String C"
Upon running my program I get the following output:
System Properties:
StringA
StringB
String C
Now, if I run the same program through a UNIX server by running the following command:
java -DfooA="StringA" -DfooB="StringB" -DfooC="String C" com.foo.fooUtil.Test_Class
I get the following error:
Exception in thread "main" java.lang.NoClassDefFoundError: C
I have tried a bunch of different ways to pass in fooC, such as -DfooC=\"String C\", -DfooC='String C', -DfooC=\'String C\', basically any idea that came to mind. I have done some research and have been unable to find any solid solution.
For reference, I found the following link online where another person seems to have the same issue but, unfortunately, none of the suggestions work.
http://www.unix.com/shell-programming-scripting/157761-issue-spaces-java-command-line-options.html
How can I pass in a System Parameter with spaces in UNIX? Thank you.
Here is my approach: Why not use a .properties file for storing the system properties instead of passing them through command line? You can access the properties using:
Properties properties = new Properties();
try {
properties.load(new FileInputStream("path/filename"));
} catch (IOException e) {
...
}
And you may iterate as:
for(String key : properties.stringPropertyNames()) {
String value = properties.getProperty(key);
System.out.println(key + " => " + value);
}
Hope that helps!!!

Loading classes to application from file system at runtime

I have an application which deals with jdbc. It supposes to be used in any PC where there is JRE, but it does not suppose that use will use -cp command line or change his/her classpath variables. So the user has my application, JRE and a jdbc driver somewhere in file system. Now he or she enters a database connection information including path to jdbc driver jar and then make sql request. The problem is that I don't now how to make jdbc driver classes to be accessible in this application. The same way as the user explicitly add a driver to classpath.
I just altered part of the miks answer for your other posting.
Executing the following code got me a success.
import java.io.File;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.net.URLClassLoader;
public class URLClassLoaderSample {
public static void main( String [] args ) throws Exception {
File f = new File( "/home/ravinder/Desktop/mysql-connector-java-5.1.18-bin.jar" );
URLClassLoader urlCl = new URLClassLoader( new URL[] { f.toURL() }, System.class.getClassLoader() );
Class mySqlDriver = urlCl.loadClass( "com.mysql.jdbc.Driver" );
System.out.println( mySqlDriver.newInstance() );
System.out.println( "Is this interface? = " + mySqlDriver.isInterface() );
Class interfaces[] = mySqlDriver.getInterfaces();
int i = 1;
for( Class _interface : interfaces ) {
System.out.println( "Implemented Interface Name " + ( i++ ) + " = " + _interface.getName() );
} // for(...)
Constructor constructors[] = mySqlDriver.getConstructors();
for( Constructor constructor : constructors ) {
System.out.println( "Constructor Name = " + constructor.getName() );
System.out.println( "Is Constructor Accessible? = " + constructor.isAccessible() );
} // for(...)
} // psvm(...)
} // class URLClassLoaderSample
Output seen is as follows:
com.mysql.jdbc.Driver#60aeb0
Is this interface? = false
Implemented Interface Name 1 = java.sql.Driver
Constructor Name = com.mysql.jdbc.Driver
Is Constructor Accessible? = false
And I don't understand what I should with log4jClass variable in my case *(com.mysql.jdbc.Driver)
Let me hope now you got it.
The best solution in this instance would be to distribute the required driver with your application and include either an executable wrapper or a shell script that sets the required variables accordingly. That allows the user to use it out of the box without having to mess with any complicated configuration and also doesn't require them to download any additional files.
Well, jdbc uses Class.forName("org.postgresql.Driver"); to load the driver. So once, you have the jar file, and have added it to the class-path, this part is easy. Just keep a hash of driver fqn classnames to jar file names. Or you can scan the jar for the Driver class.
Here's a convienent answer to how to add the jar file to the classpath once you find it.

Categories