Javassist CannotCompileException when trying to add a line to create a Map - java

um trying to instrument a method to do the following task.
Task - Create a Map and insert values to the map
Adding System.out.println lines wouldn't cause any exception. But when i add the line to create the Map, it throws a cannotCompileException due to a missing ;. When i print the final string it doesn't seem to miss any. What am i doing wrong here.
public void createInsertAt(CtMethod method, int lineNo, Map<String,String> parameterMap)
throws CannotCompileException {
StringBuilder atBuilder = new StringBuilder();
atBuilder.append("System.out.println(\"" + method.getName() + " is running\");");
atBuilder.append("java.util.Map<String,String> arbitraryMap = new java.util.HashMap<String,String>();");
for (Map.Entry<String,String> entry : parameterMap.entrySet()) {
}
System.out.println(atBuilder.toString());
method.insertAt(1, atBuilder.toString());
}
String obtained by printing the output of string builder is,
System.out.println("prepareStatement is
running");java.util.Map arbitraryMap = new
java.util.HashMap();
Exception received is,
javassist.CannotCompileException: [source error] ; is missing
at javassist.CtBehavior.insertAt(CtBehavior.java:1207)
at javassist.CtBehavior.insertAt(CtBehavior.java:1134)
at org.wso2.das.javaagent.instrumentation.InstrumentationClassTransformer.createInsertAt(InstrumentationClassTransformer.java:126)
at org.wso2.das.javaagent.instrumentation.InstrumentationClassTransformer.instrumentMethod(InstrumentationClassTransformer.java:100)
at org.wso2.das.javaagent.instrumentation.InstrumentationClassTransformer.transform(InstrumentationClassTransformer.java:37)
at sun.instrument.TransformerManager.transform(TransformerManager.java:188)
at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:424)
at sun.instrument.InstrumentationImpl.retransformClasses0(Native Method)
at sun.instrument.InstrumentationImpl.retransformClasses(InstrumentationImpl.java:144)
at org.wso2.das.javaagent.instrumentation.Agent.premain(Agent.java:39)
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:606)
at sun.instrument.InstrumentationImpl.loadClassAndStartAgent(InstrumentationImpl.java:382)
at sun.instrument.InstrumentationImpl.loadClassAndCallPremain(InstrumentationImpl.java:397)
Caused by: compile error: ; is missing
at javassist.compiler.Parser.parseDeclarationOrExpression(Parser.java:594)
at javassist.compiler.Parser.parseStatement(Parser.java:277)
at javassist.compiler.Javac.compileStmnt(Javac.java:567)
at javassist.CtBehavior.insertAt(CtBehavior.java:1186)
... 15 more
(Is there any way to debug these kind of issues.) Some help please.....

Javassist's compiler doesn't support generics. Either remove or comment them out:
.append("java.util.Map arbitraryMap = new java.util.HashMap();")
or
.append("java.util.Map/*<String,String>*/ arbitraryMap = new java.util.HashMap/*<String,String>*/();")
The latter is useful as comment for yourself only, of course, it has no special meaning for Javassist.

Related

In Java - how do I get a full stack trace

