I'm busy writing a Program that Transmits GPS Coordinates to a Server from a mobile phone where the coordinates are then used for calculations. But I'm constantly hitting a wall with blackberry. I have built the Android App and it works great but can't seem to contact the server on a real blackberry device. I have tested the application in a simulator and it works perfectly but when I install it on a real phone I get no request the phone.
I have read quite a bit about the secret strings to append at the end of the url so I adapted some demo code to get me the first available transport but still nothing ...
The Application is Signed and I normally then either install it by debugging through eclipse or directly on the device from the .jad file and allow the application the required permissions.
The current code was adapted from the HTTP Connection Demo in the Blackberry SDK.
Could you have a look and give me some direction. I'm losing too much hair here ...
The Backend Service that keeps running:
public void run() {
System.out.println("Starting Loop");
Criteria cr = new Criteria();
cr.setHorizontalAccuracy(Criteria.NO_REQUIREMENT);
cr.setVerticalAccuracy(Criteria.NO_REQUIREMENT);
cr.setCostAllowed(false);
cr.setPreferredPowerConsumption(Criteria.NO_REQUIREMENT);
cr.setPreferredResponseTime(1000);
LocationProvider lp = null;
try {
lp = LocationProvider.getInstance(cr);
} catch (LocationException e) {
System.out.println("*****************Exception" + e);
}
if (lp == null) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert("GPS not supported!");
return;
}
});
} else {
System.out
.println(lp.getState() + "-" + LocationProvider.AVAILABLE);
switch (lp.getState()) {
case LocationProvider.AVAILABLE:
// System.out.println("Provider is AVAILABLE");
while (true) {
Location l = null;
int timeout = 120;
try {
l = lp.getLocation(timeout);
final Location fi = l;
System.out.println("Got a Coordinate "
+ l.getQualifiedCoordinates().getLatitude()
+ ", "
+ l.getQualifiedCoordinates().getLongitude());
System.out.println("http://" + Constants.website_base
+ "/apis/location?device_uid=" + Constants.uid
+ "&lat="
+ l.getQualifiedCoordinates().getLatitude()
+ "&lng="
+ l.getQualifiedCoordinates().getLongitude());
if (!_connectionThread.isStarted()) {
fetchPage("http://"
+ Constants.website_base
+ "/apis/location?device_uid="
+ Constants.uid
+ "&lat="
+ l.getQualifiedCoordinates().getLatitude()
+ "&lng="
+ l.getQualifiedCoordinates()
.getLongitude());
} else {
createNewFetch("http://"
+ Constants.website_base
+ "/apis/location?device_uid="
+ Constants.uid
+ "&lat="
+ l.getQualifiedCoordinates().getLatitude()
+ "&lng="
+ l.getQualifiedCoordinates()
.getLongitude());
}
Thread.sleep(1000 * 60);
} catch (LocationException e) {
System.out.println("Location timeout");
} catch (InterruptedException e) {
System.out.println("InterruptedException"
+ e.getMessage());
} catch (Exception ex) {
System.err.println(ex.getMessage());
ex.printStackTrace();
}
}
}
}
My Connection is Made with:
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc = connFact.getConnection(getUrl());
// Open the connection and extract the data.
try {
// StreamConnection s = null;
// s = (StreamConnection) Connector.open(getUrl());
HttpConnection httpConn = (HttpConnection) connDesc.getConnection();
/* Data is Read here with a Input Stream */
Any Ideas ?
Figured it out!
Using a function I found online to determine which ; extension to use when connecting by using numerous Try / Catch. Then had to set the Internet APN settings. I'm in South-Africa using Vodacom so the APN is "Internet" with no Password.
Barely have hair left ....
Related
I have been using Javamail (version 1.6.4) for a while now, mostly for event listening, mail parsing and copy/delete mails (from Exchnage using IMAPS). Lately i was asked to use sub-folders for a business usecase. When moving mail from the Inbox folder to a sub-folder the UID changes so i'm using folder.search() in order to find the new UID. This works most of the times but sometimes the search goes indefnitley (or its duration is very long) which may lag the entire application.
Is there a way to set a timeout (or other way to throw an exception if it runs too long) for folder.search()?
I understood that imap search is done on the server side but i just wanted to validate. this is an example of how i send search to the server (we can assume subject is unique for this discussion):
private static String findMailIdBySubject(String mailbox, String srcFolder, String subject) {
Folder srcFolderObj = null;
boolean wasConnectionEstablished = connectToMail(mailbox);
if (!wasConnectionEstablished) {
return null;
}
// get mailboxStore object
MailboxStore mailboxStore = MailBoxStoreList.getMailStoreByMailBox(mailbox);
try {
// Open inbox folder to get messages metadata
srcFolderObj = mailboxStore.getStore().getFolder(srcFolder);
srcFolderObj.open(Folder.READ_WRITE);
// create search Term
SearchTerm term = new SearchTerm() {
private static final long serialVersionUID = 7L;
#Override
public boolean match(Message message) {
try {
String mailSubject = message.getSubject();
if (mailSubject == null) {
mailSubject = "";
}
if (mailSubject.equals(subject)) {
return true;
}
} catch (MessagingException ex) {
log.error("Failed to search for mail with mailbox: " + mailbox + " in folder: " + srcFolder
+ " subject: " + subject + " Error: " + ExceptionUtils.getStackTrace(ex));
}
return false;
}
};
// search for the relevant message
Message[] messages = srcFolderObj.search(term);
UIDFolder uf = (UIDFolder) srcFolderObj;
return String.valueOf(uf.getUID(messages[0]));
} catch (Exception e) {
log.error("Subject: Failed to find id of mail in mailbox " + mailbox + " in folder " + srcFolder
+ " , Error: " + ExceptionUtils.getStackTrace(e));
return null;
} finally {
try {
if (srcFolderObj != null && srcFolderObj.isOpen()) {
srcFolderObj.close();
}
} catch (Exception e) {
}
}
}
i also tried to replace SearchTerm override with the following but performance was the same:
SearchTerm searchTerm = new SubjectTerm(subject);
Thanks in advance!
I know there are tons of posts about stack overflow errors and i understand why my specific one is happening, my question is basically how to move away from recursion in this specific case. I have a class which establishes and maintains a client connection (for HL7 messaging specifically but it's essentially a glorified client connection) to another system which hosts corresponding server connections. This class' constructor starts a new thread and runs the following method :
#Override
public void connect()
{
try
{
setStatus("Connecting");
connection = context.newClient(intfc.getIp(), port, false);
connected = true;
setStatus("Connected");
logEntryService.logInfo(LogEntry.CONNECTIVITY, "Successfully connected " + connectionType + " client connection to "
+ intfc.getName() + "(" + intfc.getIp() + ") on port " + port);
monitor();
}
catch (HL7Exception ex)
{
connected = false;
setStatus("Disconnected");
try
{
TimeUnit.SECONDS.sleep(connectionRetryIntervalInSeconds);
connect();
}
catch (InterruptedException ex2)
{}
}
}
Upon successfully connecting with the server, the monitor method simply checks, in yet another thread, if the connection is still up at a given interval. If it goes down, the monitoring thread is interrupted and the connect() method is called again.
I did not anticipate this at first but you can quickly see why the connect() method is causing stack overflow errors after several days running. I'm struggling to think of a way to get the same functionality to work without the connect method calling itself again every time the connection fails.
Any suggestions would be appreciated.
Thanks!
Typically you'd use a Stack object to emulate recursion when required.
However, in your case, why are you using recursion at all? A while loop fits the purpose.
while(true /**or some relevant condition**/){
try{ //try to connect
....
catch(HL7Exception ex){
//sleep
}
}
I'm not sure of the purpose of your application, but there are may be better methods than sleeping. You could use a ScheduledExecutorService, but if it's a single threaded program with one purpose it's probably unnecessary.
When I had to deal with this issue in c# I used a Stack, and added new classes to it, instead of using recursion. Then a second loop would check to see if there were any objects in the stack that needed dealing with. That avoided stack overflow when I would have had huge amounts of recursion otherwise. Is there a similar Stack collection in Java?
Why are you calling the monitor() method in the first place? You mention that it is launched in a separate thread, then can't you just launch it in a new thread when the application comes up? Then there won't be a recursive call.
I changed my code to an iterative approach as suggested, works beautifully!
#Override
public void initThread()
{
initConnectionEntity();
mainThread = new Thread()
{
#Override
public void run()
{
while (running)
{
if (!connected)
{
try
{
connect();
}
catch (HL7Exception ex)
{
connected = false;
setStatus("Disconnected");
try
{
TimeUnit.SECONDS.sleep(connectionRetryIntervalInSeconds);
}
catch (InterruptedException ex2)
{}
}
}
try
{
TimeUnit.MILLISECONDS.sleep(500);
}
catch (InterruptedException ex2)
{}
}
}
};
mainThread.setName(intfc.getName() + " " + connectionType + " Main Thread");
mainThread.start();
}
#Override
public void connect() throws HL7Exception
{
setStatus("Connecting");
connection = context.newClient(intfc.getIp(), port, false);
connected = true;
setStatus("Connected");
logEntryService.logInfo(LogEntry.CONNECTIVITY, "Successfully connected " + connectionType + " client connection to "
+ intfc.getName() + "(" + intfc.getIp() + ") on port " + port);
monitor();
}
private void monitor()
{
monitoringThread = new Thread()
{
#Override
public void run()
{
try
{
while (running)
{
if (!connection.isOpen())
{
if (connected == true)
{
logEntryService.logWarning(LogEntry.CONNECTIVITY, "Lost " + connectionType + " connection to "
+ intfc.getName() + "(" + intfc.getIp() + ") on port " + port);
}
connected = false;
setStatus("Disconnected");
monitoringThread.interrupt();
}
else
{
connected = true;
}
TimeUnit.SECONDS.sleep(connectionMonitorIntervalInSeconds);
}
}
catch (InterruptedException ex)
{
logEntryService.logDebug(LogEntry.CONNECTIVITY, "Monitoring thread for " + connectionType
+ " connection to " + intfc.getName() + " interrupted");
}
}
};
monitoringThread.setName(intfc.getName() + " " + connectionType + " Monitoring Thread");
monitoringThread.start();
}
we were wanting to build a functionality where if a user is connected to a WiFi network, we can display the details of other devices connected to the same WiFi. How do we go about it?
Right now, we are able to achieve it by:
pinging all the IP addresses on the current network(looping from 1-255) - this is the most time consuming step (code snippet below)
for the IP addresses that responded, fetching their MAC addresses and finally
fetching the manufacturer for the MAC addresses using an external API
we have success in this but the issue is that it takes way too long - around 4-5 minutes to do this. I have a feeling that someone can point us towards a better, faster solution.
There was a similar question(although it was about iOS) but didn't find any answer, hence posting this again. Please pardon if that was against the rules. Any help in this would be highly appreciated.
Here's the snippet of code which is taking too long to give the results back(step 1)
for (int i = 0; i < 255; i++) {
String host = "";
try {
String subnet = "192.168.2";
host = subnet + "." + i;
Process exec = Runtime.getRuntime().exec(String.format(CMD, host));
int i1 = exec.waitFor();
if (i1 == 0) {
InetAddress a = InetAddress.getByName(host);
Log.i("TAG", "run: " + a.getHostAddress());
} else {
throw new IOException("Unable to get ping from runtime");
}
} catch (IOException | InterruptedException e) {
try {
InetAddress a = InetAddress.getByName(host);
if (a.isReachable(200)) {
Log.i("TAG", "run: " + a.getHostAddress());
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
I've been searching for a solution for this problem for 2 days now..
I have an android chat application that I want to implement sending files into it.
Here's the sending code:
public void sendFile(Uri uri) {
FileTransferManager fileTransferManager = FileTransferManager.getInstanceFor(app.getConnection());
OutgoingFileTransfer fileTransfer = fileTransferManager.createOutgoingFileTransfer(userId + "/Spark");
try {
fileTransfer.sendFile(new File(uri.getPath()), "this is the description");
System.out.println("status is:" + fileTransfer.getStatus());
System.out.println("sent .. just");
while (!fileTransfer.isDone()) {
if (fileTransfer.getStatus() == FileTransfer.Status.refused) {
Toast.makeText(getActivity(), "File refused.", Toast.LENGTH_SHORT).show();
return;
}
if (fileTransfer.getStatus() == FileTransfer.Status.error) {
Toast.makeText(getActivity(), "Error occured.", Toast.LENGTH_SHORT).show();
return;
}
}
System.out.println(fileTransfer.getFileName() + "has been successfully transferred.");
System.out.println("The Transfer is " + fileTransfer.isDone());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
I know this code works fine as I sent file from android to spark and received it successfully.. The problem is in receiving that file in android.. Here's the code:
ProviderManager.addIQProvider("si", "http://jabber.org/protocol/si",
new StreamInitiationProvider());
ProviderManager.addIQProvider("query", "http://jabber.org/protocol/bytestreams",
new BytestreamsProvider());
ProviderManager.addIQProvider("open", "http://jabber.org/protocol/ibb",
new OpenIQProvider());
ProviderManager.addIQProvider("close", "http://jabber.org/protocol/ibb",
new CloseIQProvider());
ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(connection);
sdm.addFeature("http://jabber.org/protocol/disco#info");
sdm.addFeature("jabber:iq:privacy");
final FileTransferManager manager = FileTransferManager.getInstanceFor(connection);
manager.addFileTransferListener(new FileTransferListener() {
public void fileTransferRequest(FileTransferRequest request) {
IncomingFileTransfer transfer = request.accept();
try {
File file = new File(Environment.getExternalStorageDirectory() + "/" + request.getFileName());
Log.i("Tawasol", "File Name: " + request.getFileName());
transfer.recieveFile(file);
while (!transfer.isDone() || (transfer.getProgress() < 1)) {
Thread.sleep(1000);
Log.i("Tawasol", "still receiving : " + (transfer.getProgress()) + " status " + transfer.getStatus());
if (transfer.getStatus().equals(org.jivesoftware.smackx.filetransfer.FileTransfer.Status.error)) {
// Log.i("Error file",
// transfer.getError().getMessage());
Log.i("Tawasol",
"cancelling still receiving : "
+ (transfer.getProgress())
+ " status "
+ transfer.getStatus() + ": " + transfer.getException().toString());
transfer.cancel();
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
still receiving : 0.0 status Negotiating Stream
I get this log for about 5 seconds the I get that:
cancelling still receiving : 0.0 status Error: org.jivesoftware.smack.SmackException: Error in execution
I think that the problem is in the openfire server that I'm using.. I've openfire 3.9.3 server installed on my windows 7 64bit.. In the Smack logs I noticed this one:
<iq id="L87BF-73" to="59xrd#rightsho/Smack" type="set" from="h97qa#rightsho/Spark"><query xmlns="http://jabber.org/protocol/bytestreams" sid="jsi_4840101552711519219" mode="tcp"><streamhost jid="proxy.rightsho" host="192.168.56.1" port="7777"/></query></iq>
The host here is 192.168.56.1 which I think is local ip so that I can't access it from android.. So I wan't to use the IP of the pc to transfer files..
Excuse me for my lack of knowledge in this field.
From my little knowledge of smack the issue may be in this piece of code:
while (!transfer.isDone() || (transfer.getProgress() < 1)) {
Thread.sleep(1000);
Log.i("Tawasol", "still receiving : " + (transfer.getProgress()) + " status " + transfer.getStatus());
if (transfer.getStatus().equals(org.jivesoftware.smackx.filetransfer.FileTransfer.Status.error)) {
// Log.i("Error file",
// transfer.getError().getMessage());
Log.i("Tawasol",
"cancelling still receiving : "
+ (transfer.getProgress())
+ " status "
+ transfer.getStatus() + ": " + transfer.getException().toString());
transfer.cancel();
break;
}
}
If you move the monitoring while loop to another thread, suddenly this error goes away. I'm not sure why, but it has worked for me and my friends in the past.
I am a newbie in Java but I need to make a scanner (that has a built in ocr) output some content to a browser. I haven't gotten to the browser yet, but the code works when I run it as an application.
With the scanner, I received Java code that makes the scanner take a picture, then read from it and output it back to the console. I added a few lines to make it an applet:
import gx.*;
import pr.*;
import java.applet.*;
public class DocScan extends Applet
{
/**
*
*/
private static final long serialVersionUID = 1L;
static
{
try
{
System.loadLibrary("jgx");
System.loadLibrary("jpr");
}
catch (UnsatisfiedLinkError e)
{
System.err.println("Native code library failed to load." + e);
System.exit(1);
}
}
public static void main(String argv[])
{
Lib lib = new Lib();
String text;
String[] ec ={ "Ok", "Warning", "Error" };
try
{
/* Opening the PR system */
lib.FunctionStart("Opening system files");
PassportReader pr = new PassportReader(); /* Object for the PR system */
lib.FunctionEnd();
/* Validity check */
if (!pr.IsValid())
{
lib.Error("Failed to initialize!");
lib.PrintStat();
}
/* Connecting to the first device */
lib.FunctionStart("Connecting to the first device");
pr.UseDevice(0, jpr.PR_UMODE_FULL_CONTROL);
lib.FunctionEnd();
/* Using the device */
while (!lib.KbHit())
{
lib.ProcessStart("Processing document");
try
{
/* Capturing images */
lib.FunctionStart("Capturing images");
pr.Capture();
lib.FunctionEnd();
/* Getting document data */
lib.FunctionStart("Recognizing.");
prDoc doc = pr.Recognize(0);
lib.FunctionEnd();
if (!doc.IsValid()) lib.WriteLine("No data found.");
else
{
/* Displaying document type */
lib.WriteLine("Document type: " + doc.Code() + ", status: " + ec[doc.Status() / 100]);
/* Get some fixed fields and displaying them */
text = doc.Field(jpr.PR_DF_NAME);
if (!text.equals("")) lib.WriteLine("NAME \"" + text + "\" [" + ec[doc.FieldStatus(jpr.PR_DF_NAME) / 100] + "]");
text = doc.Field(jpr.PR_DF_DOCUMENT_NUMBER);
if (!text.equals("")) lib.WriteLine("DOCUMENT NUMBER \"" + text + "\" [" + ec[doc.FieldStatus(jpr.PR_DF_DOCUMENT_NUMBER) / 100] + "]");
text = doc.Field(jpr.PR_DF_EXPIRY_DATE);
if (!text.equals("")) lib.WriteLine("EXPIRY DATE \"" + text + "\" [" + ec[doc.FieldStatus(jpr.PR_DF_EXPIRY_DATE) / 100] + "]");
/* Searching for fields and displaying them */
gxVariant pdoc = doc.ToVariant();
gxVariant fieldlist = new gxVariant();
pdoc.GetChild(fieldlist, jgx.GX_VARIANT_BY_ID, jpr.PRV_FIELDLIST, 0);
int nitems = fieldlist.GetNItems();
for (int i = 0; i < nitems; i++)
{
gxVariant field = new gxVariant();
fieldlist.GetItem(field, jgx.GX_VARIANT_BY_INDEX, 0, i);
int field_code = field.GetInt();
text = doc.Field(field_code);
if (!text.equals("")) lib.WriteLine("[" + field_code + "] \"" + text + "\" [" + ec[doc.FieldStatus(field_code) / 100] + "]");
if (field_code >= jpr.PR_DF_FORMATTED) continue;
try
{
gxImage img = doc.FieldImage(field_code);
if (img.IsValid()) img.Save(field_code + ".jpg", jgx.GX_JPEG);
}
catch (RuntimeException e)
{
lib.DisplExcp(e);
}
}
}
}
catch (RuntimeException e)
{
lib.DisplExcp(e);
}
lib.ProcessEnd();
lib.WaitForSec(3);
}
/* Closing the device */
lib.FunctionStart("Closing the device");
pr.CloseDevice();
lib.FunctionEnd();
}
catch (RuntimeException e)
{
lib.DisplExcp(e);
}
lib.PrintStat();
}
}
I am using Eclipse as an IDE. Right now my goal is to simply make the scanner "flash". I know that the output is to the console and I will not see anything from it in an applet, but it should still flash.
When I run this code as an application, it works. The scanner takes a picture and then it outputs what it has read to the console.
When I run this code as an Applet, the applet starts and does nothing. It just stays there with no errors of any kind (at least that's what Eclipse is showing me).
I read that I should allow the applet accesss, so I edited:
c:\program files\java\jre8\lib\security\java.policy
and added this at the end:
grant {
permission java.security.AllPermission;
};
Which should allow applets full access. However, there is no change - the applet still launches and does nothing.
Can anyone point me in the right direction? Why is the code not working when I run it as an applet?