Exception in thread “main” java.lang.Error: Unresolved compilation problems: - java

Whenver I run this program, its always throwing this error
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
And while I was trying run this code in Eclipse IDE it's telling me
declared package org.exist.examples.xmldb does not match the expected package
When I compile it it's throwing the error at Put.main(Put.java:27)
package org.exist.examples.xmldb;
import java.io.File;
import org.exist.xmldb.XmldbURI;
import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.Database;
import org.xmldb.api.modules.CollectionManagementService;
import org.xmldb.api.modules.XMLResource;
/**
* Add a document to the database.
*
* Call with java -jar start.jar org.exist.examples.xmldb.Put collection docName
*
*/
public class Put {
public final static String URI = "xmldb:exist://localhost:8080/exist/xmlrpc";
protected static void usage() {
System.out.println("usage: org.exist.examples.xmldb.Put collection docName");
System.exit(0);
}
public static void main(String args[]) throws Exception {
if(args.length < 2)
usage();
String collection = args[0], file = args[1];
// initialize driver
String driver = "org.exist.xmldb.DatabaseImpl";
Class<?> cl = Class.forName(driver);
Database database = (Database)cl.newInstance();
database.setProperty("create-database", "true");
DatabaseManager.registerDatabase(database);
// try to get collection
Collection col =
DatabaseManager.getCollection(URI + collection);
if(col == null) {
// collection does not exist: get root collection and create.
// for simplicity, we assume that the new collection is a
// direct child of the root collection, e.g. /db/test.
// the example will fail otherwise.
Collection root = DatabaseManager.getCollection(URI + XmldbURI.ROOT_COLLECTION);
CollectionManagementService mgtService =
(CollectionManagementService)root.getService("CollectionManagementService", "1.0");
col = mgtService.createCollection(collection.substring((XmldbURI.ROOT_COLLECTION + "/").length()));
}
File f = new File(file);
// create new XMLResource
XMLResource document = (XMLResource)col.createResource(f.getName(), "XMLResource");
document.setContent(f);
System.out.print("storing document " + document.getId() + "...");
col.storeResource(document);
System.out.println("ok.");
}
}

You are trying to run code that does not compile. Eclipse inserts bytecode that throws this error instead.

Related

java.lang.NullPointerException: inStream parameter is null in my Maven Project

I made a structure change in my project, and I am getting this error
Project Structure:
enter image description here
the platform notifies me of the following error:
Step failed
java.lang.NullPointerException: inStream parameter is null
at java.base/java.util.Objects.requireNonNull(Objects.java:233)
at java.base/java.util.Properties.load(Properties.java:407)
at com.crm.framework.config.ConfigReader.ReadProperty(ConfigReader.java:19)
at com.crm.framework.config.ConfigReader.PopulateSettings(ConfigReader.java:11)
at steps.TestInitialize.Initialize(TestInitialize.java:21)
This is my ConfigReader, which is shown in the above error
ConfigReader:
package com.crm.framework.config;
import com.crm.framework.base.BrowserType;
import java.io.IOException;
import java.util.Properties;
public class ConfigReader {
public static void PopulateSettings() throws IOException {
ConfigReader reader = new ConfigReader();
reader.ReadProperty();
}
private void ReadProperty() throws IOException {
//Create Property Object
Properties p = new Properties();
//Load the property file available in same package
p.load(getClass().getResourceAsStream("GlobalConfig.properties"));
//Get AUTConnection String
Settings.AUTConnectionString = p.getProperty("AUTConnectionString");
//Get Reporting String
Settings.ReportingConnectionString = p.getProperty("ReportingConnectionString");
//Get LogPath
Settings.LogPath = p.getProperty("LogPath");
//Get DriverType
Settings.DriverType = p.getProperty("DriverType");
//Get ExcelSheetPath
Settings.ExcelSheetPath = p.getProperty("ExcelSheetPath");
//Get AUT
Settings.AUT = p.getProperty("AUT");
//Browser Type
Settings.BrowserType = BrowserType.valueOf(p.getProperty("BrowserType"));
}
}
I also attach the code of the TestInitialize, file that contains the #Before to run the test cases
TestInitialize:
package steps;
import com.crm.framework.base.DriverContext;
import com.crm.framework.base.FrameworkInitialize;
import com.crm.framework.config.ConfigReader;
import com.crm.framework.config.Settings;
import com.crm.framework.utilities.LogUtil;
import io.cucumber.java.Before;
// import io.cucumber.java.Before;
import java.io.IOException;
public class TestInitialize extends FrameworkInitialize {
#Before
public void Initialize() throws IOException {
//Initialize config
ConfigReader.PopulateSettings();
//Logging
Settings.Logs = new LogUtil();
Settings.Logs.CreateLogFile();
Settings.Logs.Write("Framework initialize");
//Create Test Cycle for Reporting
/*
Pending
*/
Settings.Logs.Write("Test Cycle Created");
InitializeBrowser(Settings.BrowserType);
Settings.Logs.Write("Browser initialize");
DriverContext.Browser.GotoUrl(Settings.AUT);
Settings.Logs.Write("Navigate to URL: " + Settings.AUT);
}
}
Here is the most likely culprit:
https://docs.oracle.com/javase/10/docs/api/java/util/Properties.html#getProperty(java.lang.String)
From Javadoc:
public String getProperty​(String key)
Searches for the property with the specified key in this property list. If the key is not found in
this property list, the default property list, and its defaults,
recursively, are then checked. The method returns null if the property
is not found.
Properties are case sensitive. Make sure that:
The property file you need exists, then
The property key inside the file exists and lastly
It is spelled out the exact same way it appears in the file.
As a failsafe, you could use getProperty(key, defaultValue)which it is similar to the one above, except that it returns the passed default value instead of null in cases where the property key being passed to the method doesn't exist in the given property file.
Also, make sure the PATH to the property file is correct. Understanding how file paths are resolved when running from IDE and from deploy environment could also be an issue if you don't understand how resources are resolved.