Currently I get the following output from code run
Caused by: java.lang.NullPointerException
at com.gargoylesoftware.htmlunit.html.HtmlScript$2.execute(HtmlScript.java:227)
at com.gargoylesoftware.htmlunit.html.HtmlScript.onAllChildrenAddedToPage(HtmlScript.java:256)
at com.gargoylesoftware.htmlunit.html.parser.neko.HtmlUnitNekoDOMBuilder.endElement(HtmlUnitNekoDOMBuilder.java:560)
at org.apache.xerces.parsers.AbstractSAXParser.endElement(Unknown Source)
at com.gargoylesoftware.htmlunit.html.parser.neko.HtmlUnitNekoDOMBuilder.endElement(HtmlUnitNekoDOMBuilder.java:514)
at net.sourceforge.htmlunit.cyberneko.HTMLTagBalancer.callEndElement(HTMLTagBalancer.java:1192)
at net.sourceforge.htmlunit.cyberneko.HTMLTagBalancer.endElement(HTMLTagBalancer.java:1132)
at net.sourceforge.htmlunit.cyberneko.filters.DefaultFilter.endElement(DefaultFilter.java:219)
at net.sourceforge.htmlunit.cyberneko.filters.NamespaceBinder.endElement(NamespaceBinder.java:312)
at net.sourceforge.htmlunit.cyberneko.HTMLScanner$ContentScanner.scanEndElement(HTMLScanner.java:3189)
at net.sourceforge.htmlunit.cyberneko.HTMLScanner$ContentScanner.scan(HTMLScanner.java:2114)
at net.sourceforge.htmlunit.cyberneko.HTMLScanner.scanDocument(HTMLScanner.java:937)
at net.sourceforge.htmlunit.cyberneko.HTMLConfiguration.parse(HTMLConfiguration.java:443)
at net.sourceforge.htmlunit.cyberneko.HTMLConfiguration.parse(HTMLConfiguration.java:394)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at com.gargoylesoftware.htmlunit.html.parser.neko.HtmlUnitNekoDOMBuilder.parse(HtmlUnitNekoDOMBuilder.java:760)
at com.gargoylesoftware.htmlunit.html.parser.neko.HtmlUnitNekoHtmlParser.parseFragment(HtmlUnitNekoHtmlParser.java:158)
at com.gargoylesoftware.htmlunit.html.parser.neko.HtmlUnitNekoHtmlParser.parseFragment(HtmlUnitNekoHtmlParser.java:112)
at com.gargoylesoftware.htmlunit.javascript.host.Element.parseHtmlSnippet(Element.java:868)
at com.gargoylesoftware.htmlunit.javascript.host.Element.setInnerHTML(Element.java:920)
at com.gargoylesoftware.htmlunit.javascript.host.html.HTMLElement.setInnerHTML(HTMLElement.java:676)
at sun.reflect.GeneratedMethodAccessor17.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at net.sourceforge.htmlunit.corejs.javascript.MemberBox.invoke(MemberBox.java:188)
... 30 more
The above ... 30 more means that I do not know the line of my code that causes the problem. How can I get the full stack trace.
Also, if it does not seem to be running any of my catch statements with printStackTrace, but if I turn off logging with the below command
java.util.logging.Logger.getLogger("com.gargoylesoftware.htmlunit").setLevel(java.util.logging.Level.OFF);
java.util.logging.Logger.getLogger("org.apache.http").setLevel(java.util.logging.Level.OFF);
**Have put in my full code below as suggested by the comments below . Did not put in the actual URL though**
import com.gargoylesoftware.htmlunit.html.*;
import java.io.File;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
public class download_to_send_to_stackoverflow
{
public static void main(String args[])
{
String url = "did not want to include the actual web site ";
HtmlPage page = null;
WebClient webClient = new WebClient();
webClient.getOptions().setRedirectEnabled(true);
webClient.getOptions().setJavaScriptEnabled(true); // tried making false - but didnt work
webClient.getOptions().setCssEnabled(false);
webClient.getOptions().setUseInsecureSSL(true);
webClient.getOptions().setTimeout(30000);
webClient.setJavaScriptTimeout(30000); //e.g. 50s
webClient.waitForBackgroundJavaScript(15000) ; // added 2017/1/24
webClient.waitForBackgroundJavaScriptStartingBefore(30000) ; // added 2017/1/24
try
{
page = webClient.getPage( url );
savePage_just_html(page );
}
catch( Exception e )
{
System.out.println( "Exception thrown:----------------------------------------" + e.getMessage() );
e.printStackTrace();
}
}
protected static String savePage_just_html(HtmlPage page)
{
try
{
File saveFolder = new File("spool/_");
page.save(saveFolder); // this is the line causing the error with limit stack trace
}
catch ( Exception e )
{
System.out.println( "IOException was thrown: ---------------------------------- " + e.getMessage() );
e.printStackTrace();
}
return "file.html";
}
}
------------------------------------------------------
page.save(saveFolder); above is the problem line. if I take it out I dont get the limited statcktrace errors but I also dont save the html page - which I want to do
- The question is - why does this line only print a limited stacktrace
The "Caused by" means that this is a nested exception.
The "... 30 more" in a nested exception stacktrace means that those 30 lines are the same as in the primary exception.
So just look at the primary stacktrace to see those stack frames.
Apparently your exception stacktraces are being generated in a way that is suppressing (or removing) the primary exception stacktrace. This is puzzling, but it is probably being done by one of the unit testing libraries that you are using.
Getting to the bottom of this will probably involve you either debugging whatever it is that is generating the stacktrace, or writing a minimal reproducible example so that someone else can debug it.

