Getting null pointer exception while loading schema - xsd

public class TestValidatorSample {
public static void main(String aa[]) throws SAXException, IOException, ParserConfigurationException {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder parser = dbf.newDocumentBuilder();
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
// /test_elements.xsd
Schema schema = factory.newSchema(new StreamSource(TestValidatorSample.class.getResource(
"/xsds/pakagename/test_elements.xsd").toString()));
Validator validator = schema.newValidator();
DOMSource domsrc = new DOMSource(parser.parse(new InputSource("test-example.xml")));
try {
validator.validate(domsrc);
System.out.println("Validation successfull!!!");
// System.out.println(xmlFile.getSystemId() + " is valid");
} catch (SAXException e) {
System.out.println("Validation not successfull!!!");
// System.out.println(xmlFile.getSystemId() + " is NOT valid");
System.out.println("Reason: " + e.getLocalizedMessage());
}
}
}
Exception in thread "main" java.lang.NullPointerException at line 47.
I am getting a nullpointer(as mentioned above) exception while loading a schema.
In the above code snippet I am trying to load a schema which will be used to validate xmls generated in my application .
Can anybody please help me to find out why I am getting null pointer exception ?

Related

org.testng.TestNGException: Method tearDown requires 1 parameters but 0 were supplied in the #Configuration annotation

