javascript error"java.lang.NullPointerException" in netbeans - java

Im trying to use javascript with netbeans. Im supposed to make a mastermind game using javascript. when ı tried to add something to .js ı always have this error;
Exception in thread "main" java.lang.NullPointerException
at java.io.Reader.<init>(Reader.java:78)
at java.io.InputStreamReader.<init>(InputStreamReader.java:72)
at assgn1.Main.main(Main.java:32)
ı couldnt figur out why. thanks for any help.
my codes are;
Main.java
package assgn1;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Main {
public static void main(String[] args) throws ScriptException {
// TODO code application logic here
// create manager
ScriptEngineManager m = new ScriptEngineManager();
// create javascript script engine
ScriptEngine js = m.getEngineByName("javascript");
// evaluate "hello.js"
InputStream strm = Main.class.getResourceAsStream("/hello.js");
Reader r = new InputStreamReader(strm);
js.eval(r);
}
}
hello.js
importPackage(javax.swing);
importClass(java.lang.System);
function exit(){
System.exit(0);
}
var f= new JFrame("MasterMind");
var b= new JButton("exit");
b.addActionListener(exit);
f.add(path);
f.add(b,"South");
f.setSize(800,800);
f.visible=true;

You should check if
InputStream strm = Main.class.getResourceAsStream("/hello.js");
doesnt return a null object because the path is wrong. Seems like you get the NullPointerException because of that.

Related

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();

Java cannot find symbol symbol : method getFiles()

I'm trying to use java.awt.FileDialog in an ImageJ plugin but for some reason I am getting an error that Java cannot find the getFiles method:
C:\File_Opener3.java:50: cannot find symbol symbol : method
getFiles() location: class java.awt.FileDialog fd.getFiles();
^ 1 error
I get a similar error when trying setMultipleMode, but other methods like setVisible and getFile work fine. Can some one tell me what I am doing wrong?
import ij.plugin.*;
import ij.*;
import ij.io.*;
import java.io.*;
import javax.swing.*;
import javax.swing.filechooser.*;
import ij.gui.*;
import ij.plugin.frame.Recorder;
import ij.util.Java2;
import ij.macro.Interpreter;
import java.awt.*;
import java.awt.FileDialog;
import java.awt.Frame;
// Try to figure out why this only allows list veiw
public class File_Opener3 implements PlugIn {
//static File dir;
private static Frame sharedFrame;
private String dir;
private String name;
public void run(String arg) {
openFiles();
IJ.register( File_Opener .class);
}
public void openFiles() {
Frame parent = IJ.getInstance();
if (parent==null) {
if (sharedFrame==null) sharedFrame = new Frame();
parent = sharedFrame;
}
FileDialog fd = new FileDialog(parent, "title"); // From Java.awt.FileDialog
fd.setVisible(true);
//fd.setMultipleMode(true);
name = fd.getFile();
if (name==null) {
if (IJ.isMacOSX())
System.setProperty("apple.awt.fileDialogForDirectories", "false");
Macro.abort();
} else
dir = fd.getDirectory();
//File[] files = fd.getFiles();
fd.getFiles();
//IJ.log("48 fd.getFilenameFilter(): "+fd.getFilenameFilter());
Opener opener = new Opener();
//opener.openMultiple();
/* for (int i=0; i<files.length; i++) {
ImagePlus img = opener.openImage(path, files[i].getName());
if (img!=null)
img.show();
} */
}
}
FileDialog.getFiles() and FileDialog.setMultipleMode() were introduced in Java 1.7. You are probably compiling against an earlier version of Java. If you're using an IDE, check the source level that's set for your project.

How to get this property value in my java code?

I'm learning Java and sometimes I have some problem to retrieve the information I need from objects...
When I debug my code I can see in targetFile, a path property but I don't know how to get it in my code.
This is a screenshot:
(source: toile-libre.org)
This is my complete code:
package com.example.helloworld;
import com.github.axet.wget.WGet;
import com.github.axet.wget.info.DownloadInfo;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class HelloWorld {
public static void main(String[] args) throws IOException {
nodejs();
}
public static void nodejs() throws IOException {
// Scrap the download url.
Document doc = Jsoup.connect("http://nodejs.org/download").get();
Element link = doc.select("div.interior:nth-child(2) > table:nth-child(2) > tbody:nth-child(1) > tr:nth-child(1) > td:nth-child(3) > a:nth-child(1)").first();
String url = link.attr("abs:href");
// Print the download url.
System.out.println(url);
// Download file via the scraped url.
URL download = new URL(url);
File target = new File("/home/lan/Desktop/");
WGet w = new WGet(download, target);
w.download();
// Get the targetFile property
// ???
}
}
How can I get this value?
I do not know your code but the field you are interested in may be encapsulated and thus not accessible in your code, but the debugger can see it at runtime :)
Update:
https://github.com/axet/wget/blob/master/src/main/java/com/github/axet/wget/WGet.java
The field is default package, you can only access it from within the package.
This can be frustrating at times, but you should ask yourself why the designers of this class decided to hide this field.

