Java: Cleanly Redirect Exception to String - java

In Java, sometimes I get an exception parsing user input. Instead of printing a stack trace, I want it to "cleanly" redirect the output to a string. Example (uses LuaJ):
Exception:
Exception in thread "Thread-3" org.luaj.vm2.LuaError: [string "jhkfchyufjhdnxvk,gh'bnmcvk,fvjmfk,xdcfsdkckucfdxfds,ie(); "]:1: unfinished string
at org.luaj.vm2.compiler.LexState.lexerror(Unknown Source)
at org.luaj.vm2.compiler.LexState.read_string(Unknown Source)
at org.luaj.vm2.compiler.LexState.llex(Unknown Source)
at org.luaj.vm2.compiler.LexState.next(Unknown Source)
at org.luaj.vm2.compiler.LexState.str_checkname(Unknown Source)
at org.luaj.vm2.compiler.LexState.singlevar(Unknown Source)
at org.luaj.vm2.compiler.LexState.primaryexp(Unknown Source)
at org.luaj.vm2.compiler.LexState.suffixedexp(Unknown Source)
at org.luaj.vm2.compiler.LexState.assignment(Unknown Source)
at org.luaj.vm2.compiler.LexState.exprstat(Unknown Source)
at org.luaj.vm2.compiler.LexState.statement(Unknown Source)
at org.luaj.vm2.compiler.LexState.statlist(Unknown Source)
at org.luaj.vm2.compiler.LexState.mainfunc(Unknown Source)
at org.luaj.vm2.compiler.LuaC.luaY_parser(Unknown Source)
at org.luaj.vm2.compiler.LuaC.compile(Unknown Source)
at org.luaj.vm2.Globals.compilePrototype(Unknown Source)
at org.luaj.vm2.Globals.loadPrototype(Unknown Source)
at org.luaj.vm2.Globals.load(Unknown Source)
at org.luaj.vm2.Globals.load(Unknown Source)
at org.luaj.vm2.Globals.load(Unknown Source)
at net.snugglesstuff.LeoBot.LuaThread.run(LuaThread.java:25)
What the output should be:
[string "jhkfchyufjhdnxvk,gh'bnmcvk,fvjmfk,xdcfsdkckucfdxfds,ie(); "]:1: unfinished string

You can catch the exception and print exception.getMessage().
try {
... parsing code ...
}
catch (Exception exc) { // change this to catch the specific type of exceptions relevant to the parsing
System.out.println(exc.getMessage()); // or redirect the message to a file
}

Related

errors when replace phantomjs to headless chromedriver