I am not able to understand what is required as parameter, can anyone help me with this.
I have written below code:-
#Test(groups = "cucumber", description = "Runs Cucumber Feature", dataProvider = "features")
public void feature(CucumberFeatureWrapper cucumberFeature) throws Exception {
testNGCucumberRunner.runCucumber(cucumberFeature.getCucumberFeature());
}
#AfterMethod(alwaysRun = true)
public void tearDown(Scenario scenario) {
scenario.write("Finished Scenario");
if (scenario.isFailed()) {
String screenshotName = scenario.getName().replaceAll(" ", "_");
try {
File sourcePath =((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
File destinationPath = new File(System.getProperty("user.dir") + "/Screenshots/" + screenshotName + ".png");
Files.copy(sourcePath, destinationPath);
Reporter.addScreenCaptureFromPath(destinationPath.toString());
} catch (IOException e) {
}
driver.close();
}
}
And I am getting below error:-
FAILED CONFIGURATION: #AfterMethod tearDown
org.testng.TestNGException: Method tearDown requires 1 parameters but
0 were supplied in the #Configuration annotation.
You cannot pass a Cucumber Scenario object to a TestNg configuration method. The AfterMethod will be called by TestNg and will not be able to inject the Scenario object. For a list of objects that are injected automatically refer to this - http://testng.org/doc/documentation-main.html#native-dependency-injection
Either use the After annotation of Cucumber and pass the Scenario object.
#cucumber.api.java.After
public void tearDown(Scenario scenario)
Or use the AfterMethod of TestNg and pass the ITestResult object.
#org.testng.annotations.AfterMethod
public void tearDown(ITestResult result)

How to log ServiceStack.Messaging.Message to a database with OrmLite?

Given the following code:
public class AppHost : BasicAppHost
{
public AppHost()
: base(typeof(LeadService).Assembly){}
public override void Configure(Container container)
{
SetConfig(new HostConfig
{
DebugMode = ConfigUtils.GetAppSetting<bool>("DebugMode:Enabled", false)
});
//DataAccess
//Set ORMLite to work with columns like ColumnLikeThis
PostgreSqlDialect.Provider.NamingStrategy = new OrmLiteNamingStrategyBase();
//Set ORMLite to use ServiceStack.Text for JSON serialization
PostgreSqlDialect.Provider.StringSerializer = new JsonStringSerializer();
var dbFactory = new OrmLiteConnectionFactory(ConfigUtils.GetConnectionString("Lead:Default"), PostgreSQLDialectProvider.Instance);
container.Register<IDbConnectionFactory>(dbFactory);
//RabbitMQ
container.Register<IMessageService>(c => new RabbitMqServer()
{
AutoReconnect = true,
DisablePriorityQueues = true,
});
var mqServer = container.Resolve<IMessageService>();
//Handlers
container.Register<IMessageHandlers>(c => new MessageHandlers(c.Resolve<IDbConnectionFactory>()));
var handlers = container.Resolve<IMessageHandlers>();
mqServer.RegisterHandler<LeadInformation>(handlers.OnProcessLeadInformation, handlers.OnExceptionLeadInformation);
mqServer.Start();
}
}
public class MessageHandlers : IMessageHandlers
{
private readonly ILog _log = LogManager.GetLogger(typeof(MessageHandlers));
private readonly IDbConnectionFactory _connectionFactory;
public MessageHandlers(IDbConnectionFactory connectionFactory)
{
_connectionFactory = connectionFactory;
}
public object OnProcessLeadInformation(IMessage<LeadInformation> request)
{
var sw = Stopwatch.StartNew();
try
{
// Log to the database
using (var db = _connectionFactory.OpenDbConnection())
{
db.CreateTableIfNotExists<Message>();
var msg = request as Message<LeadInformation>; // Anyway not to have to cast it?
db.Save(msg); // Does not work
}
// Run rules against lead
// Log response to database
// return response
}
catch (Exception exception)
{
_log.Error(request, exception);
}
return new LeadInformationResponse
{
TimeTakenMs = sw.ElapsedMilliseconds,
Result = "Processed lead {0}".Fmt(request.GetBody().LeadApplication.LastName)
};
}
public void OnExceptionLeadInformation(IMessage<LeadInformation> request, Exception exception)
{
_log.Error(request, exception);
}
}
Is it possible to persist the whole message? The table gets created, and I was able to save one message, and that's it no more saves with different messages.
Update
Turns out I'm getting an exception during the save operation
Npgsql.NpgsqlException was caught
_HResult=-2147467259
_message=ERROR: 42P01: relation "Message1" does not exist
HResult=-2147467259
IsTransient=false
Message=ERROR: 42P01: relation "Message1" does not exist
Source=Npgsql
ErrorCode=-2147467259
BaseMessage=relation "Message1" does not exist
Code=42P01
ColumnName=""
ConstraintName=""
DataTypeName=""
Detail=""
ErrorSql=SELECT "Id", "CreatedDate", "Priority", "RetryAttempts", "ReplyId", "ReplyTo", "Options", "Error", "Tag", "Body" FROM "Message1" WHERE "Id" = (('ab297bca-5aea-4886-b09b-5a606b0764d5')::uuid)
File=src\backend\parser\parse_relation.c
Hint=""
Line=986
Position=119
Routine=parserOpenTable
SchemaName=""
Severity=ERROR
TableName=""
Where=""
StackTrace:
at Npgsql.NpgsqlState.d__0.MoveNext()
at Npgsql.ForwardsOnlyDataReader.GetNextResponseObject(Boolean cleanup)
at Npgsql.ForwardsOnlyDataReader.GetNextRowDescription()
at Npgsql.ForwardsOnlyDataReader.NextResultInternal()
at Npgsql.ForwardsOnlyDataReader..ctor(IEnumerable1 dataEnumeration, CommandBehavior behavior, NpgsqlCommand command, NotificationThreadBlock threadBlock, Boolean preparedStatement, NpgsqlRowDescription rowDescription)
at Npgsql.NpgsqlCommand.GetReader(CommandBehavior cb)
at Npgsql.NpgsqlCommand.ExecuteReader(CommandBehavior cb)
at Npgsql.NpgsqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader()
at ServiceStack.OrmLite.OrmLiteReadExtensions.ExecReader(IDbCommand dbCmd, String sql)
at ServiceStack.OrmLite.OrmLiteResultsFilterExtensions.ConvertTo[T](IDbCommand dbCmd, String sql)
at ServiceStack.OrmLite.OrmLiteReadExtensions.SingleById[T](IDbCommand dbCmd, Object value)
at ServiceStack.OrmLite.OrmLiteWriteExtensions.Save[T](IDbCommand dbCmd, T obj)
at ServiceStack.OrmLite.OrmLiteWriteConnectionExtensions.<>c__DisplayClass5a1.b__58(IDbCommand dbCmd)
at ServiceStack.OrmLite.OrmLiteExecFilter.Exec[T](IDbConnection dbConn, Func2 filter)
at ServiceStack.OrmLite.ReadConnectionExtensions.Exec[T](IDbConnection dbConn, Func2 filter)
at ServiceStack.OrmLite.OrmLiteWriteConnectionExtensions.Save[T](IDbConnection dbConn, T obj, Boolean references)
at LO.Leads.Processor.ServiceInterface.MessageHandlers.OnProcessLeadInformation(IMessage`1 request) in e:\Lead\src\LO.Leads.Processor\LO.Leads.Processor.ServiceInterface\MessageHandlers.cs:line 41
Update 2
Turns out my cast was wrong, this now works
using (var db = _connectionFactory.OpenDbConnection())
{
db.CreateTableIfNotExists<Message>();
db.Save(request as Message);
}
Thank you,
Stephen
You have to cast the IMessage back to a Message DTO in order for it to work. e.g.
using (var db = _connectionFactory.OpenDbConnection())
{
db.CreateTableIfNotExists<Message>();
db.Save(request as Message);
}

jaxb - how to know when eventhandler is called (during validation)

I am parsing XML with JAXB and have created an event handler that will display errors if there were issues on validation.
The event handler is called and prints out errors; How do I throw an exception if the event handler is called (after printout?)
In the code, I have no idea when the event handler is called, it is simply called on a validation error; I need the ability to move a file to a /dir/ after the event handler returns.
My event handler looks like this:
import base.helper.HelperBase;
import org.springframework.stereotype.Component;
import javax.xml.bind.ValidationEvent;
import javax.xml.bind.ValidationEventHandler;
import java.util.logging.Level;
/**
*
*/
#Component
public class MyValidationEventHandler extends HelperBase implements ValidationEventHandler {
public boolean handleEvent(ValidationEvent event) {
logger.log(Level.INFO, "\n---");
System.out.println("EVENT");
System.out.println("\nEVENT");
System.out.println("SEVERITY: " + event.getSeverity());
System.out.println("MESSAGE: " + event.getMessage());
System.out.println("LINKED EXCEPTION: " + event.getLinkedException());
System.out.println("LOCATOR");
System.out.println(" LINE NUMBER: " + event.getLocator().getLineNumber());
System.out.println(" COLUMN NUMBER: " + event.getLocator().getColumnNumber());
System.out.println(" OFFSET: " + event.getLocator().getOffset());
System.out.println(" OBJECT: " + event.getLocator().getObject());
System.out.println(" NODE: " + event.getLocator().getNode());
System.out.println(" URL: " + event.getLocator().getURL());
new Exception("fail");
return true;
}
}
When processing, my code looks like this:
private void processXmlFile(String file) throws Exception {
// todo: test for file existence, get size, print stats
try {
logger.log(Level.INFO, "Processing: " + file);
SchemaFactory sf = null;
Schema schema = null;
JAXBContext jctx = JAXBContext.newInstance("mypackage.jaxb");
Unmarshaller unmarshaller = jctx.createUnmarshaller();
if (validate) {
sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
schema = sf.newSchema(new File(xsd));
unmarshaller.setSchema(schema);
eventHandler.setLogger(logger);
unmarshaller.setEventHandler(eventHandler);
}
JAXBElement<MyType> mytype = unmarshaller.unmarshal(new StreamSource(new File(file)), MyType.class);
MyType ct = mytype.getValue();
} catch (Exception e) { // if find a problem file, just move it out of the way and keep processing
// if the event handler is called, I want to throw an exception and do something here.
// move file to failed
fileUtils.moveFile(config.getErrorDir(), file);
// on an unmarshall failure, this exception is not thrown/caught because the event handler handles things and returns true
}
}
Please read How to Throw Exceptions.
In your event handler you need to throw() an Exception perhaps with something like:
throw new ValidationException(); // throw exeption
Instead of:
new Exception("fail"); // create exception but do nothing with it?
And you would define your ValidationException as:
public class ValidationException extends RuntimeException {
public ValidationException(final String s) {
super(s);
}
Change:
public boolean handleEvent(ValidationEvent event) {
To:
public boolean handleEvent(ValidationEvent event) throws ValidationException {
In processXmlFile() we now need something like:
catch (ValidationException e) {
// catch more specific exception first
fileUtils.moveFile(config.getErrorDir(), file);
catch (Exception e) {
// deal with any other exceptions ...
}

How can I unlock a file locked by JAXB's unmarhsaller

I'm unmarshalling an XML file with JAXB w/Java 1.7.0_03 on Windows 7 x64 using the following code:
try (InputStream xsdStream = ConfigurationService.class.getClassLoader().getResourceAsStream(CONFIG_XSD_FILE_NAME)) {
configFile = new File(configFilePath);
if (configFile.exists()) {
context = JAXBContext.newInstance(Config.class);
Unmarshaller unMarshaller = context.createUnmarshaller();
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
StreamSource xsdStreamSource = new StreamSource(xsdStream);
Schema schema = sf.newSchema(xsdStreamSource);
unMarshaller.setSchema(schema);
Object xmlObject = Config.class.cast(unMarshaller.unmarshal(configFile));
myConfig = (Config) xmlObject;
} else {
log.severe(configFile.getAbsolutePath() + " does not exist, can not parse configuration info from it.");
}
}
Code which calls this method subsequently deletes the XML file.
The XML file will properly delete if unmarhalling is successful. However, if the above code throws and Exception, eg. a SAXException, the XML file remains locked indefinitely and the calling code is not able to delete it with File.delete().
This feels like JAXB is not closing the resource/file in this case. Is it my responsibility to do that somehow or is this a bug?
Reviewing the javadoc for Unmarshaller did not shed any light on this and Googling this issue revealed this old, unanswered question from 2008.
SHORT ANSWER
The behaviour you have described sounds like a bug in the JAXB reference implementation. You can open a ticket using the link below:
http://java.net/jira/browse/JAXB/
Work Around
Instead of unmarshalling from a File you can unmarshal from a FileInputStream and control that it is closed correctly yourself after unmarshalling.
LONG ANSWER
I have not been able to reproduce the issue that you are seeing. I have included what I have tried below. I am using JDK 1.7.0_07 x64 for the Mac.
Configuration Service
Most of the code below is copied from your question. I have added the call to delete the input file and then output if the file still exists.
package forum14765898;
import java.io.*;
import javax.xml.XMLConstants;
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.*;
public class ConfigurationService {
private static final String CONFIG_XSD_FILE_NAME = "forum14765898/schema.xsd";
public static void main(String[] args) throws Exception {
File configFile = null;
String configFilePath = "src/forum14765898/input.xml";
JAXBContext context;
Config myConfig;
try (InputStream xsdStream = ConfigurationService.class.getClassLoader().getResourceAsStream(CONFIG_XSD_FILE_NAME)) {
configFile = new File(configFilePath);
if (configFile.exists()) {
context = JAXBContext.newInstance(Config.class);
Unmarshaller unMarshaller = context.createUnmarshaller();
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
StreamSource xsdStreamSource = new StreamSource(xsdStream);
Schema schema = sf.newSchema(xsdStreamSource);
unMarshaller.setSchema(schema);
Object xmlObject = Config.class.cast(unMarshaller.unmarshal(configFile));
myConfig = (Config) xmlObject;
} else {
//log.severe(configFile.getAbsolutePath() + " does not exist, can not parse configuration info from it.");
}
} catch(Exception e) {
e.printStackTrace(System.out);
}
configFile.delete();
System.out.println(configFile.exists());
}
}
schema.xsd
Below is the simple XML schema that I am using.
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema">
<element name="config">
<complexType>
<sequence>
<element name="bar" type="int"/>
</sequence>
</complexType>
</element>
</schema>
input.xml
Below is the XML input. The bar element is not valid according to the XML schema. When a Schema is set on the Unmarshaller this document will be enough to cause an Exception to be thrown while performing an unmarshal operation.
<?xml version="1.0" encoding="UTF-8"?>
<config>
<bar>INVALID</bar>
</config>
Config
package forum14765898;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Config {
public int bar;
}
Output
Below is output from running the demo code. It shows both the validation exception and on the last line we see that the XML file was successfully deleted as it no longer exists.
javax.xml.bind.UnmarshalException
- with linked exception:
[org.xml.sax.SAXParseException; systemId: file:/Users/bdoughan/Scratch/src/forum14765898/input.xml; lineNumber: 3; columnNumber: 23; cvc-datatype-valid.1.2.1: 'INVALID' is not a valid value for 'integer'.]
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.createUnmarshalException(AbstractUnmarshallerImpl.java:335)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.createUnmarshalException(UnmarshallerImpl.java:512)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:209)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:175)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:157)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:162)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:171)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:189)
at forum14765898.ConfigurationService.main(ConfigurationService.java:31)
Caused by: org.xml.sax.SAXParseException; systemId: file:/Users/bdoughan/Scratch/src/forum14765898/input.xml; lineNumber: 3; columnNumber: 23; cvc-datatype-valid.1.2.1: 'INVALID' is not a valid value for 'integer'.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:198)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:437)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:368)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:325)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator$XSIErrorReporter.reportError(XMLSchemaValidator.java:453)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.reportSchemaError(XMLSchemaValidator.java:3232)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.elementLocallyValidType(XMLSchemaValidator.java:3147)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.processElementContent(XMLSchemaValidator.java:3057)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleEndElement(XMLSchemaValidator.java:2135)
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.endElement(XMLSchemaValidator.java:854)
at com.sun.org.apache.xerces.internal.jaxp.validation.ValidatorHandlerImpl.endElement(ValidatorHandlerImpl.java:579)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.ValidatingUnmarshaller.endElement(ValidatingUnmarshaller.java:91)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.SAXConnector.endElement(SAXConnector.java:143)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.endElement(AbstractSAXParser.java:606)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanEndElement(XMLDocumentFragmentScannerImpl.java:1742)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2900)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:607)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:116)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:489)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:835)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:123)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1210)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:568)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:203)
... 6 more
false
public CashCountCompleted CashDeposit(String path) throws Exception {
// TODO Auto-generated method stub
CashCountCompleted cashCountCompleted = null;
File file = null;
FileInputStream inputStram = null;
try {
file = new File(path);
inputStram = new FileInputStream(file);
JAXBContext jaxbContext = JAXBContext.newInstance(CashCountCompleted.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
cashCountCompleted = (CashCountCompleted) jaxbUnmarshaller.unmarshal(inputStram);
}catch (JAXBException e) {
//throw new...
} catch (FileNotFoundException e) {
//throw new...
}finally{
try{
if(inputStram !=null){
inputStram.close();
}
}catch(Exception exception){
//throw new...
}
}
return cashCountCompleted;
}

NoClassDefFoundError in j2me

I have build a jar file and trying to use it in j2me application. I have included the jar in the build path and imported the required classes as well. But when I run my j2me application I am getting NoClassDefFound Error in the line where I am trying to instantiate the class which is present in the jar.
I can instantiate the classes of the jar in the java project but not in j2me.
Below is the error log:
WARNING - MMA -
C:/Builds/jme-sdk/javacall-javame-sdk-305/implementation/share/jsr135_mmapi/ju_mmconfig.c
line 801: caps: optional settings missing: SuspendBehavior
java.lang.NoClassDefFoundError: com/canvasm/ida/gps/LocationUpdater
- com.test.ida.HelloIDA.(HelloIDA.java:11)
- java.lang.Class.newInstance(), bci=0
- com.sun.midp.main.CldcMIDletLoader.newInstance(), bci=46
- com.sun.midp.midlet.MIDletStateHandler.createMIDlet(), bci=66
- com.sun.midp.midlet.MIDletStateHandler.createAndRegisterMIDlet(), bci=17
- com.sun.midp.midlet.MIDletStateHandler.startSuite(), bci=27
- com.sun.midp.main.AbstractMIDletSuiteLoader.startSuite(), bci=52
- com.sun.midp.main.CldcMIDletSuiteLoader.startSuite(), bci=8
- com.sun.midp.main.AbstractMIDletSuiteLoader.runMIDletSuite(), bci=161
- com.sun.midp.main.AppIsolateMIDletSuiteLoader.main(), bci=26 javacall_lifecycle_state_changed() lifecycle: event is
JAVACALL_LIFECYCLE_MIDLET_SHUTDOWN status is JAVACALL_OK
TestApp(j2me app):
import com.test.gps.LocationUpdater;
public class Hello extends MIDlet {
public Hello() {
LocationUpdater loc = new LocationUpdater();
System.out.println("Loc updater object :"+loc.toString());
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
protected void pauseApp() {
// TODO Auto-generated method stub
}
protected void startApp() throws MIDletStateChangeException {
}
}
JAR file main class:
public class LocationUpdater {
private boolean isUpdateSuccess = false;
public static void main(String[] args){
}
public boolean updateLocation(final String serverUrl, final String userMSISDN) throws LocationException{
AppConstants.url = serverUrl;
AppConstants.msisdn = userMSISDN;
LocationCanvas loc = new LocationCanvas();
isUpdateSuccess = loc.getLocation(serverUrl, userMSISDN);
return isUpdateSuccess;
}
}
LocationCanvas class:
public class LocationCanvas {
private Location location;
private LocationProvider locationProvider;
private Coordinates coordinates;
private Criteria criteria;
private Timer tm;
private double lat, lon;
private String posturl;
private boolean status,updateStatus;
public LocationCanvas() {
}
public boolean getLocation(String url, String msisdn) {
tm = new Timer();
criteria = new Criteria();
criteria.setHorizontalAccuracy(500);
try {
locationProvider = LocationProvider.getInstance(criteria);
if (locationProvider != null) {
tm.wait(4000);
try {
location = locationProvider.getLocation(2000);
} catch (Exception e) {
System.out.println(e.getMessage());
}
coordinates = (Coordinates)location.getQualifiedCoordinates();
if (coordinates != null) {
// Use coordinate information
lat = coordinates.getLatitude();
lon = coordinates.getLongitude();
System.out.println("Latitude :"+lat);
System.out.println("Longitude :"+lon);
}
posturl = url + "?IMEI=" + msisdn
+ "&positioningtype=" + "gps" + "&locationdata=" + lat
+ "," + lon;
}else{
//return false.. cos location provider is null
updateStatus = false;
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
return updateStatus;
}
error log:
Exception in thread "main" java.lang.NoClassDefFoundError:
javax/microedition/location/Coordinates
at com.canvasm.ida.gps.LocationUpdater.updateLocation(LocationUpdater.java:17)
at com.test.HelloTest.main(HelloTest.java:10)
Caused by: java.lang.ClassNotFoundException: javax.microedition.location.Coordinates
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
Any help would be appreciated.
It specifies that class file present at compile time is not found at run time.Check for build time and run time classpaths .
Finally able to solve the issue.
The problem was not in the code. It was due to the compilation issue.
First of all To solve the NoClassDefFoundError , I had to right click on the project and in the build path-> order and export -> check the jar that you have added.
Later while running I faced classFormatError 56.
The jar file which was created, was compiled using 1.6v.
And the j2me application was getting compiled with 1.3v.
I had to recompile my library project with 1.3v and create a jar out of it and used it in the j2me application.
Here is the link to guide: Build a Project from the Command Line - Java ME SDK

Resources