i'm trying use a java class in matlab and i get a nullpointer exception.
import com.oanda.fxtrade.api.*;
public class TestLogin {
public static void main(String[] args) {
FXClient fxclient = null;
fxclient = API.createFXGame();
System.out.print("Logging in as \"" + "\"...");
fxclient.setWithRateThread(true);
try {
fxclient.login("user", "password", "RateTicker Test");
} catch (SessionException e) {
System.exit(1);
} catch (InvalidUserException e) {
System.exit(1);
} catch (InvalidPasswordException e) {
System.exit(1);
} catch (MultiFactorAuthenticationException e) {
System.exit(1);
}
System.out.print("login complete. Registering listeners...");
fxclient.logout();
}
if i run this class by itself it runs just fine, it logs in, gives me the message and logs out.
in matlab, i create an instance with
obj = TestLogin than
obj.main('')
and i get:
>> obj.main('')
API proxy version : null
API implementation jar : http://dynamic-api.oanda.com/oanda_fxtrade_implementation.jar
Logging in as ""...Java exception occurred:
java.lang.NullPointerException
at com.oanda.fxtrade.api.implementation.FXClient.login(Unknown Source)
at com.oanda.fxtrade.api.implementation.FXClient.login(Unknown Source)
at com.oanda.fxtrade.api.implementation.FXClient.login(Unknown Source)
at com.oanda.fxtrade.api.implementation.FXClient.login(Unknown Source)
at TestLogin.main(TestLogin.java:32)
for the test i've hard coded the user and password. the error comes from the fxclient.login line. if there is a null pointer, i guess it doesn't know where the fxclient is?("FXClient" is an interface)
what is the object that needs to be instantiated?
Related
I am new to android apps development. Recently,Im writing an application which able to show public ip based on Ipify. So far, i already:
Download the required jar file and put inside libs folder
I also compile file within gradle
Then i import required class it to my class
How to use Ipify, according to its website:
import org.ipify.Ipify;
public class HelloIP {
public static void main(String[] args) throws IOException {
System.out.println(Ipify.getPublicIp());
}
}
I write the following method to be invoked from another class:
public static String getPublicIp() throws IOException{
String ip = Ipify.getPublicIp();
return ip;
}
Another Class
//Get wifi
getWifiName wifiInfo = new getWifiName();
String myIP = wifiInfo.getPublicIp();
However, i keep getting:
Error:(52, 43) error: unreported exception IOException; must be caught
or declared to be thrown
I tried to modify the code and use the following try and catch, but still got the same error.
public static String getPublicIp() throws IOException{
String myip = Ipify.getPublicIp();
try{
return myip;
}
catch (IOException e){
System.out.println("General I/O exception: " + e.getMessage());
e.printStackTrace();
}
}
Im not too good in catch and throw exception, and already spent the whole day for this.I dont have idea anymore to fix this error..T.T
public static String getPublicIp() {
try{
return Ipify.getPublicIp();
}catch (IOException e){
System.out.println("General I/O exception: " + e.getMessage());
e.printStackTrace();
}
return null;
}
In case it didn't help, clean project in your IDE. You may have some data cached and it might be a reason.
Your problem is in another class! As you have declared the method getPublicIp() to throw IOException that class is afraid of receiving the Exception and therefor requests catching it.
In Java you have two types of Exceptions. Checked and unchecked. Checked Exceptions must be caught.
In Java Exceptions are used for marking unexpected situations. For example parsing non-numeric String to a number (NumberFormatException) or calling a method on a null reference (NullPointerException). You can catch them in many ways.
Unchecked Exceptions are those which extend RunTimeException. They are used for marking unexpected states usually caused by user's input. They shouldn't cause harm and should be worked out with business logic. You don't have to catch them, but sometimes you should.
On the other hand there are Checked Exceptions which mark dangerous situations. For example the application being unable to open a file. As those situations are found dangerous, you must catch them.
try{
//some code
} catch (NumberFormatException e1) {
e.printStackTrace() //very important - handles the Exception but prints the information!
} catch (NullPointerException e2) {
e.printStackTrace();
}
or using the fact, that they all extend Exception:
try {
//somecode
} catch (Exception e) {
e.printStackTrace;
};
or since Java 7:
try {
//somecode
} catch (NullPointerException | NumberFormatException e) {
e.printStackTrace;
};
So here it is my program:
public static void main(String[] args) {
UsbServices services = null;
try {
services = UsbHostManager.getUsbServices();
hub = services.getRootUsbHub();
} catch (SecurityException | UsbException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
And I have created the file 'javax.usb.properties' with inside:
javax.usb.services = org.usb4java.javax.Services
Like it's said in the documentation
At the moment of 'getRootUsbHub()' I have this error:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/lang3/builder/HashCodeBuilder
Does someone know why the method getRootUsbHub() doesn't work ?
You miss the commons-lang3.jar in your classpath. Download and add it.
EDIT:
Found the solution. It was a problem with minifing the code while maven build process. Run the OrientDB in a Java Applet is possible.
I have problems starting the inmemory OrientDB in a Java Applet. I use a signed Applet with OrientDB version 1.0.1. Did someone implemented the OrientDB in a Applet and can verify that this is possible or could help me with this exception?
The exception I get:
2012-06-20 11:22:24:734 INFO OrientDB Server v1.0.1 is starting up... [OServer]Exception in thread "thread applet-de.test.all.Applet-1" sun.misc.ServiceConfigurationError: com.orientechnologies.orient.core.sql.OCommandExecutorSQLFactory: Provider com.orientechnologies.orient.core.sql.ODefaultCommandExecutorSQLFactory not found
at sun.misc.Service.fail(Service.java:129)
at sun.misc.Service.access$000(Service.java:111)
at sun.misc.Service$LazyIterator.next(Service.java:273)
at com.orientechnologies.orient.core.sql.OSQLEngine.getCommandFactories(OSQLEngine.java:186)
at com.orientechnologies.orient.core.sql.OSQLEngine.getCommandNames(OSQLEngine.java:216)
at com.orientechnologies.orient.core.sql.OSQLEngine.getCommand(OSQLEngine.java:239)
at com.orientechnologies.orient.core.sql.OCommandExecutorSQLDelegate.parse(OCommandExecutorSQLDelegate.java:41)
at com.orientechnologies.orient.core.sql.OCommandExecutorSQLDelegate.parse(OCommandExecutorSQLDelegate.java:31)
at com.orientechnologies.orient.core.storage.OStorageEmbedded.command(OStorageEmbedded.java:62)
at com.orientechnologies.orient.core.command.OCommandRequestTextAbstract.execute(OCommandRequestTextAbstract.java:60)
at com.orientechnologies.orient.core.metadata.schema.OSchemaShared.createClass(OSchemaShared.java:218)
at com.orientechnologies.orient.core.metadata.schema.OSchemaShared.createClass(OSchemaShared.java:164)
at com.orientechnologies.orient.core.metadata.schema.OSchemaShared.createClass(OSchemaShared.java:145)
at com.orientechnologies.orient.core.metadata.schema.OSchemaShared.createClass(OSchemaShared.java:116)
at com.orientechnologies.orient.core.metadata.schema.OSchemaProxy.createClass(OSchemaProxy.java:65)
at com.orientechnologies.orient.core.metadata.security.OSecurityShared.createMetadata(OSecurityShared.java:259)
at com.orientechnologies.orient.core.metadata.security.OSecurityShared.create(OSecurityShared.java:202)
at com.orientechnologies.orient.core.metadata.security.OSecurityProxy.create(OSecurityProxy.java:37)
at com.orientechnologies.orient.core.metadata.OMetadata.create(OMetadata.java:68)
at com.orientechnologies.orient.core.db.record.ODatabaseRecordAbstract.create(ODatabaseRecordAbstract.java:171)
at com.orientechnologies.orient.core.db.ODatabaseWrapperAbstract.create(ODatabaseWrapperAbstract.java:53)
at com.orientechnologies.orient.core.db.ODatabaseRecordWrapperAbstract.create(ODatabaseRecordWrapperAbstract.java:54)
at com.orientechnologies.orient.server.OServer.loadStorages(OServer.java:451)
at com.orientechnologies.orient.server.OServer.loadConfiguration(OServer.java:394)
at com.orientechnologies.orient.server.OServer.startup(OServer.java:152)
at com.orientechnologies.orient.server.OServer.startup(OServer.java:143)
at com.orientechnologies.orient.server.OServer.startup(OServer.java:132)
at de.test.all.Applet$1.run(Applet.java:132)
at de.test.all.Applet$1.run(Applet.java:125)
at java.security.AccessController.doPrivileged(Native Method)
at de.test.all.Applet.init(Applet.java:124)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Plugin2Manager.java:1639)
at java.lang.Thread.run(Thread.java:680)
My Applet code to start the DB:
public class Applet extends java.applet.Applet {
OrientDbConfigurationLoader configLoader = null;
OServer server = null;
ODatabaseDocumentTx db = null;
#Override
public void init() {
AccessController.doPrivileged(new
PrivilegedAction<OServer>() {
public OServer run() {
configLoader = new OrientDbConfigurationLoader("db/", "test");
try {
server = OServerMain.create();
server.startup(configLoader.loadDefaultConfig());
server.activate();
} catch (InstanceAlreadyExistsException e) {
server = OServerMain.server();
} catch (Exception e) {
System.out.println("Something went wrong while the server should start");
e.printStackTrace();
}
try {
db = new ODatabaseDocumentTx("memory:temp");
db = db.open(OrientDbConfigurationLoader.USERNAME, OrientDbConfigurationLoader.PASSWORD);
} catch (Exception e) {
System.out.println("Can't init the in-memory db.");
e.printStackTrace();
}
return null;
}
});
}
}
the problem seems the usage of Java Service Registry. Look at:
OClassLoaderHelper.lookupProviderWithOrientClassLoader()
it calls:
ServiceRegistry.lookupProviders(clazz);
I've just added in SVN trunk (r5909) this check:
try {
factories.add(ite.next());
} catch (Exception e) {
OLogManager.instance().warn(null, "Cannot load OCommandExecutorSQLFactory instance from service registry", e);
}
In this way a WARN is dumped but you can continue to configure your own factories if needed.
When I received an exception such as IOException or RunTimeException, I can only know the line number in the class.
First of my question. Is it possible to retrieve the method name through exception?
Second, is it possible to retrieve the method and the parameter of this method by line number?
p.s. I need to know the exact method name and its parameters, because I want to distinguish the overloading methods. To distinguish overloading methods, all that I know is to determine its parameters.
try{
//your code here}
catch(Exception e){
for (StackTraceElement st : e.getStackTrace())
{
System.out.println("Class: " + st.getClassName() + " Method : "
+ st.getMethodName() + " line : " + st.getLineNumber());
}
}
as you can see in the code above, you can get the stackTrace and loop over it to get all the method names and line numbers, refer to this for more info http://download.oracle.com/javase/1.4.2/docs/api/java/lang/StackTraceElement.html
If you look at the stacktrace you can know in which line the error occurred.
When using an overriden method you get the exact class name, source file and line number, you just have to know how to read it.
From that page:
java.lang.NullPointerException
at MyClass.mash(MyClass.java:9) //<--- HERE!!!!
at MyClass.crunch(MyClass.java:6)
at MyClass.main(MyClass.java:3)
This says, the problem occurred in line 9 of file MyClass.java in the method mash, which was in turn invoked by the method crunch at line 6 of the same file which was invoked by main in line 3 of the same file.
Heres the source code:
class MyClass {
public static void main(String[] args) {
crunch(null); // line 3
}
static void crunch(int[] a) {
mash(a); // line 6
}
static void mash(int[] b) {
System.out.println(b[0]);//line 9, method mash.
}
}
Basically you just have to ... well read it!
Stacktraces are a bit hard to grasp the first time, but later they become a very powerful tool.
I hope this helps.
pass it the exception and it will print the parameter types of the methods along with the exception
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
public class Main
{
public static void main(String[] args)
{
new Main().run();
}
public void run(){
try
{
new Car().run(60, "Casino");
}
catch (Exception e)
{
detailedException(e);
}
try
{
new Engine().run(10);
}
catch (Exception e)
{
detailedException(e);
}
}
public void detailedException(Exception e)
{
try
{
StringBuilder buffer = new StringBuilder(e.getClass().getName()).append(" \"").append(e.getMessage()).append("\"\n");
for (var trace: e.getStackTrace())
{
buffer.append("\tat ").append(trace.getClassName()).append(".").append(trace.getMethodName()).append("(").append(trace.getFileName()).append(":").append(trace.getLineNumber()).append(")[");
Class<?> clazz = Class.forName(trace.getClassName());
ArrayList<Method> methods = new ArrayList<>(Arrays.asList(clazz.getMethods()));
methods.removeIf(m -> !m.getName().equals(trace.getMethodName()));
Method method = methods.get(0);
for (var param: method.getParameters())
{
buffer.append(param.getName()).append(":").append(param.getParameterizedType().getTypeName()).append(", ");
}
buffer.append("]->").append(method.getGenericReturnType().getTypeName()).append("\n");
}
System.err.println(buffer);
}
catch (Exception parseFailed){
e.printStackTrace();
}
}
}
class Car extends Engine
{
public void run(int when, String where) throws Exception
{
super.run(25);
}
}
class Engine
{
public String run(int For) throws Exception
{
throw new Exception("need more fuel");
}
}
While upgrading sun application server 8.2 to a new patch level an exception occurred and I don't know why. Following a code snippet from a Servlet:
public void init() throws ServletException {
Properties reqProperties = new Properties();
try {
reqProperties.load(this.getClass().getResourceAsStream(
"/someFile.properties"));
} catch (IOException e) {
e.printStackTrace();
}
...
}
The file does exists on the classpath and in previous patch versions it worked just fine. but now when deploying this result in a exception. The stack trace:
[#|2010-04-14T16:43:48.208+0200|WARNING|sun-appserver-ee8.2|javax.enterprise.system.core.classloading|_ThreadID=11;|loader.InputStreams with no valid reference is closed
java.lang.Throwable
at com.sun.enterprise.loader.EJBClassLoader$SentinelInputStream.<init>(EJBClassLoader.java:1172)
at com.sun.enterprise.loader.EJBClassLoader.getResourceAsStream(EJBClassLoader.java:858)
at java.lang.Class.getResourceAsStream(Class.java:1998)
at a.package.TestServlet.init(TestServlet.java:44)
at javax.servlet.GenericServlet.init(GenericServlet.java:261)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:592)
at org.apache.catalina.security.SecurityUtil$1.run(SecurityUtil.java:249)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAsPrivileged(Subject.java:517)
at org.apache.catalina.security.SecurityUtil.execute(SecurityUtil.java:282)
at org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:165)
at org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:118)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1093)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:931)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4183)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4535)
at com.sun.enterprise.web.WebModule.start(WebModule.java:241)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1086)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:847)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1086)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:483)
at org.apache.catalina.startup.Embedded.start(Embedded.java:894)
at com.sun.enterprise.web.WebContainer.start(WebContainer.java:741)
at com.sun.enterprise.web.HttpServiceWebContainer.startInstance(HttpServiceWebContainer.java:963)
at com.sun.enterprise.web.HttpServiceWebContainerLifecycle.onStartup(HttpServiceWebContainerLifecycle.java:50)
at com.sun.enterprise.server.ApplicationServer.onStartup(ApplicationServer.java:300)
at com.sun.enterprise.server.PEMain.run(PEMain.java:308)
at com.sun.enterprise.server.PEMain.main(PEMain.java:221)
|#]
I've no idea what could be the problem anyone have any idea?
(note that I changed some names in the code and stacktrace)
Are you sure it throws an exception? We get warnings like this in Glassfish all the time. The EJBClassLoader uses a throwable to dump the stack trace so it may look like an exception to you.
EJBClassLoader wraps all streams with sentinels. This warning simply tells you that your stream is not closed. You can safely ignore it. To get rid of the warning, you have to close the stream after you use it.
you should always close inputstreams after using:
public void init() throws ServletException {
InputStream str = null;
Properties reqProperties = new Properties();
try {
str = this.getClass().getResourceAsStream("/someFile.properties");
reqProperties.load(str);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (str != null) {
try {
str.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
btw, the finally clause can be made a lot simpler using apache commons / io:
finally {
IOUtils.closeQuietly(str);
}