using Neo4j embedded in Java applications

I am trying to use Neo4j embedded in Java applications, and I am using this code:
package com.tp.neo4j.java.examples;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
public class Neo4jJavaAPIDBOperation {
public static void main(String[] args) {
GraphDatabaseFactory dbFactory = new GraphDatabaseFactory();
GraphDatabaseService db = dbFactory.newEmbeddedDatabase("C:/TPNeo4jDB");
try (Transaction tx = db.beginTx()) {
// Perform DB operations
tx.success();
}
}
}
But I got this Exception:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The method newEmbeddedDatabase(File) in the type GraphDatabaseFactory is not applicable for the arguments (String)
Syntax error on token ";", try expected after this token
any idea, please
newEmbeddedDatabase expect File as argument
GraphDatabaseService db = dbFactory.newEmbeddedDatabase(new File("C:/TPNeo4jDB"));

Java NoClassDefFoundError amf

I'm trying to compile a java snippet into a jar file, I got into a classical java runtime exception but I'm unable to solve the problem.
This is the code, borrowed from Markus Wulftange:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import flex.messaging.io.SerializationContext;
import flex.messaging.io.amf.ActionContext;
import flex.messaging.io.amf.ActionMessage;
import flex.messaging.io.amf.AmfMessageDeserializer;
import flex.messaging.io.amf.AmfMessageSerializer;
import flex.messaging.io.amf.MessageBody;
public class Amf3ExternalizableUnicastRef {
public static void main(String[] args) throws IOException, ClassNotFoundException {
if (args.length < 2 || (args.length == 3 && !args[0].equals("-d"))) {
System.err.println("usage: java -jar " + Amf3ExternalizableUnicastRef.class.getSimpleName() + ".jar [-d] <host> <port>");
return;
}
boolean doDeserialize = false;
if (args.length == 3) {
doDeserialize = true;
args = Arrays.copyOfRange(args, 1, args.length);
}
// generate the UnicastRef object
Object unicastRef = generateUnicastRef(args[0], Integer.parseInt(args[1]));
// serialize object to AMF message
byte[] amf = serialize(unicastRef);
// deserialize AMF message
if (doDeserialize) {
deserialize(amf);
} else {
System.out.write(amf);
}
}
public static Object generateUnicastRef(String host, int port) {
java.rmi.server.ObjID objId = new java.rmi.server.ObjID();
sun.rmi.transport.tcp.TCPEndpoint endpoint = new sun.rmi.transport.tcp.TCPEndpoint(host, port);
sun.rmi.transport.LiveRef liveRef = new sun.rmi.transport.LiveRef(objId, endpoint, false);
return new sun.rmi.server.UnicastRef(liveRef);
}
public static byte[] serialize(Object data) throws IOException {
MessageBody body = new MessageBody();
body.setData(data);
ActionMessage message = new ActionMessage();
message.addBody(body);
ByteArrayOutputStream out = new ByteArrayOutputStream();
AmfMessageSerializer serializer = new AmfMessageSerializer();
serializer.initialize(SerializationContext.getSerializationContext(), out, null);
serializer.writeMessage(message);
return out.toByteArray();
}
public static void deserialize(byte[] amf) throws ClassNotFoundException, IOException {
ByteArrayInputStream in = new ByteArrayInputStream(amf);
AmfMessageDeserializer deserializer = new AmfMessageDeserializer();
deserializer.initialize(SerializationContext.getSerializationContext(), in, null);
deserializer.readMessage(new ActionMessage(), new ActionContext());
}
}
Using the package flex-messaging-core, located in the same directory, I compiled into a jar with
javac -cp flex...jar sourcefile.java.
Then compiled to a jar with
jar -cfm myjar.jar MANIFEST.ML myclass.class.
But then, when running from shell with proper arguments
java -jar myjar.jar -d 127.0.0.1 8000
it throws an Exception in threadmain java.lang.NoClassDefFoundError : flex/messaging/io/amf/MessageBody.
I googled and tried all solutions for 2 days, but really can't solve the problem by myself, can I kindly ask for a little help?
Shouldn't it be MANIFEST.MF, not MANIFEST.ML?

