stackoverflow exception while using String match in java - java

For a little university project i'm doing, i need to extract code samples from html given as a string.
To by more precise, i need to get from that html string, everything in between <code> and </code>.
I'm writing in Java, and using String.match to do that.
My code:
public static ArrayList<String> extractByHTMLtagDelimiters(String source, String startDelimiter, String endDelimiter){
ArrayList<String> results = new ArrayList<String>();
if (source.matches("([\t\n\r]|.)*" + startDelimiter + "([\t\n\r]|.)*" + endDelimiter)){
//source has some code samples in it
//get array entries of the form: {Some code}</startDelimiter>{something else}
String[] splittedSource = source.split(startDelimiter);
for (String sourceMatch : splittedSource){
if (sourceMatch.matches("([\t\n\r]|.)*" + endDelimiter + "([\t\n\r]|.)*")){
//current string has code sample in it (with some body leftovers)
//the code sample located before the endDelimiter - extract it
String codeSample = (sourceMatch.split(endDelimiter))[0];
//add the code samples to results
results.add(codeSample);
}
}
}
return results;
iv'e tried to extract that samples from some html of ~1300 chars and got pretty massive exception: (it goes on and on for few dozens of lines)
Exception in thread "main" java.lang.StackOverflowError
at java.util.regex.Pattern$Branch.match(Unknown Source)
at java.util.regex.Pattern$GroupHead.match(Unknown Source)
at java.util.regex.Pattern$Loop.match(Unknown Source)
at java.util.regex.Pattern$GroupTail.match(Unknown Source)
at java.util.regex.Pattern$BranchConn.match(Unknown Source)
at java.util.regex.Pattern$CharProperty.match(Unknown Source)
at java.util.regex.Pattern$Branch.match(Unknown Source)
at java.util.regex.Pattern$GroupHead.match(Unknown Source)
at java.util.regex.Pattern$Loop.match(Unknown Source)
at java.util.regex.Pattern$GroupTail.match(Unknown Source)
at java.util.regex.Pattern$BranchConn.match(Unknown Source)
at java.util.regex.Pattern$CharProperty.match(Unknown Source)
at java.util.regex.Pattern$Branch.match(Unknown Source)
at java.util.regex.Pattern$GroupHead.match(Unknown Source)
at java.util.regex.Pattern$Loop.match(Unknown Source)
at java.util.regex.Pattern$GroupTail.match(Unknown Source)
at java.util.regex.Pattern$BranchConn.match(Unknown Source)
at java.util.regex.Pattern$CharProperty.match(Unknown Source)
at java.util.regex.Pattern$Branch.match(Unknown Source)
at java.util.regex.Pattern$GroupHead.match(Unknown Source)
at java.util.regex.Pattern$Loop.match(Unknown Source)
i've found the following bug report:
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5050507
is there anything i can do to still use string.match? if not, can you please recommend some other way to do it without implementing html parsing by myself?
Thank a lot,
Dub.

You can just manually go through the input string using String's indexOf() method to find the start and end deliminters and extract out the bits between yourself.
public static void main(String[] args) {
String source = "<html>blah<code>this is awesome</code>more junk</html>";
String startDelim = "<code>";
String endDelim = "</code>";
int start = source.indexOf(startDelim);
int end = source.indexOf(endDelim);
String code = source.substring(start + startDelim.length(), end);
System.out.println(code);
}
If you need to find more than one, then just use indexOf again starting at the point you finished:
int nextStart = source.indexOf(startDelim, end + endDelim.length())

Simply replace your regex pattern with "(?s).*"
This matches anything including new lines as you intended.

Related

convert a binary String containing 64bits to hexadecimal in java?

I'm trying to convert this binary String that contains 64bits to Hexadecimal with this code:
String mm = "1000010111101000000100110101010000001111000010101011010000000101";
String v = new BigInteger(mm, 2).toString(16);
v=String.format("%64x", v);
but it gives me this exception:
Exception in thread "main" java.util.IllegalFormatConversionException: x != java.lang.String
at java.util.Formatter$FormatSpecifier.failConversion(Unknown Source)
at java.util.Formatter$FormatSpecifier.printInteger(Unknown Source)
at java.util.Formatter$FormatSpecifier.print(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.util.Formatter.format(Unknown Source)
at java.lang.String.format(Unknown Source)
at test.main(test.java:332)
what is getting wrong and why?
change this:
v=String.format("%64x", v);
to this:
v=String.format("%s", v);
Also you need this:
String v = new BigInteger(mm, 2).toString(16);

Error serializing element in ehcache

I get the following error, when puting an element in the ehcache. Does anyone have any idea why this error occures?
Thank you in advance.
This is put method:
#SuppressWarnings("unchecked")
#Override
public void putActivity(Activity activity) {
// put activity itself
Serializable activityKey = KEY_PREFIX_ACTIVITY + activity.getId();
final Element activityElement = new Element(activityKey, activity);
getCache().put(activityElement);
// add activity to the list of user
ArrayList<Activity> activities = null;
Serializable userKey = KEY_PREFIX_USER_ACTIVITIES + activity.getExecutingUserId();
Element userActivities = getCache().get(userKey);
if (userActivities == null) {
activities = new ArrayList<Activity>();
userActivities = new Element(userKey, activities);
} else {
activities = (ArrayList<Activity>) userActivities.getObjectValue();
}
activities.add(activity);
getCache().put(userActivities);
}
and here is the corresponding erorr:
Mrz 05, 2016 11:07:40 AM net.sf.ehcache.store.disk.DiskStorageFactory$DiskWriteTask call
Schwerwiegend: Disk Write of u-1 failed:
net.sf.ehcache.CacheException: Failed to serialize element due to ConcurrentModificationException. This is frequently the result of inappropriately sharing thread unsafe object (eg. ArrayList, HashMap, etc) between threads
at net.sf.ehcache.store.disk.DiskStorageFactory.serializeElement(DiskStorageFactory.java:405)
at net.sf.ehcache.store.disk.DiskStorageFactory.write(DiskStorageFactory.java:385)
at net.sf.ehcache.store.disk.DiskStorageFactory$DiskWriteTask.call(DiskStorageFactory.java:477)
at net.sf.ehcache.store.disk.DiskStorageFactory$PersistentDiskWriteTask.call(DiskStorageFactory.java:1071)
at net.sf.ehcache.store.disk.DiskStorageFactory$PersistentDiskWriteTask.call(DiskStorageFactory.java:1055)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.util.ConcurrentModificationException
at java.util.ArrayList.writeObject(Unknown Source)
at sun.reflect.GeneratedMethodAccessor33.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
at java.io.ObjectOutputStream.defaultWriteObject(Unknown Source)
at net.sf.ehcache.Element.writeObject(Element.java:875)
at sun.reflect.GeneratedMethodAccessor31.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at net.sf.ehcache.util.MemoryEfficientByteArrayOutputStream.serialize(MemoryEfficientByteArrayOutputStream.java:97)
at net.sf.ehcache.store.disk.DiskStorageFactory.serializeElement(DiskStorageFactory.java:403)
... 10 more
and here more details from ehcache source code:
private MemoryEfficientByteArrayOutputStream [More ...] serializeElement(Element element) throws IOException {
// A ConcurrentModificationException can occur because Java's serialization
// mechanism is not threadsafe and POJOs are seldom implemented in a threadsafe way.
// e.g. we are serializing an ArrayList field while another thread somewhere in the application is appending to it.
try {
return MemoryEfficientByteArrayOutputStream.serialize(element);
} catch (ConcurrentModificationException e) {
throw new CacheException("Failed to serialize element due to ConcurrentModificationException. " +
"This is frequently the result of inappropriately sharing thread unsafe object " +
"(eg. ArrayList, HashMap, etc) between threads", e);
}
}
You are updating an object while it's been serialized (ehcache try to save it to disk). You should store in a cache only an immutable object.
In your case, don't try to reuse the ArrayList, create a new one:
if (userActivities == null) {
activities = new ArrayList<Activity>();
userActivities = new Element(userKey, activities);
} else {
activities = new ArrayList<Activity>((List) userActivities.getObjectValue());
}
Instead of an ArrayList, you can instanciate a CopyOnWriteArrayList.

Class.forName() throws ClassNotFoundException

So this is my first time posting, please be gentle :3
General overview:
My goal is to be able to give my program a XSD file, then the program generates a bean, generates a nice GUI using reflection on the bean, then I can enter appropriate values into the textfields and then the program updates the bean with the values and finally marshalls the bean into a nice XML.
It's coming along pretty good, but yesterday I stumbled over an error that I can't figure out..
StackTrace
java.lang.ClassNotFoundException: X.Y.Z.BEAN_FILE_WITHOUT_.JAVA
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at X.Y.Z.GenerateXMLService.generateBean(GenerateXMLService.java:101)
at X.Y.Z.view.Gui$1.handle(Gui.java:56)
at X.Y.Z.view.Gui$1.handle(Gui.java:1)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at javafx.scene.Node.fireEvent(Unknown Source)
at javafx.scene.control.Button.fire(Unknown Source)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(Unknown Source)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(Unknown Source)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at javafx.scene.Scene$MouseHandler.process(Unknown Source)
at javafx.scene.Scene$MouseHandler.access$1800(Unknown Source)
at javafx.scene.Scene.impl_processMouseEvent(Unknown Source)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.notifyMouse(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$300(Unknown Source)
at com.sun.glass.ui.win.WinApplication$4$1.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
generateBean
public Class generateBean(File xsd) {
String finalDir = System.getProperty("user.dir") + "/src/main/java";
String xsdDir = xsd.getParentFile().getAbsolutePath();
try {
Process p = Runtime.getRuntime().exec(
"cmd /c cd " + xsdDir + " && xjc -d " + finalDir
+ " -p PACKAGE_PATH_GOES_HERE " + xsd.getName().toString());
p.waitFor();
} catch (IOException | InterruptedException e) {
Gui.errorPopUp(e);
}
/**
* Get the newly created files and put them in an array
*/
File[] fList = new File[2];
fList = new File("DIRECTORY_PATH_GOES_HERE").listFiles();
/**
* Get the file that isn't Objectfactory.java ---> that's the bean
*/
for (File file : fList) {
if (!"ObjectFactory.java".equals(file.getName())) {
String beanName = file.getName();
String beanBinaryName = "PACKAGE_PATH_GOES_HERE"
+ beanName.substring(0, beanName.length() - 5);
Class beanClass = null;
try {
beanClass = Class.forName(beanBinaryName); //this is line 101
return beanClass;
} catch (ClassNotFoundException e) {
Gui.errorPopUp(e);
}
}
}
return null;
}
So I checked first if the beanBinaryName is correct, and I think it is. It has the following format:
com.foo.foo.some.more.foo.beanbag.bean
Then I started googling with the error message and stumbled accross this post:
Link to the blog
But to be honest I didn't really understand what he was trying to explain. The stacktrace looks similar, but I just started with java a few months ago and still consider myself a newbie. Do you have any advice what the error might be? Thank in advance!
EDIT / SOLUTION:
My first mistake was trying to use class.forName() on a .java file. This only works with compiled files, e.g. .class.
After I fixed that i was still getting error messages, but after playing around with the URLClassLoader it worked :D I renamed and refactored this method compared to the method at the top, so in this one we really only get the class, while in my first example I also generate the .java files. I now do this in a seperate method to keep things organized.
public Class getClassFromBean() {
File[] fList = new File[3];
fList = new File("foo/beanbag").listFiles();
Class beanClass = null;
for (File file : fList) {
String lastSix = file.getName().toString().substring(file.getName().length() - 6);
if (".class".equals(lastSix)) {
String beanBinaryName = "foo.beanbag."
+ file.getName().toString().substring(0, file.getName().toString().length() - 6);
try {
File root = new File(System.getProperty("user.dir") + "/src/main/java");
URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { root.toURI()
.toURL() });
beanClass = Class.forName(beanBinaryName, true, classLoader);
} catch (ClassNotFoundException | MalformedURLException e) {
Gui.errorPopUp(e);
}
return beanClass;
}
}
return beanClass;
}
Method Class.forName() works only for compiled classes i.e. for files with extension '.class'. You cannot just put '.java' file to your classpath.

java error while parsing xml file from url [duplicate]

This question already has an answer here:
Unable to extract xml data from website using JAVA
(1 answer)
Closed 8 years ago.
I am trying to parse an XML file in java but i am facing a problem. The code is showing an error in the parsing process as if it is getting a JSON File. How can i solve this issue ?
URL url2 = new URL("https://api.eancdn.com/ean-services/rs/hotel/v3/list?cid=55505&minorRev=99&apiKey=cbrzfta369qwyrm9t5b8y8kf&locale=en_US&currencyCode=USD&longitude=0.1275&latitude=51.5072&xml=%3CHotelListRequest%3E%0A%20%20%20%20%3Ccity%3ESeattle%3C%2Fcity%3E%0A%20%20%20%20%3CstateProvinceCode%3EWA%3C%2FstateProvinceCode%3E%0A%20%20%20%20%3CcountryCode%3EUS%3C%2FcountryCode%3E%0A%20%20%20%20%3CarrivalDate%3E11%2F25%2F2014%3C%2FarrivalDate%3E%0A%20%20%20%20%3CdepartureDate%3E11%2F27%2F2014%3C%2FdepartureDate%3E%0A%20%20%20%20%3CRoomGroup%3E%0A%20%20%20%20%20%20%20%20%3CRoom%3E%0A%20%20%20%20%20%20%20%20%20%20%20%20%3CnumberOfAdults%3E2%3C%2FnumberOfAdults%3E%0A%20%20%20%20%20%20%20%20%3C%2FRoom%3E%0A%20%20%20%20%3C%2FRoomGroup%3E%0A%20%20%20%20%3CnumberOfResults%3E25%3C%2FnumberOfResults%3E%0A%3C%2FHotelListRequest%3E");
InputStream is2 = url2.openStream();
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(is2);
StringBuilder sb = new StringBuilder();
Element root = doc.getRootElement();
List<Element> HotelList =
root.getChildren("HotelList");
Element Hotel = HotelList.get(0);
List<Element> SummaryList =
Hotel.getChildren("HotelSummary");
Element Summary = SummaryList.get(0);
Element Sum;
for(int f=0; f< SummaryList.size(); f++){
Sum = SummaryList.get(f);
sb.append("Hotel ID: " + Sum.getChildText("hotelId") +"\n" + "Name: " + Sum.getChildText("name") + "\n");
sb.append("HotelRating: " + Sum.getChildText("hotelRating")+ "\n");
}System.out.println(sb);
The Error:
org.jdom2.input.JDOMParseException: Error on line 1: Content is not allowed in prolog.
at org.jdom2.input.sax.SAXBuilderEngine.build(SAXBuilderEngine.java:232)
at org.jdom2.input.sax.SAXBuilderEngine.build(SAXBuilderEngine.java:253)
at org.jdom2.input.SAXBuilder.build(SAXBuilder.java:1091)
at HotelInfo.main(HotelInfo.java:22)
Caused by: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLScanner.reportFatalError(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
at org.jdom2.input.sax.SAXBuilderEngine.build(SAXBuilderEngine.java:217)
... 3 more
Take a look at the returned data using curl. It is JSON, not XML, therefore you cannot parse it this way. Use a JSON parser instead, or figure out the API parameter needed to make the service return XML.

NullPointerException I cannot resolve

This is the method called when the player has to be removed from the game. Both these methods are in different classes.
GameboardGUI class
Vector<Player> players = new Vector<Player>();
public void removePlayerFromGame(Player playerToRemove)
{
//go through the playerToRemove's properties and reset all their variables
for(int i = 0; i < playerToRemove.getPropertiesOwned().size(); i++)
{
//code to reset the player's properties to an unowned/unmodified state
}
//same with transports
for(int i = 0; i < playerToRemove.getTransportsOwned().size(); i++)
{
//code to reset the player's transports to an unowned/unmodified state
}
//just updating the vector based on the playerToRemove's position
if(players.get(0) == playerToRemove)
{
players.remove(playerToRemove);
updatePlayerInformation();
}
else
{
players.remove(playerToRemove);
updatePlayerVector(players);
updatePlayerInformation();
}
}
This is how the method is called:
If the current player (fromMe) lands on a property and cant afford to pay the rent (i.e. their balance reaches 0 as a result of takefrombalance(1200);, currently hardcoded to 1200 to make testing easier) they are removed in the if statement if(fromMe.isBankrupt())
Property Class
GameboardGUI gui = new GameboardGUI();
public void payRent(Player fromMe, Player toYou, int rent)
{
//remove rent from the current player
fromMe.takeFromBalance(1200);
//add it to the owner
toYou.addToBalance(rent);
GameboardGUI.addGameFeedMessage(fromMe.getName() + " has paid " + rent + " in rent to " + toYou.getName());
GameboardGUI.addGameFeedMessage(toYou.getName() + "'s balance is now " + toYou.getBalance());
if(fromMe.isBankrupt())
{
//THIS IS THE CALL THAT THROWS THE NullPointerException
gui.removePlayerFromGame(fromMe);
}
else
{
GameboardGUI.addGameFeedMessage(fromMe.getName() + "'s balance is now " + fromMe.getBalance());
}
}
Here is the stack trace when the line is reached:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at PropertyTile.payRent(PropertyTile.java:254)
at PropertyTile.landedOnProperty(PropertyTile.java:239)
at GameboardGUI.playerHasLanded(GameboardGUI.java:1905)
at Player.setPosition(Player.java:82)
at Player.movePlayer(Player.java:101)
at GameboardGUI$11.actionPerformed(GameboardGUI.java:1536)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
It's really hard to help you without a stacktrace and the line numbers for your code, but we're trying.
If that's really the line (and not actually within removePlayerFromGame), the member gui hasn't been initialized.
Of course, if it's not that line, it could simply be that playerToRemove is null, and the NullPointerException is actually happening a couple of lines above.
Or, another possibility is that it's happening within removePlayerFromGame, in which case the most likely case is that playerToRemove hasn't been properly set up - that its getPropertiesOwned() or getTransportsOwned() methods are returning null.
I would add the following two lines, as a first step to see what happens:
if(fromMe==null)
System.out.println("from me is null");
if(gui == null)
System.out.println("gui is null");
gui.removePlayerFromGame(fromMe);
One of the two object references is null causing the exception.
Otherwise, the method removePlayerFromGame is doing something, but I don't think that would be the case because the stacktrace would include additional methods.
You say in the code that the Exception is thrown when you reach the line
gui.removePlayerFromGame(fromMe);
However, the top of stacktrace you are showing is Player.movePlayer(), with its bottom at PropertyTile.payRent().
Is this payRent() receiving any parameter? Can you post it source?

Categories

Resources