java.lang.NullPointerException when using Java with Ruby

I am trying to call a ruby function in java. but I got a NullPointerException when I run the program.
Here is my java code
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.InputStream;
public class MyProgram
{
public static void main(String[] args) throws IOException, NoSuchMethodException
{
try
{
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine rbEngine = mgr.getEngineByExtension("rb");
InputStream is = ClassLoader.getSystemResourceAsStream("src/myruby.rb");
Reader reader = new InputStreamReader(is);
rbEngine.eval(reader);
Invocable invocableEngine = (Invocable)rbEngine;
if (invocableEngine != null)
{
int set = (Integer) invocableEngine.invokeFunction("myfunc",6,6);
}
}
catch (ScriptException e)
{
System.out.println("\nScriptException = "+e);
}
}
}
And the myruby.rb file contains
def myfunc(a,b)
f=a+b
return f
end
The Error I am getting is,
Exception in thread "main" java.lang.NullPointerException
at java.io.Reader.<init>(Unknown Source)
at java.io.InputStreamReader.<init>(Unknown Source)
at MyProgram.main(MyProgram.java:22)
Please help me to find the problem.
Thanks in Advance.
InputStream is = ClassLoader.getSystemResourceAsStream("src/myruby.rb");
Here, is is null.
Try an absolute path to open your file.
If your file is found, then there is a problem with the ClassLoader.getSystemResourceAsStream.
As LaGrandMere said in his answer is is null here.
It is null because ClassLoader.getSystemResourceAsStream is not able to find the resource specified.
ClassLoader looks for the resource in the classpath specified.
To get this resource available, add myruby.rb in your class path.
Hope this helps !!

Crystal report SDK JRC Passing parameter giving error Error code:-2147217394 Error code name:missingParameterValueError

When I am trying pass paramaters from crystal report SDK and export my report to PDF. It is stand alone application so I can't user crystalreportviewer options but it is keep giving me error
com.crystaldecisions.sdk.occa.report.lib.ReportSDKParameterFieldException: InternalFormatterException---- Error code:-2147217394 Error code name:missingParameterValueError My code is given below please help
import com.crystaldecisions.reports.sdk.DatabaseController;
import com.crystaldecisions.reports.sdk.ReportClientDocument;
import com.crystaldecisions.reports.sdk.ParameterFieldController;
import com.crystaldecisions.sdk.occa.report.data.IConnectionInfo;
import com.crystaldecisions.sdk.occa.report.exportoptions.ExportOptions;
import com.crystaldecisions.sdk.occa.report.exportoptions.ReportExportFormat;
import com.crystaldecisions.sdk.occa.report.lib.ReportSDKException;
public class Test {
public static void main(String args[]) throws ReportSDKException, SQLException, FileNotFoundException, IOException{
try{
ReportClientDocument reportClientDoc = new ReportClientDocument();
reportClientDoc.open("Report.rpt",0);
ParameterFieldController paramController = reportClientDoc.getDataDefController().getParameterFieldController();
paramController.setCurrentValue("","P_DP",new Integer(22));
//Here I was calling switch database code
ByteArrayInputStream byteArrayInputStream = (ByteArrayInputStream)reportClientDoc.getReportSource().export(ReportExportFormat.PDF);
IOUtils.copy(byteArrayInputStream, new FileOutputStream("new.pdf"));
reportClientDoc.close();
}
}
it starts working by just moving setting parameter code to above line. we need to set parameter before opening the report.
import com.crystaldecisions.reports.sdk.DatabaseController;
import com.crystaldecisions.reports.sdk.ReportClientDocument;
import com.crystaldecisions.reports.sdk.ParameterFieldController;
import com.crystaldecisions.sdk.occa.report.data.IConnectionInfo;
import com.crystaldecisions.sdk.occa.report.exportoptions.ExportOptions;
import com.crystaldecisions.sdk.occa.report.exportoptions.ReportExportFormat;
import com.crystaldecisions.sdk.occa.report.lib.ReportSDKException;
public class Test {
public static void main(String args[]) throws ReportSDKException, SQLException, FileNotFoundException, IOException{
try{
ReportClientDocument reportClientDoc = new ReportClientDocument();
ParameterFieldController paramController = reportClientDoc.getDataDefController().getParameterFieldController();
paramController.setCurrentValue("","P_DP",new Integer(22));
reportClientDoc.open("Report.rpt",0);
//Here I was calling switch database code
ByteArrayInputStream byteArrayInputStream = (ByteArrayInputStream)reportClientDoc.getReportSource().export(ReportExportFormat.PDF);
IOUtils.copy(byteArrayInputStream, new FileOutputStream("new.pdf"));
reportClientDoc.close();
}
}

Categories