Exception while calling Parser method outside main class

In my application I have a method which I cant execute without main method. It only runs inside the main method. When I call that method inside my servlet class. It show an exception
My class with Main Method
package com.books.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.HashSet;
import java.util.Set;
import opennlp.tools.cmdline.parser.ParserTool;
import opennlp.tools.parser.Parse;
import opennlp.tools.parser.Parser;
import opennlp.tools.parser.ParserFactory;
import opennlp.tools.parser.ParserModel;
public class ParserTest {
// download
public void download(String url, File destination) throws IOException, Exception {
URL website = new URL(url);
ReadableByteChannel rbc = Channels.newChannel(website.openStream());
FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
rbc.close();
}
public static Set<String> nounPhrases = new HashSet<>();
private static String line = "The Moon is a barren, rocky world ";
public void getNounPhrases(Parse p) {
if (p.getType().equals("NN") || p.getType().equals("NNS") || p.getType().equals("NNP")
|| p.getType().equals("NNPS")) {
nounPhrases.add(p.getCoveredText());
}
for (Parse child : p.getChildren()) {
getNounPhrases(child);
}
}
public void parserAction() throws Exception {
// InputStream is = new FileInputStream("en-parser-chunking.bin");
File modelFile = new File("en-parser-chunking.bin");
if (!modelFile.exists()) {
System.out.println("Downloading model.");
download("https://drive.google.com/uc?export=download&id=0B4uQtYVPbChrY2ZIWmpRQ1FSVVk", modelFile);
}
ParserModel model = new ParserModel(modelFile);
Parser parser = ParserFactory.create(model);
Parse topParses[] = ParserTool.parseLine(line, parser, 1);
for (Parse p : topParses) {
// p.show();
getNounPhrases(p);
}
}
public static void main(String[] args) throws Exception {
new ParserTest().parserAction();
System.out.println("List of Noun Parse : " + nounPhrases);
}
}
It gives me below output
List of Noun Parse : [barren,, world, Moon]
Then I commented the main method and. Called the ParserAction() method in my servlet class
if (name.equals("bkDescription")) {
bookDes = value;
try {
new ParserTest().parserAction();
System.out.println("Nouns Are"+ParserTest.nounPhrases);
} catch (Exception e) {
}
It gives me the below exceptions
And below error in my Browser
Why is this happening ? I can run this with main method. But when I remove main method and called in my servlet. it gives an exception. Is there any way to fix this issue ?
NOTE - I have read below instructions in OpenNLP documentation , but I have no clear idea about it. Please help me to fix his issue.
Unlike the other components to instantiate the Parser a factory method
should be used instead of creating the Parser via the new operator.
The parser model is either trained for the chunking parser or the tree
insert parser the parser implementation must be chosen correctly. The
factory method will read a type parameter from the model and create an
instance of the corresponding parser implementation.
Either create an object of ParserTest class or remove new keyword in this line new ParserTest().parserAction();

Learning Java Compiler APIs,why does trees.getElement(treepath) return null?

I'm trying to parse a java file with Java Compiler APIs.
The documents are very poor. After hours of digging I still cannot get the Trees#getElement work for me. Here's my code:
import com.sun.source.tree.*;
import com.sun.source.util.*;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.IOException;
import java.nio.CharBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class CodeAnalyzerTreeVisitor extends TreePathScanner<Object, Trees> {
#Override
public Object visitClass(ClassTree classTree, Trees trees) {
System.out.println("className " + classTree.getSimpleName());
//prints name of class
TreePath path = getCurrentPath();
printLocationAndSource(trees, path, classTree);
//prints the original source code
while (path != null) {
System.out.println("treepath");
System.out.println(trees.getElement(path));
path = path.getParentPath();
}
//it prints several nulls here
//why?
return super.visitClass(classTree, trees);
}
public static void printLocationAndSource(Trees trees,
TreePath path, Tree tree) {
SourcePositions sourcePosition = trees.getSourcePositions();
long startPosition = sourcePosition.
getStartPosition(path.getCompilationUnit(), tree);
long endPosition = sourcePosition.
getEndPosition(path.getCompilationUnit(), tree);
JavaFileObject file = path.getCompilationUnit().getSourceFile();
CharBuffer sourceContent = null;
try {
sourceContent = CharBuffer.wrap(file.getCharContent(true).toString().toCharArray());
} catch (IOException e) {
e.printStackTrace();
}
CharBuffer relatedSource = null;
if (sourceContent != null) {
relatedSource = sourceContent.subSequence((int) startPosition, (int) endPosition);
}
System.out.println("start: " + startPosition + " end: " + endPosition);
// System.out.println("source: "+relatedSource);
System.out.println();
}
}
public class JavaParser {
private static final JavaCompiler javac
= ToolProvider.getSystemJavaCompiler();
private static final String filePath = "/home/pinyin/Source/hadoop-common/hadoop-yarn-project/hadoop-ya" +
"rn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/ya" +
"rn/server/resourcemanager/ResourceManager.java";
public static void main(String[] args) throws IOException {
StandardJavaFileManager jfm = javac.getStandardFileManager(null, null, null);
Iterable<? extends javax.tools.JavaFileObject> javaFileObjects = jfm.getJavaFileObjects(filePath);
String[] sourcePathParam = {
"-sourcepath",
"/home/pinyin/Source/hadoop-common/hadoop-yarn-project/hadoop-yarn/" +
"hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/"
};
List<String> params = new ArrayList<String>();
params.addAll(Arrays.asList(sourcePathParam));
JavacTask task = (JavacTask) javac.getTask(null, jfm, null, params, null, javaFileObjects);
Iterable<? extends CompilationUnitTree> asts = task.parse();
Trees trees = Trees.instance(task);
for (CompilationUnitTree ast : asts) {
new CodeAnalyzerTreeVisitor().scan(ast, trees);
}
}
}
The lines about params and -sourcepath are added because I thought the compiler is trying to find the source file in the wrong places. They didn't work.
I'm still trying to understand how the Trees, javac and related JSRs work together, are there any recommended documents for beginners?
Thanks for your help.
edit:
The java file I'm trying to analyze is:
https://github.com/apache/hadoop-common/blob/trunk/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/ResourceManager.java
The file can be compiled without errors in its maven project, but its dependencies are not passed to javac in my situation. I'm not sure if this is the problem.
The trees.getElement returns null in the middle part of the code above, while the other parts seems to work well.
According to this answer, it seems that the Elements' information is not usable until the compilation is completed.
So calling task.analyze() solved my problem. Although javac is complaining about missing dependencies.
Please correct me if I'm wrong, thanks.

Categories