i got many errors about js... so i changed to chromedriver headless, and it work better for screenshot a specific element, but i got an errors in a other screenshot(s) code
Starting ChromeDriver 2.45.615291 (ec3682e3c9061c10f26ea9e5cdcf3c53f3f74387)
on port 44903
Only local connections are allowed.
janv. 31, 2019 7:02:22 AM org.openqa.selenium.remote.ProtocolHandshake createSession
INFOS: Detected dialect: OSS
Exception in thread "AWT-EventQueue-0" java.awt.image.RasterFormatException: (y + height) is outside of Raster
at sun.awt.image.ByteInterleavedRaster.createWritableChild(Unknown Source)
at java.awt.image.BufferedImage.getSubimage(Unknown Source)
at CarteEtdInfo.photoProfile(CarteEtdInfo.java:57)
at Accueil.<init>(Accueil.java:99)
at Login$2.actionPerformed(Login.java:287)
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.AbstractButton.doClick(Unknown Source)
at javax.swing.plaf.basic.BasicRootPaneUI$Actions.actionPerformed(Unknown Source)
at javax.swing.SwingUtilities.notifyAction(Unknown Source)
at javax.swing.JComponent.processKeyBinding(Unknown Source)
at javax.swing.KeyboardManager.fireBinding(Unknown Source)
at javax.swing.KeyboardManager.fireKeyboardAction(Unknown Source)
at javax.swing.JComponent.processKeyBindingsForAllComponents(Unknown Source)
at javax.swing.JComponent.processKeyBindings(Unknown Source)
at javax.swing.JComponent.processKeyEvent(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.KeyboardFocusManager.redispatchEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(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$500(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$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.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$JavaSecurityAccessImpl.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)
this is the the code that have errors from class CarteEtdInfo
public void photoProfile() throws IOException {
String cookie = String.join("\n",Files.readAllLines(Paths.get("temp\\cookie.txt")));
Login webpage = new Login();
WebDriver pagee = webpage.driver;
pagee.get("https://www4.inscription.tn/ORegMx/servlet/AuthentificationEtud?Idsession="+cookie+"&action1=toCarteEtd");
// Get entire page screenshot
WebElement taswira = driver.findElement(By.xpath("/html[1]/body[1]/table[1]/tbody[1]/tr[1]/td[1]/table[1]/tbody[1]/tr[1]/td[1]/table[2]/tbody[1]/tr[4]/td[1]/div[2]/div[1]/table[2]/tbody[1]/tr[2]/td[1]/img[1]"));
File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
BufferedImage fullImg = null;
try {
fullImg = ImageIO.read(screenshot);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Get the location of element on the page
org.openqa.selenium.Point point = taswira.getLocation();
// Get width and height of the element
int eleWidth = taswira.getSize().getWidth();
int eleHeight = taswira.getSize().getHeight();
// Crop the entire page screenshot to get only element screenshot
BufferedImage eleScreenshot = fullImg.getSubimage(point.getX(), point.getY(), eleWidth, eleHeight); // line 57
try {
ImageIO.write(eleScreenshot, "png", screenshot);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Copy the element screenshot to disk
File screenshotLocation = new File("temp\\avatar.png");
try {
FileUtils.copyFile(screenshot, screenshotLocation);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
this is the line 57
BufferedImage eleScreenshot = fullImg.getSubimage(point.getX(), point.getY(), eleWidth, eleHeight);
the preivious code of screenshot an element in Login class works fine, so why this one have a problem ?
also the chromedriver not headless works fine but the headless not
Headless chrome default window size might be smaller than expected and this might cause your element to be outside of the window, hence not visible. You can either set the widndow size yourself or maximize window by using:
chromeOptions.addArguments(""--start-maximized")
i fixed the problem by adding
chromeOptions.addArguments("window-size=1980,960");

Unhandled Exception Type Java

I am using Sikuli with Java to create a small automation tool. I am having trouble with this Unhandled Exception error. I am trying to pass a method I created to the GUI actionPerformed method.
package mission;
import org.sikuli.script.FindFailed;
import org.sikuli.script.Pattern;
import org.sikuli.script.Screen;
import tools.ChooseMission;
public class Story {
public static void runStoryMissions(int chapter, int stage) throws FindFailed, InterruptedException {
Screen screen = new Screen();
ChooseMission.ChooseChapter(screen,chapter);
ChooseMission.ChooseStage(screen, stage);
int dailyBiometricCount = ChooseMission.dailyBiometricCount(screen);
Pattern start = new Pattern("img/chapters/start.png");
Pattern replay = new Pattern("img/chapters/replay.png");
Pattern next = new Pattern("img/chapters/next.png");
Pattern mission_finish_bar = new Pattern("img/chapters/mission_finish_bar.png");
screen.click(start);
System.out.println("The mission has started.");
Thread.sleep(2000);
while (find(screen, mission_finish_bar) == false) {
System.out.println("Still playing the mission...");
}
if (screen.exists(mission_finish_bar) != null){
System.out.println("The mission has finished.");
}
System.out.println("Wait for 5 Seconds");
Thread.sleep(5000);
System.out.println("Click repeat button");
screen.click(replay);
}
Here is the code for my actionPerformed listener button:
btnStartMissions.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int chapter = Integer.parseInt(txtFldChapter.getText());
int stage = Integer.parseInt(txtFldStage.getText());
System.out.println("Chapter #: " + chapter);
System.out.println("Stage #: " + stage);
try {
Story.runStoryMissions(chapter, stage);
} catch (FindFailed e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
There is a error at Story. runStoryMissions(chapter,stage) it says: Unhandled Exception type FindFailed and InterruptedException
Stack Trace:
Exception in thread "AWT-EventQueue-0" java.lang.ExceptionInInitializerError
at mission.Story.runStoryMissions(Story.java:12)
at GuiFrame1$2.actionPerformed(GuiFrame1.java:94)
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$500(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$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.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$JavaSecurityAccessImpl.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)
Caused by: java.lang.IllegalThreadStateException: Cannot call method from the event dispatcher thread
at java.awt.Robot.checkNotDispatchThread(Unknown Source)
at java.awt.Robot.waitForIdle(Unknown Source)
at org.sikuli.script.Mouse.move(Mouse.java:345)
at org.sikuli.script.Mouse.move(Mouse.java:318)
at org.sikuli.script.Mouse.init(Mouse.java:59)
at org.sikuli.script.Screen.initScreens(Screen.java:89)
at org.sikuli.script.Screen.<clinit>(Screen.java:58)
... 38 more
Okay, I found the answer to my problem if anyone is interested.
Sikuli uses the java.awt features so scripts cannot implement and use Swing elements.
Java AWT Robot actions cannot be called froma Java swing container.
Solution is to create a new Thread:
new Thread(() -> {
try {
Story.runStoryMissions(chapter, stage);
} catch (FindFailed | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}).start();

JavaFX Reading from file throws "InvocationTargetException"?

I've been trying to understand what the issue is exactly, but whatever I do doesn't seem to work.
I have a text file that lists names along with numbers, seperated by a colon.
An example of this is:
Betty Ross:52
Angie Scotts:29
Michael Rosen:72
The list is very long and comprises over 10,000 lines.
public class PeopleIds {
public static int UNDEFINED_ID = -1;
private static HashMap<String, Integer> people;
public static void initialize() {
people = new HashMap<String, Integer>();
System.out.println(new File("res/ids/people_ids.txt").exists());
try {
Files.lines(Paths.get("res/ids/people_ids.txt")).forEach(s -> {
people.put(s.replaceAll(":.*", "").trim(), Integer.parseInt(s.replaceAll(".*:", "")));
});
} catch (IOException e) {
System.out.println("Unable to read specified file.");
e.printStackTrace();
}
}
public static int getId(final String name) {
final Integer id = people.get(name);
return id != null ? id : UNDEFINED_ID;
}
}
I call the initialize method from a GUIController class:
public class GUIController implements Initializable {
#FXML
private TableView<PersonData> personTable;
#FXML
private TableColumn<PersonData, String> name;
#FXML
private TableColumn<PersonData, Integer> limit;
#FXML
private TextField searchInput;
#FXML
private ImageView personIcon;
private Image undefinedIcon;
private PersonIcon icon;
private ObservableList<PersonData> data;
#Override
public void initialize(URL location, ResourceBundle resources) {
PeopleIds.initialize();
undefinedIcon = new Image(getClass().getResourceAsStream("/ids/no.png"));
name.setCellValueFactory(new PropertyValueFactory<PersonData, String>("name"));
limit.setCellValueFactory(new PropertyValueFactory<PersonData, Integer>("limit"));
data = PriceData.getData();
personTable.setPeople(data);
searchInput.textProperty().addListener((ov, oldValue, newValue) -> {
final String input = searchInput.getText();
if (input.length() == 0) return;
searchInput.setText(input.substring(0, 1).toUpperCase() + input.substring(1).toLowerCase());
filterSearch();
});
}
}
When I call it from this class with PeopleIds.initialize(), an exception is thrown, telling me that there was an exception in the application start method.
Here is what was logged in its entirety:
Exception in Application start method
java.lang.reflect.InvocationTargetException
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.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(Unknown Source)
at com.sun.javafx.application.LauncherImpl.launchApplication(Unknown Source)
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 sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(Unknown Source)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$156(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: javafx.fxml.LoadException:
/C:/Confidential/bin/base/PersonGUI.fxml
at javafx.fxml.FXMLLoader.constructLoadException(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.load(Unknown Source)
at base.PersonGUI.start(PersonGUI.java:13)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$163(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$176(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$null$174(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$175(Unknown Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$149(Unknown Source)
... 1 more
Caused by: java.io.UncheckedIOException: java.nio.charset.MalformedInputException: Input length = 1
at java.io.BufferedReader$1.hasNext(Unknown Source)
at java.util.Iterator.forEachRemaining(Unknown Source)
at java.util.Spliterators$IteratorSpliterator.forEachRemaining(Unknown Source)
at java.util.stream.ReferencePipeline$Head.forEach(Unknown Source)
at base.PeopleIds.initialize(PeopleIds.java:17)
at base.GUIController.initialize(GUIController.java:36)
... 18 more
Caused by: java.nio.charset.MalformedInputException: Input length = 1
at java.nio.charset.CoderResult.throwException(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
... 24 more
Exception running application base.PersonGUI
I'm not sure what is going on here? I've looked into it and people have said to move the fxml file (the one that is used to format the content and is linked with the GUIController to the same package as the Main class, however it already is.
I've been wrestling with this issue for days to no avail. Do any of you have past experiences with this issue? If so, how did you resolve it? Thanks a lot.
If there is an Exception while the file is being read, not when opening the file, an unchecked exception is thrown for the Files.lines stream operation (Stream.forEach doesn't have a throws clause).
This happens here
Files.lines(Paths.get("res/ids/people_ids.txt")).forEach(s -> {
people.put(s.replaceAll(":.*", "").trim(), Integer.parseInt(s.replaceAll(".*:", "")));
});
, which you can easily see in the stacktrace:
Caused by: java.io.UncheckedIOException: java.nio.charset.MalformedInputException: Input length = 1
(This is caused by the wrong Charset being used, see Files.readAllBytes vs Files.lines getting MalformedInputException )
You don't catch this kind of exception with your catch clause:
} catch (IOException e) {
You need to use
} catch (Exception e) {
to catch the unchecked exceptions too.

Nullpointers in java and how to overcome those?

Say for example, if in a program you get a null-pointer error for adding a piece of code to your which program makes the program run fine but without that piece of code the program doesn't work as expected, would it be a good idea to allow the null-pointer error to happen, if so, is there any way of catching it before it displays onto the console. 1 way I am aware of is, using try and catch but in my past experience this hasn't worked, my attempt at using this might be wrong, but this is how I tried it.
try {
// line / s of code to catch the error from
} catch (java.lang.NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
edited: The list of error i am getting:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at playAGame.endGameResult(playAGame.java:204)
at playAGame.checkingWinner(playAGame.java:159)
at playAGame.callCheckWinner(playAGame.java:179)
at playAGame.moveSetup(playAGame.java:66)
at playAGame$1.actionPerformed(playAGame.java:52)
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.AWTEventMulticaster.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$200(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)
this is because of this line: button = new JButton[button.length][button.length];
I am creating a TicTacToe game and if I remove that line from my code, the game won't work properly.
edited: I believe this is one of the lines providing the null pointer, correct me if I am wrong. Basically, I have created a method checking if three given buttons have the value X, if it does then trigger the win variable to true. This is how I am checking if someone has won the TicTacToe game.
public void checkingWinner(JButton button1, JButton button2, JButton button3) {
if(buttonA.getText().equals(buttonB.getText()) && buttonB.getText().equals(buttonC.getText()) && buttonA.getText().equals("X"))
{
win = true;
System.out.pl("winner is X");
}
It's hard to tell without seeing the whole code, but it might be the case that the initialization you're doing of the array is throwing an exception since it's the first time it's being initialized, during which time it is being referenced.
If that's the case, you should solve this by using a constant for the width and height instead of self reference:
public static final int HEIGHT = ...;
public static final int WIDTH = ...;
...
button = new JButton[HEIGHT][WIDTH];
Are you sure that the line/s of code are throwing a NullPointerException? Because it works for me.
public class Main {
static String a;
public static void main(String args[]) {
try {
a.charAt(0);
} catch (java.lang.NullPointerException e) {
System.out.println("Thrown");
e.printStackTrace();
}
}
}

Java calls php to retrieve SQL data

I'm hoping someone can help figure this out. I've got a problem trying to run some backend php code from java that extracts sql data and sends it back via gson. I've used posting from java to php and inserting it into mysql database as a model, but, I can't seem to get beyond the HTTP 400 response code that is returned. I've edited the following java console to remove identifying names, but, the context should remain the same.
security: JSS is not configured
network: Connecting https://secure.justhost.com/<server>/<folder>/<php program name>.php with proxy=DIRECT
network: Cache entry not found [url: http://secure.justhost.com:443/crossdomain.xml, version: null]
network: Connecting http://secure.justhost.com:443/crossdomain.xml with proxy=DIRECT
network: Connecting http://secure.justhost.com:443/ with proxy=DIRECT
java.io.IOException: Server returned HTTP response code: 400 for URL: http://secure.justhost.com:443/crossdomain.xml
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at com.sun.deploy.net.CrossDomainXML.check(Unknown Source)
at com.sun.deploy.net.CrossDomainXML.check(Unknown Source)
at sun.plugin2.applet.SecurityManagerHelper.checkConnectHelper(Unknown Source)
at sun.plugin2.applet.AWTAppletSecurityManager.checkConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.<init>(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.New(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)
at newposting.GetCategories(newposting.java:864)
at newposting.<init>(newposting.java:170)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at com.sun.deploy.uitoolkit.impl.awt.AWTAppletAdapter$1.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(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)
basic: exception: java.lang.reflect.InvocationTargetException.
java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at com.sun.deploy.uitoolkit.impl.awt.AWTAppletAdapter.runOnEDTAndWait(Unknown Source)
at com.sun.deploy.uitoolkit.impl.awt.AWTAppletAdapter.instantiateApplet(Unknown Source)
at sun.plugin2.applet.Plugin2Manager.initAppletAdapter(Unknown Source)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.reflect.InvocationTargetException
at com.sun.deploy.uitoolkit.impl.awt.OldPluginAWTUtil.invokeAndWait(Unknown Source)
... 5 more
Caused by: java.lang.RuntimeException: java.security.AccessControlException: access denied ("java.net.SocketPermission" "secure.justhost.com:443" "connect,resolve")
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getHeaderField(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)
at newposting.GetCategories(newposting.java:864)
at newposting.<init>(newposting.java:170)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at com.sun.deploy.uitoolkit.impl.awt.AWTAppletAdapter$1.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(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)
Caused by: java.security.AccessControlException: access denied ("java.net.SocketPermission" "secure.justhost.com:443" "connect,resolve")
at java.security.AccessControlContext.checkPermission(Unknown Source)
at java.security.AccessController.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkConnect(Unknown Source)
at sun.plugin2.applet.SecurityManagerHelper.checkConnectHelper(Unknown Source)
at sun.plugin2.applet.AWTAppletSecurityManager.checkConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.<init>(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.New(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
... 29 more
security: Reset deny session certificate store
The url for the php code has no spaces. It does use underlines ("_") to join words. The request that is show in the console does not pass any parameters to the url because the php code has all it needs to retrieve the data. The java code is simply calling the backend php code. Here's a look at what I've got for the java code.
private ArrayList<String> GetCategories ()
{
ArrayList<String> cats = new ArrayList<String> ();
// preparation
String charset = "UTF-8";
String szURL = new String ();
if (!debugConfiguration)
szURL = "https://secure.justhost.com/<server>/<folder>/<php program name>.php";
else
szURL = "http://localhost/<php program name>.php";
// HTTP Post request
URL object = null;
try
{
object = new URL(szURL);
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
HttpsURLConnection con = null;
try
{
con = (HttpsURLConnection) object.openConnection();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
//add request header
try
{
con.setRequestMethod("POST");
}
catch (ProtocolException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty(charset, "utf-8");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
// Send post request
//con.setDoOutput(true);
/*
DataOutputStream wr = null;
try
{
wr = new DataOutputStream (con.getOutputStream());
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
try
{
wr.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
try
{
int responseCode = con.getResponseCode();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader in = null;
try
{
in = new BufferedReader(new InputStreamReader(con.getInputStream()));
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
String inputLine;
StringBuffer response = new StringBuffer();
try
{
while ((inputLine = in.readLine()) != null)
{
response.append(inputLine);
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
try
{
in.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
Gson gson = new Gson ();
jsonArticleCategories[] enums = gson.fromJson(response.toString(), jsonArticleCategories[].class);
for (int i=0; i<enums.length; ++i)
{
jsonArticleCategories jac = enums[i];
cats.add(jac.get_category());
}
return cats;
}
Again, I've edited the code sample to remove some names, but the context is valid. There are not spaces in any of the names for the server, folder, or program name. Lastly, let me add that the java code is digitally signed with a code signing certificate and run through jnlp. The php code runs correctly if executed manually from a browser.
Thanks for any help.

Categories