The SAX parser is throwing 403 exception for a valid URL, which loads without any issues in a browser. We are able to reproduce the problem with the sample code that follows. Pointers appreciated.
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.helpers.DefaultHandler;
public class StackOverflow {
public static void main(String[] args) {
SAXParserFactory factory2 = SAXParserFactory.newInstance();
try {
String uri;
uri = "https://www.sec.gov/Archives/edgar/data/1326801/000132680119000009/FilingSummary.xml"; // Does not work
// uri = "https://www.w3schools.com/xml/simple.xml"; // ** Works if this line is uncommented **
SAXParser saxParser = factory2.newSAXParser();
DefaultHandler eventHandler = new DefaultHandler();
saxParser.parse(uri, eventHandler);
// ...
// Business Logic
// ...
System.out.println("SUCCESS");
}
catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
The stacktrace is as follows:
java.io.IOException: Server returned HTTP response code: 403 for URL: https://www.sec.gov/Archives/edgar/data/1326801/000132680119000009/FilingSummary.xml
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLEntityManager.setupCurrentEntity(Unknown Source)
at com.sun.org.apache.xerces.internal.impl.XMLVersionDetector.determineDocVersion(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 com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl.parse(Unknown Source)
at javax.xml.parsers.SAXParser.parse(Unknown Source)
at StackOverflow.main(StackOverflow.java:15)
Related
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();
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.
I am working on a project of sorts to load HTML files from a server and display them in swing.
import java.io.*;
import java.net.*;
import java.util.regex.*;
import javax.swing.*;
public class webloader {
public static void loadcode(){
URL url = null;
try {
url = new URL("web"+File.separator+web.url+File.separator+"index.html");
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection con = null;
try {
con = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
Pattern p = Pattern.compile("text/html;\\s+charset=([^\\s]+)\\s*");
Matcher m = p.matcher(con.getContentType());
String charset = m.matches() ? m.group(1) : "ISO-8859-1";
Reader r = null;
try {
r = new InputStreamReader(con.getInputStream(), charset);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
StringBuilder buf = new StringBuilder();
while (true) {
int ch = 0;
try {
ch = r.read();
} catch (IOException e) {
e.printStackTrace();
}
if (ch < 0)
break;
buf.append((char) ch);
}
String str = buf.toString();
JFrame mainframe = new JFrame(web.url);
mainframe.setSize(800, 750);
mainframe.setResizable(false);
JPanel website = new JPanel();
JLabel webcontent = new JLabel(str);
website.add(webcontent);
mainframe.add(website);
mainframe.setVisible(true);
}
}
Error:
Loading test.com
Exception in thread "AWT-EventQueue-0" java.lang.Error: Unresolved compilation
roblem:
Syntax error on token ""web"", delete this token
at webloader.loadcode(webloader.java:11)
at web$1.actionPerformed(web.java:46)
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 Sou
ce)
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 Sou
ce)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Sou
ce)
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 Sou
ce)
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)
I am quite new to Java, so if I seem to be stupid or not know what I am doing, that's because I am.
I was trying to access the file wrong.
Correct code:
import java.io.*;
import java.net.*;
import java.util.regex.*;
import javax.swing.*;
public class webloader {
static JComponent page;
public static void loadcode(){
JEditorPane jep = new JEditorPane();
jep.setEditable(false);
try {
jep.setPage("http://(server):(port)/" + web.url);
}
catch (IOException e) {
jep.setContentType("text/html");
jep.setText("<html>Could not load webpage</html>");
}
JScrollPane scrollPane = new JScrollPane(jep);
JFrame f = new JFrame(web.url);
f.getContentPane().add(scrollPane);
f.setSize(512, 342);
f.show();
}
}
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
NullPointerException when try to capture imagem from webcam
I saw this good webcam applet but i'm beginner with java, and I'm trying just put another JButton called Capture that will take a picture through the webcam and save in a specific path.
CODE OF MY CAPTURE BUTTON
startC.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
// Grab a frame
FrameGrabbingControl fgc = new FrameGrabbingControl() {
#Override
public Component getControlComponent() {
// TODO Auto-generated method stub
return null;
}
#Override
public Buffer grabFrame() {
// TODO Auto-generated method stub
return null;
}
};
player.getControl("javax.media.control.FrameGrabbingControl");
buf = fgc.grabFrame();
// Convert it to an image
BufferToImage btoi = new BufferToImage((VideoFormat)buf.getFormat());
img = btoi.createImage(buf);
// show the image
//imgpanel.setImage(img);
// save image
try {
saveJPG(img,"c:\\test.jpg");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
SAVE JPG METHOD
public static void saveJPG(Image img, String s) throws IOException
{
BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_RGB);
File outputfile = new File("C:\\saved.jpg");
ImageIO.write(bi, "png", outputfile);
}
ERROR
Exception in thread "AWT-EventQueue-1" java.lang.NullPointerException
at com.colorfulwolf.webcamapplet.WebcamApplet$6.actionPerformed(WebcamApplet.java:524)
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.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)
In my line 524 I have the code
BufferToImage btoi = new BufferToImage((VideoFormat)buf.getFormat());
FGC declaration
FrameGrabbingControl fgc = new FrameGrabbingControl() {
#Override
public Component getControlComponent() {
// TODO Auto-generated method stub
return null;
}
#Override
public Buffer grabFrame() {
// TODO Auto-generated method stub
return null;
}
};
Your application is throw a NullPointerException because you try to invoke a method on a null object, buf.
Even though you declare buf = fgc.grabFrame();, your buf object is null because fgc.grabFrame() is returning null.
#Override
public Buffer grabFrame() {
// TODO Auto-generated method stub
return null;
}
To fix the issue, you can return new Buffer() instead of null in your fgc.grabFrame() implementation.
I am programming on a system with client running Java Applet on one end and server on the other. Now I have the client and server on the same computer. But as a client, I cannot see the applet and I get error like below:
java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(Unknown Source)
at MainJApplet.init(MainJApplet.java:58)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(Unknown Source)
at RequestServer.sendRequest(RequestServer.java:25)
at createGUI.createEditingBar(createGUI.java:1313)
at GUI.createAndShowGUI(GUI.java:813)
at MainJApplet.init(MainJApplet.java:137)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
java.net.ConnectException: Connection refused: connect
java.lang.NullPointerException
at createGUI.createEditingBar(createGUI.java:1315)
at GUI.createAndShowGUI(GUI.java:813)
at MainJApplet.init(MainJApplet.java:137)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Exception: java.lang.NullPointerException
Below is where the problem traced back:
URL url = new URL(ipAddr);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); // exception happens
I checked http://localhost:8080/ and port conflict. I have turn off windows firewall and yet the problem exists. Can someone kindly point me some direction? Any advice would be great! Thanks ahead!
I apologize for the long code. The first is for client.
import javax.swing.*;
import java.awt.*;
import java.net.*;
import java.io.*;
public class MainJApplet extends JApplet {
GUI gui = new GUI();
Thread renewThread;
public void init() {
//pass parameters from url to applet
String filePath = this.getParameter("FilePath");
//temporary solution to bypass the new extention
String userName = this.getParameter("UserName");
String ipAddr = this.getParameter("IpAddress");
String userLevel = this.getParameter("UserLevel");
String ticket = this.getParameter("Ticket");
String accessMode = this.getParameter("AccessMode"); //1-normal 2-shared 3-email
//sharedTo will be get from the file path infor
String sharedTo = this.getParameter("ShareTo");
String type = this.getParameter("Type");
gui.shareTo = sharedTo;
gui.ticket = ticket; //this gui.ticket is used to varify email access, will be replaced
String relativePath = "";
try {
//connect to servlet
URL url = new URL(ipAddr);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
//Passing NAME+FILE+TICKET+TYPE to server at the initialization stage
out.write("IN");
out.write(userName + "#");
out.write(filePath + "#");
out.write(ticket + "#");
out.write(type + "#");
out.close();
//Wait for server response
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream()));
String dcodedStr;
StringBuffer decodedStringBuffer = new StringBuffer("");
while ((dcodedStr = in.readLine()) != null) {
decodedStringBuffer.append(dcodedStr);
}
String dStr = decodedStringBuffer.toString();
in.close();
if (dStr.equals("NOT_AUTHORIZED")) { //not passing authentication check
JOptionPane.showMessageDialog(new JFrame(),
"Access Denied",
"Warning!",
JOptionPane.ERROR_MESSAGE);
return;
} else {//pass authentication check
String[] initResp = dStr.split("#");
gui.FID = initResp[0]; //file ID
gui.EditMode = Boolean.parseBoolean(initResp[1]);
gui.userLevel = 1; //temporary set all as normal user
boolean firstOpen = Boolean.parseBoolean(initResp[2]);
relativePath = initResp[3];
if (initResp[4].trim().equals("normal")) {//owner
gui.accessMode = 1;
} else {//shared user
gui.accessMode = 2;
}
}
}catch(UnknownServiceException exp){
exp.printStackTrace();
}catch(IOException ex){
ex.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
}
public void destroy() {
gui.check_upon_window_close();
if (gui.is_new_drawing == 0) {
//2010.9.29 workDir -> FID
if (gui.EditMode) {
RequestServer.canClose(gui.IpAddress, gui.user, gui.FID);
} else {
RequestServer.canCloseNoEdit(gui.IpAddress, gui.user, gui.FID);
}
}
renewThread.stop();
}
}
Based off your comments my guess is that your server is binding to the loopback address (127.0.0.1, aka localhost). You didn't post what the server software is, but change it's configuration so that it binds on 0.0.0.0 instead. That should fix your issue.