It is the code from HitHub for my learning purpose. And I tried run it in eclipse and got errors like following:
Exception in thread "main" org.matsim.core.utils.io.UncheckedIOException: java.io.FileNotFoundException: args[0]
at org.matsim.core.utils.io.IOUtils.getBufferedReader(IOUtils.java:125)
at org.matsim.core.utils.io.IOUtils.getBufferedReader(IOUtils.java:72)
at org.matsim.core.utils.io.MatsimXmlParser.parse(MatsimXmlParser.java:147)
at org.matsim.core.config.ConfigUtils.loadConfig(ConfigUtils.java:59)
at test1.RunCarsharing.main(RunCarsharing.java:23)
Caused by: java.io.FileNotFoundException: args[0]
... 5 more
And the main program is as following:
public class RunCarsharing {
public static void main(String[] args) {
Logger.getLogger( "org.matsim.core.controler.Injector" ).setLevel(Level.OFF);
final Config config = ConfigUtils.loadConfig(args[0]);
CarsharingUtils.addConfigModules(config);
final Scenario sc = ScenarioUtils.loadScenario(config);
final Controler controler = new Controler( sc );
installCarSharing(controler);
controler.run();
}
public static void installCarSharing(final Controler controler) {
Scenario sc = controler.getScenario() ;
controler.addOverridingModule( new AbstractModule() {
#Override
public void install() {
this.addPlanStrategyBinding("RandomTripToCarsharingStrategy").to( RandomTripToCarsharingStrategy.class ) ;
this.addPlanStrategyBinding("CarsharingSubtourModeChoiceStrategy").to( CarsharingSubtourModeChoiceStrategy.class ) ;
}
});
controler.addOverridingModule(new AbstractModule() {
#Override
public void install() {
bindMobsim().toProvider( CarsharingQsimFactory.class );
}
});
controler.setTripRouterFactory(CarsharingUtils.createTripRouterFactory(sc));
//setting up the scoring function factory, inside different scoring functions are set-up
controler.setScoringFunctionFactory(new CarsharingScoringFunctionFactory( sc.getConfig(), sc.getNetwork()));
final CarsharingConfigGroup csConfig = (CarsharingConfigGroup) controler.getConfig().getModule(CarsharingConfigGroup.GROUP_NAME);
controler.addControlerListener(new CarsharingListener(controler,
csConfig.getStatsWriterFrequency() ) ) ;
}
}
If the code and stacktrace are accurate, then the only way you can get that exception message is if something is trying to open a file whose filename is "args[0]".
Related
I have created a cron job that start during application restart but when i tried to create db connection i am geeting null pointer exception. I am able to create and use db from other module using same configuration.
Below is my Application.conf
db.abc.driver=com.mysql.jdbc.Driver
db.abc.url="jdbc:mysql://localhost:3306/db_name?useSSL=false"
db.abc.username=root
db.abc.password=""
db.abc.autocommit=false
db.abc.isolation=READ_COMMITTED
And code that tried to access db is
public class SchduleJob extends AbstractModule{
#Override
protected void configure() {
bind(JobOne.class)
.to(JobOneImpl.class)
.asEagerSingleton();
} }
#ImplementedBy(JobOneImpl.class)
public interface JobOne {}
#Singleton
public class JobOneImpl implements JobOne {
final ActorSystem actorSystem = ActorSystem.create("name");
final ActorRef alertActor = actorSystem.actorOf(AlertActor.props);
public JobOneImpl() {
scheduleJobs();
}
private Cancellable scheduleJobs() {
return actorSystem.scheduler().schedule(
Duration.create(0, TimeUnit.MILLISECONDS), //Initial delay 0 milliseconds
Duration.create(6, TimeUnit.MINUTES), //Frequency 30 minutes
alertActor,
"alert",
actorSystem.dispatcher(),
null
);
}
}
public class AlertActor extends UntypedActor{
public static Props props = Props.create(AlertActor.class);
final ActorSystem actorSystem = ActorSystem.create("name");
final ActorRef messageActor = actorSystem.actorOf(MessageActor.props());
#Override
public void onReceive(Object message) throws Exception {
if(message != null && message instanceof String) {
RequestDAO requestDAO = new RequestDAO();
try {
List<DBRow> rows = requestDAO.getAllRow();
} catch(Exception exception) {
exception.printStackTrace();
}
}
}
}
public class RequestDAO {
public List<DBRow> getAllRow() throws Exception {
List<DBRow> rows = new ArrayList<DBRow>();
Connection connection = null;
try {
connection = DB.getDataSource("abc").getConnection();
connection.setAutoCommit(false);
} catch(Exception exception) {
exception.printStackTrace();
if(connection != null) {
connection.rollback();
} else {
System.out.println("in else***********");
}
return null;
} finally {
if(connection != null)
connection.close();
}
return schools;
}
When i am calling method getAllRow() of RequestDAO class it's throwing
java.lang.NullPointerException
at play.api.Application$$anonfun$instanceCache$1.apply(Application.scala:235)
at play.api.Application$$anonfun$instanceCache$1.apply(Application.scala:235)
at play.utils.InlineCache.fresh(InlineCache.scala:69)
at play.utils.InlineCache.apply(InlineCache.scala:55)
at play.api.db.DB$.db(DB.scala:22)
at play.api.db.DB$.getDataSource(DB.scala:41)
at play.api.db.DB.getDataSource(DB.scala)
at play.db.DB.getDataSource(DB.java:33)
But same code is working without cron job. What should i do to remove this error
Play uses the Typesafe config library for configuration.
I suspect your current working directory from the cron script isn't set, so it's probably not finding your application.conf (application.properties) file.
However, Config is nice in that it allows you to specify where to look for the file, either by its base name (to choose among .conf | .properties | .json extensions) or the filename including the extension on the java command line:
To specify the base name, use -Dconfig.resource=/path/to/application
To specify the full name, use -Dconfig.file=/path/to/application.properties
I am getting the following error when running nachos in eclipse:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
at nachos.machine.Lib.assertTrue(Lib.java:75)
at nachos.machine.Machine.main(Machine.java:24)
The above two methods are as follows:
nachos.machine.Lib.assertTrue:
public static void assertTrue(boolean expression) {
if (!expression)
throw new AssertionFailureError();
}
nachos.machine.Machine.main:
public static void main(final String[] args) {
System.out.println("nachos 5.0j initializing...");
Lib.assertTrue(Machine.args == null);//This is the call after which error is thrown
Machine.args = args;
processArgs();
Config.load(configFileName);
// get the current directory (.)
baseDirectory = new File(new File("").getAbsolutePath());
// get the nachos directory (./nachos)
nachosDirectory = new File(baseDirectory, "nachos");
String testDirectoryName =
Config.getString("FileSystem.testDirectory");
// get the test directory
if (testDirectoryName != null) {
testDirectory = new File(testDirectoryName);
}
else {
// use ../test
testDirectory = new File(baseDirectory.getParentFile(), "test");
}
securityManager = new NachosSecurityManager(testDirectory);
privilege = securityManager.getPrivilege();
privilege.machine = new MachinePrivilege();
TCB.givePrivilege(privilege);
privilege.stats = stats;
securityManager.enable();
createDevices();
checkUserClasses();
autoGrader = (AutoGrader) Lib.constructObject(autoGraderClassName);
new TCB().start(new Runnable() {
public void run() { autoGrader.start(privilege); }
});
}
I had this same error come up for me when I was trying to run nachos through eclipse. What I did was to look at Lib.java and scroll down to the function with an eclipse error on it. For me it was checkDerivation. There should be an eclipse error on the parameters <?>, if you look at the auto fix eclipse gives you and pick the project wide fix nachos should run after that.
I am using multi text output formate to create multiple files of a single file i.e each line on new file.
This is my code:
public class MOFExample extends Configured implements Tool {
private static double count = 0;
static class KeyBasedMultipleTextOutputFormat extends
MultipleTextOutputFormat<Text, Text> {
#Override
protected String generateFileNameForKeyValue(Text key, Text value,
String name) {
return count++ + "_";// + name;
}
}
/**
* The main job driver.
*/
public int run(final String[] args) throws Exception {
Path csvInputs = new Path(args[0]);
Path outputDir = new Path(args[1]);
JobConf jobConf = new JobConf(super.getConf());
jobConf.setJarByClass(MOFExample.class);
jobConf.setMapperClass(IdentityMapper.class);
jobConf.setInputFormat(KeyValueTextInputFormat.class);
jobConf.setOutputFormat(KeyBasedMultipleTextOutputFormat.class);
jobConf.setOutputValueClass(Text.class);
jobConf.setOutputKeyClass(Text.class);
FileInputFormat.setInputPaths(jobConf, csvInputs);
FileOutputFormat.setOutputPath(jobConf, outputDir);
//jobConf.setNumMapTasks(4);
jobConf.setNumReduceTasks(4);
return JobClient.runJob(jobConf).isSuccessful() ? 0 : 1;
}
public static void main(final String[] args) throws Exception {
int res = ToolRunner.run(new Configuration(), new MOFExample(), args);
System.exit(res);
}
}
This code runs fine on small text file but when the number of lines of input file are greater than 1900 which is yet not a large file it throws an exception:
Exception in thread "main" java.io.IOException: Job failed!
at org.apache.hadoop.mapred.JobClient.runJob(JobClient.java:836)
at MOFExample.run(MOFExample.java:57)
at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
at MOFExample.main(MOFExample.java:61)
I also tried this tutorial but this one returns empty output directory without any exception when the input file is large however this one also worked fine with small input file.
Note: I am using Single-Node Cluster
I have a problem regarding java.lang.NoSuchMethodError. This program is about Compiler API (JSR 199). When I create a prototype for this it run work, but when I try to make it to become library it throw NoSuchMethodError Exception.
Here is the First Prototype:
public class DynaCompTest {
public static void main(String[] args) {
String fullName = "HelloWorld";
StringBuilder sourceCode = new StringBuilder();
sourceCode.append("public class HelloWorld {\n")
.append("\tpublic static void main(String[] args) {\n")
.append("\t\tSystem.out.println(\"Hello World\")\n")
.append("\t}\n")
.append("}");
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
JavaFileManager fileManager = new ClassFileManager(compiler.getStandardFileManager(null, null, null));
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
List<JavaFileObject> jFiles = new ArrayList<>();
jFiles.add(new CharSequenceJavaFileObject(fullName, sourceCode));
compiler.getTask(null, fileManager, diagnostics, null, null, jFiles).call();
for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
System.out.format("Error on line %d in %s\n", diagnostic.getLineNumber(), diagnostic);
}
}
}
public class CharSequenceJavaFileObject extends SimpleJavaFileObject {
private CharSequence content;
public CharSequenceJavaFileObject(String className, CharSequence content) {
super(URI.create("string:///" + className.replace('.', '/') + Kind.SOURCE.extension), Kind.SOURCE);
this.content = content;
}
#Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return content;
}
}
public class ClassFileManager extends ForwardingJavaFileManager {
private JavaClassObject jClassObject;
public ClassFileManager(StandardJavaFileManager standardManager) {
super(standardManager);
}
#Override
public ClassLoader getClassLoader(Location location) {
return new SecureClassLoader() {
#Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
byte[] b = jClassObject.getBytes();
return super.defineClass(name, jClassObject.getBytes(), 0, b.length);
}
};
}
#Override
public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind, FileObject sibling) throws IOException {
jClassObject = new JavaClassObject(className, kind);
return jClassObject;
}
}
public class JavaClassObject extends SimpleJavaFileObject {
protected final ByteArrayOutputStream bos = new ByteArrayOutputStream();
public JavaClassObject(String name, Kind kind) {
super(URI.create("string:///" + name.replace('.', '/') + kind.extension), kind);
}
public byte[] getBytes() {
return bos.toByteArray();
}
#Override
public OutputStream openOutputStream() {
return bos;
}
}
I changed the DynaCompTest become DynamicCompiler for the library:
public class DynamicCompiler {
private JavaCompiler compiler;
private JavaFileManager fileManager;
private List<JavaFileObject> jFiles;
private DiagnosticCollector<JavaFileObject> diagnostics;
public DiagnosticCollector<JavaFileObject> getDiagnostics() {
return diagnostics;
}
public DynamicCompiler(String className, StringBuilder sourceCode) {
compiler = ToolProvider.getSystemJavaCompiler();
fileManager = new ClassFileManager(compiler.getStandardFileManager(null, null, null));
diagnostics = new DiagnosticCollector<>();
jFiles = new ArrayList<>();
jFiles.add(new CharSequenceJavaFileObject(className, sourceCode));
}
public boolean doCompilation() {
return compiler.getTask(null, fileManager, diagnostics, null, null, jFiles).call();
}
}
And I created Second Prototype to test the library:
public class Compiler {
private static StringBuilder sourceCode = new StringBuilder();
public static void main(String[] args) {
boolean status;
sourceCode.append("public class HelloWorld {\n")
.append("\tpublic static void main(String[] args) {\n")
.append("\t\tSystem.out.println(\"Hello World\");\n")
.append("\t}\n")
.append("}");
DynamicCompiler compiler = new DynamicCompiler("HelloWorld", sourceCode);
status = compiler.doCompilation();
StringBuilder messages = new StringBuilder();
if (!status) {
for (Diagnostic diagnostic : compiler.getDiagnostics().getDiagnostics()) {
messages.append("Error on line ")
.append(diagnostic.getLineNumber())
.append(" in ")
.append(diagnostic)
.append("\n");
}
} else {
messages.append("BUILD SUCCESSFUL ");
}
System.out.println(messages.toString());
}
}
When I test with code above it run well and print BUILD SUCCESSFUL but when I tried to make it error for example I deleted the semicolon ; like the first prototype, it throw the NoSuchMethodError Exception when access the compiler.getDiagnostics().getDiagnostics() inside the looping.
The question is, why in the First Prototype it run well when try to make an error but when I tried with my own library it become Exception?
Edit
Here is the stacktrace:
/HelloWorld.java:3: error: ';' expected
System.out.println("Hello World")
^
1 error
Exception in thread "main" java.lang.NoSuchMethodError: org.ert.lib.DynamicCompiler.getDiagnostics()Ljavax/tools/DiagnosticCollector;
at org.ert.exp.Compiler.main(Compiler.java:28)
Java Result: 1
It should be like this:
Error on line 3 in /HelloWorld.java:3: error: ';' expected
System.out.println("Hello World")
^
When trying to debug it, it shown an error:
public DiagnosticCollector<JavaFileObject> getDiagnostics() {
return diagnostics; // Set Breakpoint here
}
Here is the error message:
Not able to submit breakpoint LineBreakpoint DynamicCompiler.java : 25, reason: No executable location available at line 25 in class org.ert.lib.DynamicCompiler.
Invalid LineBreakpoint DynamicCompiler.java : 25
Update
Got the problem, this problem will occur if we add the whole project instead build the jar of the library. So when I build the library jar it works. But anyone can explain why this thing happen when I try add the whole project instead the jar file?
Note
I'm using:
JDK 1.7 from Oracle
Netbeans 7.1.1
It seems that you have similar class exists in two different libraries(jars).
e.g.
com.test.Example.class in a.jar
com.test.Example.class in b.jar
Now class loader will load the first first Example.class and it seems that you need class which is there in b.jar. Then it will not throw exception such as NoMethodFound but throw an Exception that NoSuchMethodFound because class still exists in memory but can not find required method.
Such problems can be resolved by changing library order. You need to make required library's order higher. You can do this from the eclipse
Project Setting -> Java Build Path -> Order and Export.
Hope this is helpful.
After I tried with Eclipse Indigo, I found that it works when add the Project or add the jar file. While in Netbeans 7.1.1 will get an error if add the Project, but works if add the jar file.
Maybe it one of the bugs of Netbeans...
Thank you for your attention...
Below are some code fragments that indicate what I am trying at the moment, but its unreliable. Princiaply I think
because you can only register a protocol handler once, and occasionally other libraries may be doing this first.
import org.apache.xerces.util.XMLCatalogResolver;
public static synchronized XMLCatalogResolver getResolver() {
String c[] = {"classpath:xml-catalog.xml"};
if (cr==null) {
log.debug("Registering new protcol handler for classpath");
ConfigurableStreamHandlerFactory configurableStreamHandlerFactory = new ConfigurableStreamHandlerFactory("classpath", new org.fao.oek.protocols.classpath.Handler(XsdUtils.class.getClassLoader()));
configurableStreamHandlerFactory.addHandler("http", new sun.net.www.protocol.http.Handler());
URL.setURLStreamHandlerFactory(configurableStreamHandlerFactory);
log.debug("Creating new catalog resolver");
cr = new XMLCatalogResolver(c);
}
return cr;
}
xml-catalog.xml contains:
<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog">
<group prefer="public" xml:base="classpath:org/me/myapp/xsd/" >
<uri name="http://www.w3.org/XML/1998/namespace" uri="xml.xsd"/>
<uri name="http://www.w3.org/1999/xlink" uri="xlink.xsd" />
<uri name="http://www.w3.org/2001/XMLSchema" uri="XMLSchema.xsd" />
<uri name="http://purl.org/dc/elements/1.1/" uri="dc.xsd" />
<uri name="http://www.loc.gov/mods/v3" uri="mods-3.3.xsd" />
</group>
</catalog>
Obviously - the xsd files exist at the right place in the classpath.
The resolver acted properly with the following minimum set of code:
public class XsdUtils {
static {
System.setProperty("java.protocol.handler.pkgs", "org.fao.oek.protocols");
}
private static XMLCatalogResolver cr;
public static synchronized XMLCatalogResolver getResolver() {
if (cr == null) {
cr = new XMLCatalogResolver(new String[] { "classpath:xml-catalog.xml" });
}
return cr;
}
public static void main(String[] args) throws MalformedURLException, IOException {
XMLCatalogResolver resolver = getResolver();
URL url0 = new URL("classpath:xml-catalog.xml");
URL url1 = new URL(resolver.resolveURI("http://www.loc.gov/mods/v3"));
url0.openConnection();
url1.openConnection();
}
}
You can alternatively specify java.protocol.handler.pkgs as a JVM argument:
java -Djava.protocol.handler.pkgs=org.fao.oek.protocols ...
The Handler class was implemented as follows:
package org.fao.oek.protocols.classpath;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
public class Handler extends java.net.URLStreamHandler {
#Override
protected URLConnection openConnection(URL u) throws IOException {
String resource = u.getPath();
if (!resource.startsWith("/")) resource = "/" + resource;
System.out.println(getClass().getResource(resource));
return getClass().getResource(resource).openConnection();
}
}
It is important to have the forward slash ("/") when requesting the resource, as answered by this Stack Overflow question: "open resource with relative path in java."
Note the main method in XsdUtils. The output to the program when xml-catalog.xml and mods-3.3.xsd are on the classpath but not in a JAR is:
file:/workspace/8412798/target/classes/xml-catalog.xml
file:/workspace/8412798/target/classes/org/me/myapp/xsd/mods-3.3.xsd
The output to the program when the files are in a JAR is:
jar:file:/workspace/8412798/target/stackoverflow.jar!/xml-catalog.xml
jar:file:/workspace/8412798/target/stackoverflow.jar!/org/me/myapp/xsd/mods-3.3.xsd
With respect to this code in the original question:
new org.fao.oek.protocols.classpath.Handler(XsdUtils.class.getClassLoader())
your Handler does not need a specific class loader unless you have configured your application to use a special class loader, like one extended from URLClassLoader.
"A New Era for Java Protocol Handlers" is a good resource about protocol handlers.
Just to bring everything full circle, the following class uses XsdUtils.getResolver() to parse XML. It validates against the schemas specified in the XMLCatalogResolver:
public class SampleParser {
public static void main(String[] args) throws Exception {
String xml = "<?xml version=\"1.0\"?>" + //
"<mods ID=\"id\" version=\"3.3\" xmlns=\"http://www.loc.gov/mods/v3\">" + //
"<titleInfo></titleInfo>" + //
"</mods>";
ByteArrayInputStream is = new ByteArrayInputStream(xml.getBytes());
XMLReader parser = XMLReaderFactory.createXMLReader(org.apache.xerces.parsers.SAXParser.class.getName());
parser.setFeature("http://xml.org/sax/features/validation", true);
parser.setFeature("http://apache.org/xml/features/validation/schema", true);
parser.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
parser.setProperty("http://apache.org/xml/properties/internal/entity-resolver", XsdUtils.getResolver());
parser.setErrorHandler(new ErrorHandler() {
#Override
public void error(SAXParseException exception) throws SAXException {
System.out.println("error: " + exception);
}
#Override
public void fatalError(SAXParseException exception) throws SAXException {
System.out.println("fatalError: " + exception);
}
#Override
public void warning(SAXParseException exception) throws SAXException {
System.out.println("warning: " + exception);
}
});
parser.parse(new InputSource(is));
}
}