How to create a Spark UDF in Java which accepts array of Strings?

This question has been asked here for Scala, and it does not help me as I am working with Java API. I have been literally throwing everything and the kitchen sink at it, so this was my approach:
List<String> sourceClasses = new ArrayList<String>();
//Add elements
List<String> targetClasses = new ArrayList<String>();
//Add elements
dataset = dataset.withColumn("Transformer", callUDF(
"Transformer",
lit((String[])sourceClasses.toArray())
.cast(DataTypes.createArrayType(DataTypes.StringType)),
lit((String[])targetClasses.toArray())
.cast(DataTypes.createArrayType(DataTypes.StringType))
));
And for my UDF declaration:
public class Transformer implements UDF2<Seq<String>, Seq<String>, String> {
// #SuppressWarnings("deprecation")
public String call(Seq<String> sourceClasses, Seq<String> targetClasses)
throws Exception {
When I run the code, the execution does not proceed past the UDF call, which is expected because I am not being able to match up the types. Please help me in this regard.
EDIT
I tried the solution suggested by #Oli. However, I got the following exception:
org.apache.spark.SparkException: Failed to execute user defined function($anonfun$261: (array<string>, array<string>) => string)
at org.apache.spark.sql.catalyst.expressions.GeneratedClass$GeneratedIteratorForCodegenStage1.project_doConsume_0$(Unknown Source)
at org.apache.spark.sql.catalyst.expressions.GeneratedClass$GeneratedIteratorForCodegenStage1.processNext(Unknown Source)
at org.apache.spark.sql.execution.BufferedRowIterator.hasNext(BufferedRowIterator.java:43)
at org.apache.spark.sql.execution.WholeStageCodegenExec$$anonfun$13$$anon$1.hasNext(WholeStageCodegenExec.scala:636)
at org.apache.spark.sql.execution.SparkPlan$$anonfun$2.apply(SparkPlan.scala:255)
at org.apache.spark.sql.execution.SparkPlan$$anonfun$2.apply(SparkPlan.scala:247)
at org.apache.spark.rdd.RDD$$anonfun$mapPartitionsInternal$1$$anonfun$apply$24.apply(RDD.scala:836)
at org.apache.spark.rdd.RDD$$anonfun$mapPartitionsInternal$1$$anonfun$apply$24.apply(RDD.scala:836)
at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
at org.apache.spark.rdd.MapPartitionsRDD.compute(MapPartitionsRDD.scala:52)
at org.apache.spark.rdd.RDD.computeOrReadCheckpoint(RDD.scala:324)
at org.apache.spark.rdd.RDD.iterator(RDD.scala:288)
at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:90)
at org.apache.spark.scheduler.Task.run(Task.scala:123)
at org.apache.spark.executor.Executor$TaskRunner$$anonfun$10.apply(Executor.scala:408)
at org.apache.spark.util.Utils$.tryWithSafeFinally(Utils.scala:1360)
at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:414)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassCastException: scala.collection.mutable.WrappedArray$ofRef cannot be cast to scala.collection.immutable.Seq
at com.esrx.dqm.uuid.UUIDTransformerEngine$1.call(UUIDTransformerEngine.java:1)
at org.apache.spark.sql.UDFRegistration$$anonfun$261.apply(UDFRegistration.scala:774)
... 22 more
This line specifically seems to be indicative of a problem:
Caused by: java.lang.ClassCastException: scala.collection.mutable.WrappedArray$ofRef cannot be cast to scala.collection.immutable.Seq
From what I understand from the type of your UDF, you are trying to create a UDF that takes two arrays as inputs and returns a string.
In java, that's a bit painful but manageable.
Let's say that you want to join both arrays and link them with the word AND. You could define the UDF as follows:
UDF2 my_udf2 = new UDF2<WrappedArray<String>, WrappedArray<String>, String>() {
public String call(WrappedArray<String> a1, WrappedArray a2) throws Exception {
ArrayList<String> l1 = new ArrayList(JavaConverters
.asJavaCollectionConverter(a1)
.asJavaCollection());
ArrayList<String> l2 = new ArrayList(JavaConverters
.asJavaCollectionConverter(a2)
.asJavaCollection());
return l1.stream().collect(Collectors.joining(",")) +
" AND " +
l2.stream().collect(Collectors.joining(","));
}
};
Note that you need to use scala WrappedArray in the signature in the method and transform them in the body of the method with JavaConverters to be able to manipulate them in Java. Here are the required import just in case.
import scala.collection.mutable.WrappedArray;
import scala.collection.JavaConverters;
Then you can register the UDF can use it with Spark. To be able to use it, I created a sample dataframe and two dummy arrays from the 'id' column. Note that it can also work with the lit function as you were trying to do in your question.
spark.udf().register("my_udf2", my_udf2, DataTypes.StringType);
String[] data = {"abcd", "efgh", "ijkl"};
spark.range(3)
.withColumn("id", col("id").cast("string"))
.withColumn("array", functions.array(col("id"), col("id")))
.withColumn("string_of_arrays",
functions.callUDF("my_udf2", col("array"), lit(data)))
.show(false);
which yields:
+---+------+----------------------+
|id |array |string_of_arrays |
+---+------+----------------------+
|0 |[0, 0]|0,0 AND abcd,efgh,ijkl|
|1 |[1, 1]|1,1 AND abcd,efgh,ijkl|
|2 |[2, 2]|2,2 AND abcd,efgh,ijkl|
+---+------+----------------------+
In Spark >= 2.3, you could also do it like this:
UserDefinedFunction my_udf2 = udf(
(WrappedArray<String> s1, WrappedArray<String> s2) -> "some_string",
DataTypes.StringType
);
df.select(my_udf2.apply(col("a1"), col("a2")).show(false);

Ignite Scan Query Throws class org.apache.ignite.binary.BinaryInvalidTypeException

Following Ignite Readme page https://apacheignite.readme.io/docs/cache-queries#section-scan-queries I am trying to run the discussed example code.
IgniteCache<Long, Person> cache = ignite.cache("mycache");
// Find only persons earning more than 1,000.
try (QueryCursor<Cache.Entry<Long, Person>> cursor =
cache.query(new ScanQuery<Long, Person>((k, p) -> p.getSalary() > 1000))) {
for (Cache.Entry<Long, Person> entry : cursor)
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
I am getting the following exception
Caused by: class org.apache.ignite.binary.BinaryInvalidTypeException: examples.model.Person
at org.apache.ignite.internal.binary.BinaryContext.descriptorForTypeId(BinaryContext.java:707)
at org.apache.ignite.internal.binary.BinaryReaderExImpl.deserialize0(BinaryReaderExImpl.java:1757)
at org.apache.ignite.internal.binary.BinaryReaderExImpl.deserialize(BinaryReaderExImpl.java:1716)
at org.apache.ignite.internal.binary.BinaryObjectImpl.deserializeValue(BinaryObjectImpl.java:798)
at org.apache.ignite.internal.binary.BinaryObjectImpl.value(BinaryObjectImpl.java:143)
at org.apache.ignite.internal.processors.cache.CacheObjectUtils.unwrapBinary(CacheObjectUtils.java:177)
at org.apache.ignite.internal.processors.cache.CacheObjectUtils.unwrapBinaryIfNeeded(CacheObjectUtils.java:39)
at org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager$ScanQueryIterator.advance(GridCacheQueryManager.java:3063)
at org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager$ScanQueryIterator.onHasNext(GridCacheQueryManager.java:2965)
at org.apache.ignite.internal.util.GridCloseableIteratorAdapter.hasNextX(GridCloseableIteratorAdapter.java:53)
at org.apache.ignite.internal.util.lang.GridIteratorAdapter.hasNext(GridIteratorAdapter.java:45)
at org.apache.ignite.internal.processors.cache.query.GridCacheQueryManager.runQuery(GridCacheQueryManager.java:1141)
at org.apache.ignite.internal.processors.cache.query.GridCacheDistributedQueryManager.processQueryRequest(GridCacheDistributedQueryManager.java:234)
at org.apache.ignite.internal.processors.cache.query.GridCacheDistributedQueryManager$2.apply(GridCacheDistributedQueryManager.java:109)
at org.apache.ignite.internal.processors.cache.query.GridCacheDistributedQueryManager$2.apply(GridCacheDistributedQueryManager.java:107)
at org.apache.ignite.internal.processors.cache.GridCacheIoManager.processMessage(GridCacheIoManager.java:1056)
at org.apache.ignite.internal.processors.cache.GridCacheIoManager.onMessage0(GridCacheIoManager.java:581)
at org.apache.ignite.internal.processors.cache.GridCacheIoManager.handleMessage(GridCacheIoManager.java:380)
at org.apache.ignite.internal.processors.cache.GridCacheIoManager.handleMessage(GridCacheIoManager.java:306)
at org.apache.ignite.internal.processors.cache.GridCacheIoManager.access$100(GridCacheIoManager.java:101)
at org.apache.ignite.internal.processors.cache.GridCacheIoManager$1.onMessage(GridCacheIoManager.java:295)
at org.apache.ignite.internal.managers.communication.GridIoManager.invokeListener(GridIoManager.java:1569)
at org.apache.ignite.internal.managers.communication.GridIoManager.processRegularMessage0(GridIoManager.java:1197)
at org.apache.ignite.internal.managers.communication.GridIoManager.access$4200(GridIoManager.java:127)
at org.apache.ignite.internal.managers.communication.GridIoManager$9.run(GridIoManager.java:1093)
... 3 more
Caused by: java.lang.ClassNotFoundException: examples.model.Person
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at org.apache.ignite.internal.util.IgniteUtils.forName(IgniteUtils.java:8771)
at org.apache.ignite.internal.MarshallerContextImpl.getClass(MarshallerContextImpl.java:349)
at org.apache.ignite.internal.binary.BinaryContext.descriptorForTypeId(BinaryContext.java:698)
The Person object is taken from the Ingnite example (as well as most of the code, available https://gist.github.com/alexterman/075d7e12f470ce873f99d59478260250 on github ). I am running it on Mac.
This means you do not have Person class in classpath of your server node(s).
Ignite will not peer class load its Key-Value classes so you need to distribute them to all nodes before running any distributed operations which use those types.
Alternatively you can use withKeepBinary(), work on BinaryObject's. Something along the lines of
cache.withKeepBinary().query(new ScanQuery<Long, BinaryObject>(
(k, p) -> p.<Integer>getField("salary") > 1000))

GWT RPC: using methods of other Service Implementation fails

I get an error while calling one of my GWT services.
Eclipse console puts out this:
SCHWERWIEGEND: javax.servlet.ServletContext log: Exception while dispatching incoming RPC call
com.google.gwt.user.server.rpc.UnexpectedException: Service method 'public abstract de.hdm.gruppe09.clickandlove.shared.report.AllInfosOfProfileReport de.hdm.gruppe09.clickandlove.shared.ReportGenerator.createAllInfosOfProfileReport(de.hdm.gruppe09.clickandlove.shared.bo.Profil) throws java.lang.IllegalArgumentException' threw an unexpected exception: java.lang.NullPointerException
.......
Caused by: java.lang.NullPointerException
at de.hdm.gruppe09.clickandlove.server.report.ReportGeneratorImpl.createAllInfosOfProfileReport(ReportGeneratorImpl.java:107)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.google.appengine.tools.development.agent.runtime.Runtime.invoke(Runtime.java:130)
at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:561)
... 40 more
ReportGeneratorImpl.java:107 looks like this (107 is the first of the two Sysos):
103 //Abrufen des eingeloggten Profils. Wird benoetigt für die anschließende Berechnung des Aehnlichkeitsmaßes
104 Profil ep = this.verwaltung.getEingeloggtesProfil();
//Ausgaben über das ep. Nur zu Textzwecken
107 System.out.println("RGImpl: eingeloggtesProfilID:" + ep.getId());
System.out.println("RGImpl: eingeloggtesProfilMail:" + ep.getEmail());
//Abrufen des Aehnlichkeitsma�es
int score = this.verwaltung.berechneAhnlichkeit(p, ep);
System.out.println("RGImpl: Score:" + score);
//Score Int Wert in String umwandeln, da new Column nur String Werte annimmt
String scorestring = Integer.toString(score);
//Setzen des Aehnlichkeitsma�es
Row TopRow = new Row();
TopRow.addColumn(new Column(fullname));
TopRow.addColumn(new Column(scorestring));
Obviously the Object ep must be null. Probably because line 104 fails.
My method fails whenever I use methods of "this.verwaltung".
Here is how I create my object of verwaltung:
private Verwaltung verwaltung = null;
public void init() throws IllegalArgumentException {
VerwaltungImpl a = new VerwaltungImpl();
a.init();
this.verwaltung = a;
}
Since both the "ReportGeneratorImpl" and the VerwatlungImpl" are running on the server I understand that i need no Callbacks to use methods from one another. Is that right?
Obviously the Object ep musst [sic] be null.
Have you considered starting the embedded Jetty server that GWT uses with the debugger and setting a breakpoint on line 104, so that you can step through the code and see what the cause of the NullPointerException is?
See Testing Services During Development here for more details: http://www.gwtproject.org/doc/latest/DevGuideServerCommunication.html

Java jList NullPointerException error

Error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at test.factory.MainWindow.setFuncList(MainWindow.java:160)
at test.factory.MainWindow.<init>(MainWindow.java:22)
at test.factory.MainWindow$2.run(MainWindow.java:151)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:721)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:682)
at java.awt.EventQueue$3.run(EventQueue.java:680)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:691)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:244)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:163)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:147)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:97)
Code:
TestFactory tf = new TestFactory();
ArrayList<Function> fList = tf.getFunctions();
DefaultListModel<Function> dFuncList = new DefaultListModel();
fListPane.setModel(dFuncList);
for(Function f : fList) {
dFuncList.addElement(f);
}
Question:
Now, if you find the error that's great, but my question is. How do I parse the error text to find where my error originated? I'm used to things like missing ';' at line 24 of C:\filename
Update: fList has two elements, so not null.
The error dump is a stack trace, so I tend to find it's always best to start at the top and work down. In this case it looks like your setFuncList at line 160 of MainWindow.java is trying to work with an object that is null (maybe not yet initialised?).
UPDATE: Example of code that works
class Function {
int i;
public Function(int myI) {
this.i = myI;
}
#Override
public String toString() {
return "i=" + this.i;
}
}
Used with:
ArrayList<Function> fList = new ArrayList<>();
fList.add(new Function(1));
fList.add(new Function(2));
DefaultListModel<Function> dFuncList = new DefaultListModel();
jList2.setModel(dFuncList);
for(Function f : fList) {
dFuncList.addElement(f);
}
So basically look through the stack trace from the top, it will list the calls that have occurred which led to the error you received. Look carefully at the lines in your code that are listed. If you can't see any obvious errors you can add some extra tests based on the error. Ie check some objects are not null before the line which caused the error, I find printouts a simple approach. You can also use a debugger, I use jswat but only break it out when I really need to.
Hope that was what you were after
#orangegoat gave a good breakdown of how to interpret the stack trace if that's what you wanted
Also a link to jswat
http://code.google.com/p/jswat/

Categories

Resources