Today I started learning about json files and I made a test using NetBeans and json-lib :
package tp;
import java.io.FileInputStream;
import java.io.IOException;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.apache.commons.io.IOUtils;
public class Tp {
public static void main(String[] args) throws IOException {
String jsonTxt = IOUtils.toString(new FileInputStream("test/test/test1.json"), "UTF-8");
System.out.println("jsonTxt.length " + jsonTxt.length());
JSONArray root = (JSONArray) JSONSerializer.toJSON(jsonTxt);
JSONObject document = root.getJSONObject(0);
String tag = document.getString("tag");
System.out.println("tag " + tag);
}
}
this is my json file :
{
"tag": "value"
}
I'm tying to read and display the value but I get :
jsonTxt.length 25
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(ClassLoader.java:760)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:455)
at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
at java.net.URLClassLoader$1.run(URLClassLoader.java:367)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at tp.Tp.main(Tp.java:15)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.lang.exception.NestableRuntimeException
at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 13 more
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
line 15 is : JSONArray root = (JSONArray) JSONSerializer.toJSON(jsonTxt);
What m'I doing wrong ?
SOLUTION :
adding all the libraries : commons-io-2.4.jar, ezmorph-1.0.6.jar, json-lib-2.4-jdk15.jar, commons-logging-1.2.jar, commons-lang-2.6.jar, commons-beanutils-1.9.2.jar, commons-collections-3.2.1.jar
package tp;
import java.io.FileInputStream;
import java.io.IOException;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.apache.commons.io.IOUtils;
public class Tp {
public static void main(String[] args) throws IOException {
String jsonTxt = IOUtils.toString(new FileInputStream("test/test/test1.json"), "UTF-8");
System.out.println("jsonTxt.length " + jsonTxt.length());
JSONObject root = (JSONObject) JSONSerializer.toJSON(jsonTxt);
String tag = root.getString("tag");
System.out.println("tag " + tag);
}
}
Thanks
Related
im trying to use documents4j (https://bintray.com/raphw/maven/documents4j) in order to convert a docx file to pdf with this code:
Thank you very much in advance, i have no idea of making it works
package documents4j;
import java.io.File;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
public class HelloPDF {
public static void main(String[] args) {
File wordFile = new File("c:/datos/Resultados.docx"), target = new File("c:/datos/Resultados.pdf");
IConverter converter = LocalConverter.builder().baseFolder(new File("c:/datos/"))
.workerPool(20, 25, 2, TimeUnit.SECONDS)
.processTimeout(5, TimeUnit.SECONDS).build();
Future<Boolean> conversion = converter.convert(wordFile).as(DocumentType.DOCX).to(target).as(DocumentType.PDF)
// .prioritizeWith(1000) // optional
.schedule();
}
}
But im encountering an illegalstateexcepcion
Exception in thread "main" java.lang.IllegalStateException: class com.documents4j.conversion.msoffice.MicrosoftWordBridge could not be created by a (File, long, TimeUnit) constructor
at com.documents4j.conversion.ExternalConverterDiscovery.make(ExternalConverterDiscovery.java:32)
at com.documents4j.conversion.ExternalConverterDiscovery.makeAll(ExternalConverterDiscovery.java:42)
at com.documents4j.conversion.ExternalConverterDiscovery.loadConfiguration(ExternalConverterDiscovery.java:85)
at com.documents4j.conversion.DefaultConversionManager.<init>(DefaultConversionManager.java:22)
at com.documents4j.job.LocalConverter.makeConversionManager(LocalConverter.java:79)
at com.documents4j.job.LocalConverter.<init>(LocalConverter.java:51)
at com.documents4j.job.LocalConverter$Builder.build(LocalConverter.java:186)
at documents4j.HelloPDF.main(HelloPDF.java:20)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at com.documents4j.conversion.ExternalConverterDiscovery.make(ExternalConverterDiscovery.java:30)
... 7 more
Caused by: java.lang.NoClassDefFoundError: com/documents4j/util/Reaction$IExceptionBuilder
at com.documents4j.conversion.msoffice.AbstractMicrosoftOfficeBridge.tryStart(AbstractMicrosoftOfficeBridge.java:34)
at com.documents4j.conversion.msoffice.MicrosoftWordBridge.startUp(MicrosoftWordBridge.java:44)
at com.documents4j.conversion.msoffice.MicrosoftWordBridge.<init>(MicrosoftWordBridge.java:39)
... 12 more
Caused by: java.lang.ClassNotFoundException: com.documents4j.util.Reaction$IExceptionBuilder
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
... 15 more
[Shutdown hook: com.documents4j.job.LocalConverter] INFO com.documents4j.job.ConverterAdapter - Tried to deregister shut down hook in shut down period
java.lang.IllegalStateException: Shutdown in progress
at java.lang.ApplicationShutdownHooks.remove(ApplicationShutdownHooks.java:82)
at java.lang.Runtime.removeShutdownHook(Runtime.java:237)
at com.documents4j.job.ConverterAdapter.deregisterShutdownHook(ConverterAdapter.java:121)
at com.documents4j.job.ConverterAdapter.cleanUp(ConverterAdapter.java:107)
at com.documents4j.job.ConverterAdapter.shutDown(ConverterAdapter.java:98)
at com.documents4j.job.LocalConverter.shutDown(LocalConverter.java:109)
at com.documents4j.job.ConverterAdapter$ConverterShutdownHook.run(ConverterAdapter.java:134)
Exception in thread "Shutdown hook: com.documents4j.job.LocalConverter" java.lang.NullPointerException
at com.documents4j.job.LocalConverter.shutDown(LocalConverter.java:100)
at com.documents4j.job.ConverterAdapter$ConverterShutdownHook.run(ConverterAdapter.java:134)
Ok, i have found the answer. The problem was that i have not all the libraries included, i add:
documents4j-util-all-1.0.3
documents4j-util-standalone-1.0.3
And it finally works
I'm using spark whith java, and i want to use spark Job-Server. For this i followed all in this link :
https://github.com/spark-jobserver/spark-jobserver
This is the scala class in my project :
import _root_.spark.jobserver.SparkJob
import _root_.spark.jobserver.SparkJobValid
import _root_.spark.jobserver.SparkJobValidation
import com.typesafe.config._
import org.apache.spark._
import org.apache.spark.api.java.JavaSparkContext
import spark.jobserver.{SparkJob, SparkJobValid, SparkJobValidation}
object JavaWord extends SparkJob {
def main(args: Array[String]) {
val ctx = new SparkContext("local[4]", "JavaWordCount")
val config = ConfigFactory.parseString("")
val results = runJob(ctx, config)
}
override def validate(sc: SparkContext, config: Config): SparkJobValidation = {
SparkJobValid;
}
override def runJob(sc: SparkContext, config: Config): Any = {
val jsc = new JavaSparkContext(sc)
val j = new JavaCount()
return j.Mafonction(jsc: JavaSparkContext)
}
}
And the Java class "word wount"
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.Function2;
import org.apache.spark.api.java.function.PairFunction;
import scala.Tuple2;
import java.io.Serializable;
import java.util.Arrays;
import java.util.regex.Pattern;
public final class JavaCount implements Serializable {
public static Object main(String[] args) throws Exception {
return null;
}
public Object Mafonction(JavaSparkContext sc){
String s= "a a a a b b c a";
JavaPairRDD<String, Integer> lines = sc.parallelize(Arrays.asList(s.split(" "))).mapToPair(new PairFunction<String, String, Integer>() {
#Override
public Tuple2<String, Integer> call(String s) {
return new Tuple2<String, Integer>(s, 1);
}
}).reduceByKey(new Function2<Integer, Integer, Integer>() {
#Override
public Integer call(Integer i1, Integer i2) {
return i1 + i2;
}
});
return lines.collect();
}
}
But when i execute it i got curl: (52) Empty reply from server with this error in spark job-server:
> job-server[ERROR] Uncaught error from thread [JobServer-akka.actor.default-dispatcher-13] shutting down JVM since 'akka.jvm-exit-on-fatal-error' is enabled for ActorSystem[JobServer]
job-server[ERROR] java.lang.IncompatibleClassChangeError: Implementing class
job-server[ERROR] at java.lang.ClassLoader.defineClass1(Native Method)
job-server[ERROR] at java.lang.ClassLoader.defineClass(ClassLoader.java:800)
job-server[ERROR] at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
job-server[ERROR] at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
job-server[ERROR] at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
job-server[ERROR] at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
job-server[ERROR] at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
job-server[ERROR] at java.security.AccessController.doPrivileged(Native Method)
job-server[ERROR] at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
job-server[ERROR] at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
job-server[ERROR] at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
job-server[ERROR] at spark.jobserver.JobManagerActor$$anonfun$spark$jobserver$JobManagerActor$$getJobFuture$4.apply(JobMan agerActor.scala:222)
job-server[ERROR] at scala.concurrent.impl.Future$PromiseCompletingRunnable.liftedTree1$1(Future.scala:24)
job-server[ERROR] at scala.concurrent.impl.Future$PromiseCompletingRunnable.run(Future.scala:24)
job-server[ERROR] at akka.dispatch.TaskInvocation.run(AbstractDispatcher.scala:42)
job-server[ERROR] at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(AbstractDispatcher.scala:386)
job-server[ERROR] at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
job-server[ERROR] at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
job-server[ERROR] at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
job-server[ERROR] at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
job-server ... finished with exit code 255
i fixed the problem. I just deleted all the the contenent of /tmp/Spark-JobServe and i recompiled the JobServer and It works ^^ Thank you so much for your help
Solution: Add the guava dependency:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
I'm trying to use the json-schema-validator over here: https://github.com/fge/json-schema-validator .
I'm using the following maven dependency:
<dependency>
<groupId>com.github.fge</groupId>
<artifactId>json-schema-validator</artifactId>
<version>2.2.5</version>
</dependency>
Here is a class I'm trying:
import java.io.IOException;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jackson.JsonLoader;
public class JsonSchemaTest {
public static void main(String[] args) throws IOException {
JsonNode jsonNode = JsonLoader.fromString("{\"a\":1}");
}
}
And here is the error I'm receiving:
Exception in thread "main" java.lang.NoClassDefFoundError: com/google/common/io/Closer
at com.github.fge.jackson.JsonNodeReader.fromReader(JsonNodeReader.java:120)
at com.github.fge.jackson.JsonLoader.fromReader(JsonLoader.java:179)
at com.github.fge.jackson.JsonLoader.fromString(JsonLoader.java:192)
at com.cisco.webex.squared.flume.JsonSchemaTest.main(JsonSchemaTest.java:10)
Caused by: java.lang.ClassNotFoundException: com.google.common.io.Closer
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
... 4 more
--- Edit:
If I change my maven version to 2.1.7, I can do JsonNode jsonNode = JsonLoader.fromString("{\"a\":1}"); but I cannot create the factory here without the same java.lang.NoClassDefFoundError: com/google/common/io/Closer error:
import com.fasterxml.jackson.databind.JsonNode;
import com.github.fge.jackson.JsonLoader;
import com.github.fge.jsonschema.exceptions.ProcessingException;
import com.github.fge.jsonschema.main.JsonSchema;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
import com.github.fge.jsonschema.report.ProcessingReport;
public final class JsonSchemaTest {
public static void main(final String[] args) throws IOException, ProcessingException {
//JsonNode data = JsonLoader.fromString("{\"a\":1}");
final JsonNode data = JsonLoader.fromString("{\"a\":1}");
final JsonNode fstabSchema = JsonLoader.fromString("{\"type\":\"object\", \"properties\":{\"a\":{\"type\":\"number\"}}}");
final JsonSchemaFactory factory = JsonSchemaFactory.byDefault();
final JsonSchema schema = factory.getJsonSchema(fstabSchema);
ProcessingReport report;
report = schema.validate(data);
System.out.println(report);
}
}
You have to import guava library in your project.
http://www.java2s.com/Code/Jar/g/Downloadguava150rc1jar.htm
I'm trying to parse a bit of JSON in Java by following this tutorial. Because it mentions nothing about org.apache.commons.io.IOUtils other than it imports it, I figured all it was used for it to convert an InputStream into a String. I have my own code for that, so I omitted it. Here is my code:
import java.io.*;
import java.io.InputStream;
import java.net.*;
import java.util.Scanner;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
public class Net {
static String returnParsedIp() throws UnsupportedEncodingException, MalformedURLException, IOException {
String url = "http://httpbin.org/ip";
URLConnection connection = new URL(url).openConnection();
connection.setRequestProperty("Accept-Charset", "UTF-8");
InputStream response = connection.getInputStream();
String responseString = new Scanner(response,"UTF-8").useDelimiter("\\A").next();
//return responseString;
JSONObject json = (JSONObject) JSONSerializer.toJSON(responseString);
String Ip = json.getString("origin");
return Ip;
}
}
I then call the method from my main class with:
public class DDNS {
public static void main(String[] args) throws Exception {
String Ip = Net.returnParsedIp();
System.out.println(Ip);
}
}
However, it throws the following error:
run:
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(ClassLoader.java:800)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at ddns.Net.returnParsedIp(Net.java:19)
at ddns.DDNS.main(DDNS.java:6)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.lang.exception.NestableRuntimeException
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 14 more
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
Any help is appreciated.
Either you don't have the Apache Commons lang and io JARs in your CLASSPATH or you have the wrong version.
Caused by: java.lang.ClassNotFoundException: org.apache.commons.lang.exception.NestableRuntimeException
This is Java 101. You need all the dependencies in the CLASSPATH in order to compile and run.
You have to add the commons-lang jar in yout project
I'm having trouble running this sample code for the gdata java library:
import java.net.URL;
import com.google.gdata.client.Query;
import com.google.gdata.client.blogger.BloggerService;
import com.google.gdata.data.Feed;
public class AccessBloggerSample {
public static void main(String[] args) throws Exception {
BloggerService service = new BloggerService("Testing-Blogger");
service.setUserCredentials("tmerachli#gmail.com", "XXX");
System.out.println("Google: " + BloggerService.getVersion());
URL feedUrl = new URL("http://minhchaunyc.blogspot.com/feeds/posts/default ");
Query query = new Query(feedUrl);
System.out.println("service: ");
Feed resultFeed = service.getFeed(query, Feed.class);
System.out.println("blogs: " + resultFeed.getEntries().size());
}
}
And I get the following error:
java.lang.NoClassDefFoundError: com/google/common/collect/Maps
at com.google.gdata.wireformats.AltRegistry.<init>(AltRegistry.java:118)
at com.google.gdata.wireformats.AltRegistry.<init>(AltRegistry.java:100)
at com.google.gdata.client.Service.<clinit>(Service.java:555)
at AccessBloggerSample.main(AccessBloggerSample.java:23)
Caused by: java.lang.ClassNotFoundException: com.google.common.collect.Maps
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at com.google.gdata.wireformats.AltRegistry.<init>(AltRegistry.java:118)
at com.google.gdata.wireformats.AltRegistry.<init>(AltRegistry.java:100)
at com.google.gdata.client.Service.<clinit>(Service.java:555)
at AccessBloggerSample.main(AccessBloggerSample.java:23)
at __SHELL0.run(__SHELL0.java:6)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at bluej.runtime.ExecServer$3.run(ExecServer.java:724)`
Any ideas why I'm getting this? I'm compiling and running my code through BlueJ and I extracted all the jar files into the lib directory of BlueJ and the code compiles.
You need to add guava to your Java Build-Patproject: http://code.google.com/p/guava-libraries/