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?
Related
I'm looking for a way that my application can call the user's standard mail application (e.g. Outlook, Thunderbird, etc.). And give it an recipient address, the email text and an attachment.
So, basically the standard email application should pop up have the email ready for me (with recipient, text and attachment) and all that is left to do for me is pressing "send" in my outlook, thunderbird etc.
I've been googling for a while now, but I couldn't find a real solution.
I've been looking into mapi a bit but it seems like 1. it's deprecated and 2. it's mainly built for outlook.
Any help/suggestions/solutions greatly appreciated!
Edit: I have seen the question Start Mail-Client with Attachment but no working answer was provided there and also the question is more than 3 years old.
Edit: Other languages would be ok, too. Has to work on Windows XP, Vista, 7, 8 (both 32 and 64 bit)
UPDATE: It seems to be more difficult than I have thought it to be.
I've been looking into JMAPI, which apparently only works for 32bit Systems.
I've also seen the solutions on codeproject.org (here and here), but I somehow couldn't get them to work.
Now I'm trying to do it with command line:
1. Read user's default mail client
2. Call a batch file according to the email client. (Yes you have to write a batch file for every common mail client.
Example for outlook:
"outlook.exe" /a "F:\test.png" /m "test.test#test.test&cc=test#test.test&subject=subject123&body=Hello, how are you%%3F%%0D%%0Anew line"
--> see my provided answer for futher info on that method
So...
After days of research I gave up to get a general solution.
I came up with a solution working at least for the two most common clients (Thunderbird & Outlook)
My solution is basically calling the application from command line.
For those interested, here is my solution: (I haven't tested it cross platform - works on my old XP laptop though)
import java.io.IOException;
/*
:: Punctuation Hexadecimal equivalent
:: ----------------------------------------------
:: Space ( ) %20
:: Comma (,) %2C
:: Question mark (?) %3F
:: Period (.) %2E
:: Exclamation point (!) %21
:: Colon (:) %3A
:: Semicolon (;) %3B
:: Line feed %0A --> New line %0D%0A
:: Line break (ENTER key) %0D --> New line %0D%0A
*/
public class Main {
static String test = "hi";
private static String attachment;
private static String to;
private static String cc;
private static String subject;
private static String body;
public static void main (String[] args){
attachment = "F:\\pietquest.png";
to = "test#test.de";
cc = "a.b#c.de";
subject = "TestSubject 123";
body = "Hi, what\'s going on%0D%0Anew line";
body = replace(body);
subject = replace(subject);
String[] value = WindowsRegistry.readRegistry("HKEY_LOCAL_MACHINE\\SOFTWARE\\Clients\\Mail", "");
if (value[10].contains("Thunderbird")){
System.out.println("Thunderbird");
String[] pfad = WindowsRegistry.readRegistry("HKEY_LOCAL_MACHINE\\SOFTWARE\\Clients\\Mail\\Mozilla Thunderbird\\shell\\open\\command", "");
String Pfad = pfad[10] + " " + pfad[11];
String argument = Pfad + " /compose \"to=" + to + ",cc=" + cc + ",subject=" + subject + ",body=" + body + ",attachment=" + attachment + "\"";
// System.out.println(argument);
try {
Runtime.getRuntime().exec(argument);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else if (value[10].contains("Outlook")){
System.out.println("Outlook");
String[] pfad = WindowsRegistry.readRegistry(
"HKEY_LOCAL_MACHINE\\SOFTWARE\\Clients\\Mail\\Microsoft Outlook\\shell\\open\\command", "");
String Pfad = pfad[10];
String argument = Pfad + " /a " + attachment + " /m \"" + to
+ "&cc=" + cc + "&subject=" + subject + "&body=" + body + "\"";
// System.out.println(argument);
try {
Runtime.getRuntime().exec(argument);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static String replace(String toReplace){
toReplace = toReplace.replace(" ", "%20");
toReplace = toReplace.replace(",", "%2C");
toReplace = toReplace.replace("?", "%3F");
toReplace = toReplace.replace(".", "%2E");
toReplace = toReplace.replace("!", "%21");
toReplace = toReplace.replace(":", "%3A");
toReplace = toReplace.replace(";", "%3B");
return toReplace;
}
}
and this is the Windows Registry Class: (got that from here)
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
public class WindowsRegistry {
/**
*
* #param location path in the registry
* #param key registry key
* #return registry value or null if not found
*/
public static final String[] readRegistry(String location, String key){
try {
// Run reg query, then read output with StreamReader (internal class)
Process process = Runtime.getRuntime().exec("reg query " +
'"'+ location);
StreamReader reader = new StreamReader(process.getInputStream());
reader.start();
process.waitFor();
reader.join();
// Parse out the value
String[] parsed = reader.getResult().split("\\s+");
if (parsed.length > 1) {
return parsed;
}
} catch (Exception e) {}
return null;
}
static class StreamReader extends Thread {
private InputStream is;
private StringWriter sw= new StringWriter();
public StreamReader(InputStream is) {
this.is = is;
}
public void run() {
try {
int c;
while ((c = is.read()) != -1)
sw.write(c);
} catch (IOException e) {
}
}
public String getResult() {
return sw.toString();
}
}
you can use C#: Example C# or java: Example Java
EDIT
You can use Boost for ssl and send email via smtp
I was writing a java tool that toggles wether a game mod is active (specifically, the game is Dwarf Fortress, and the mod is DFHack) and the program is nearly done. However, I cant seem to get the variables right that tell the program how to check if the mod is active or not.
I got this status file containing a single character, being 1 for active and 0 for inactive.
This is the code (By the way, if it is needed: I checked the name of the file and it matches the class declaration).
package nl.dirkkok.dfhacktoggle;
/*
* DFHacktoggle
* 28-12-2013 # 2:02 PM
*
* This program will disable DFHack if it is enabled, and enable it if it is disabled.
*
* Using this tool is at your own risk. If you send me an email complaining about this program doing anything you dont want, then I will laugh at you, and tell you that you cant read. :)
*
* Created by Dirk Kok <d.kok.2000#gmail.com>. This tool is my property, but I do not claim rights of neither Dwarf Fortress nor DFHack.
*/
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.IOException;
import java.nio.file.NoSuchFileException;
public class Dfhacktoggle {
private static Path statusfile = "dfhack-status";
private boolean dfhack = false;
private byte[] fileArray = new byte[1];
private byte[] active = new byte[1];
private byte[] inactive = new byte[1];
private file dfhacksdl = "SDLdfhack.dll";
private file vanillasdl = "SDLreal.dll";
private file sdl = "SDL.dll";
active[] <byte> = 1;
inactive[] <byte> = 0;
public static void main(String[] args) {
try {
fileArray = Files.readAllBytes(file);
if (fileArray[0] == 1) {
p("DFHack is active. Deactivating...");
try {
if (vanillasdl.exists()) throw new java.io.IOException("File exists");
sdl.renameTo(dfhacksdl);
vanillasdl.renameTo(sdl);
Files.write(statusfile, inactive, WRITE);
} catch (IOException x) {
errp("DFHack could not be deactivated. Reinstalling the program will solve this.");
errp("Detailed info:");
errp("IOException: " + x);
} catch (NoSuchFileException x) {
errp("Status file could not be found. Reinstalling the program will solve this.");
errp("Detailed info:");
errp("NoSuchFileException: " + x);
}
} else if (fileArray[0] == 0) {
p("DFHack is inactive. Activating...");
try {
if(vanillasdl.exists()) throw new java.io.IOException("File exists");
sdl.renameTo(vanillasdl);
dfhacksdl.renameTo(sdl);
Files.write(statusfile, active, WRITE);
} catch (IOException x) {
errp("Status could not be checked. Reinstalling the program will solve this.");
errp("Detailed info:");
errp("IOException: " + x);
} catch (NoSuchFileException x) {
errp("Status file could not be found. Reinstalling the program will solve this.");
errp("Detailed info:");
errp("NoSuchFileException: " + x);
}
} else {
errp("DFHack's status could not be checked. Reinstalling the program will solve this.");
}
} catch (IOException x) {
errp("Status could not be checked. Reinstalling the program will solve this.");
errp("Detailed info:");
errp(x);
}
}
public void p(String txt) {
System.out.println(txt);
}
public void errp(String txt) {
System.err.println(txt);
}
}
The compiler returns this:
F:\Dfhack-swap>javac Dfhacktoggle.java
Dfhacktoggle:29: error: <identifier> expected
active[] <byte> = 1;
^
Dfhacktoggle:30: error: <identifier> expected
inactive[] <byte> = 0;
^
Your syntax is wrong there's no active[] <byte> = 1; in Java
If you want to assign it a value You can do it in this way
active[0] = 1;
inactive[0] = 0;
But there's no need for array to use it as a boolean you can just define it as a byte
byte active= 1;
byte inactive= 0;
I am trying to achieve the automatic update for my java web-start applicaiton. Logic: I am fetching the jnlp file from the server and comparing the timestamp with the current one. if there is difference then download the latest file and restart the application with javaws command. Now I have two problems.
1. I am not able to fetch the local jnlp file (because the location for jnlp file is different for different operating system as mentioned here
2. I am not able to find a graceful way to restart the application after killing the current running application. I would appreciate if there is any other graceful solution available. Thanks
My code:
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import javax.swing.JOptionPane;
import org.apache.log4j.Logger;
import com.ibm.nzna.projects.qit.app.PropertySystem;
/**
* QitUpdater . java
*
* #Info Checks for updates for the JWS Application
*
* This program will try to use a given URL to connect online to check for
* a newer version of the jnlpFile. The program then compares the last
* modified dates of the local copy and the URL copy, and notifies the
* user if the URL copy is newer, via a Dialog box popup. The newer
* version can then, be downloaded and installed using JWS.
*
* #Warnings If the server containing QIT changes its directory or location then
* the program will error out every time since the URL link is
* hard-coded.
*
* #author Ashish Tyagi
* #version 4/22/2013
*
*/
public abstract class QitUpdater {
// constant which hold the location of property file and server location
public final static String jnlpFile = PropertySystem.getString(PropertySystem.PROPERTY_JNLP_FILE);
public final static String fileDirectoryURL = PropertySystem.getString(PropertySystem.PROPERTY_JNLP_SERVER);
static Logger logger = Logger.getLogger(QitUpdater.class.getName());
// private variables
private static HttpURLConnection huc;
private static File oldFile = null;
private static long localDate = 0;
private static long remoteDate = 0;
public static void checkUpdates(boolean displayErrors,boolean displayIsUpToDate,boolean autoRunner){
logger.info("value of jnlp file: "+fileDirectoryURL+"/"+jnlpFile);
if(jnlpFile !=null && fileDirectoryURL != null)
checkForUpdates(displayErrors, displayIsUpToDate, autoRunner);
}
/**
* Starts a new task to check for QIT updates.
*
* If there is no connection or the program is up to date, then this method
* returns normally. Otherwise, it will exit the old program and execute the
* newer QIT program.
*
* #param displayErrors
* will show all error messages in popups, if any occur. This is
* recommended to be false on boostrapping, so the 'offline user'
* is not annoyed.
*
* #param displayIsUpToDate
* will show a popup letting the user know if their current
* version of QIT is up to date, if they have the most up to date
* version. Otherwise, it will ignore the popup.
*
* #param autoRunNewer
* will automatically execute the newer JNLP file, if it is found
* or downloaded. This is recommended to be false if this method
* is being called from within a user action, like a button
* press. If it is set to false, a dialog will ask the user to
* restart QIT in order to finish updating the program, if an
* update was found.
*/
public static void checkForUpdates(boolean displayErrors,
boolean displayIsUpToDate, boolean autoRunNewer) {
// Try to find a similarly named file
// in the current local directory
oldFile = new File(jnlpFile);
if (oldFile.exists()) // find the JNLP file
{
// grab the local last modified date to compare
localDate = oldFile.lastModified();
}
// Try to access the base URL
int code = 404;
try {
URL u = new URL(fileDirectoryURL);
huc = (HttpURLConnection) u.openConnection();
huc.setRequestMethod("GET");
huc.connect();
code = huc.getResponseCode();
} catch (MalformedURLException e) {
if (displayErrors)
printError("Error: Could not check for updates.\nMalformedURLException: "
+ e.getMessage()
+ "\n\nClick OK to continue using QIT.");
return;
} catch (IOException e) {
if (displayErrors)
printError("Error: Could not check for updates.\nIOException: "
+ e.getMessage()
+ "\n\nClick OK to continue using QIT.");
return;
}
if (code == 200) {
// 200 is a valid connection
// scan URL for versions
try {
StringBuilder sb = new StringBuilder();
sb.append(fileDirectoryURL).append("/").append(jnlpFile);
URL u = new URL(sb.toString());
huc = (HttpURLConnection) u.openConnection();
huc.setRequestMethod("GET");
huc.connect();
// grab the last modified date
remoteDate = huc.getLastModified();
} catch (MalformedURLException e) {
if (displayErrors)
printError("Error: Failed to download.\n\n"
+ e.getMessage()
+ "\n\nClick OK to continue using QIT.");
return;
} catch (IOException e) {
if (displayErrors)
printError("Error: Failed to download.\n\n"
+ e.getMessage()
+ "\n\nClick OK to continue using QIT.");
return;
}
// compare last modified dates of JNLP files
if (remoteDate != localDate) {
// found a newer version of JNLP
// ask to download
if (0 == printQuestion("An updated version of QIT is available.\n\nLast updated:\n"
+ new Date(remoteDate).toString()
+ "\n\nDo you want to download and install it?")) {
// download and install
try {
downloadUrlFile(jnlpFile, fileDirectoryURL + "/"
+ jnlpFile);
oldFile.setLastModified(remoteDate);
// set the date to the date on the server
if (autoRunNewer) {
// run the JNLP file
try {
Runtime.getRuntime()
.exec("javaws "+jnlpFile);
System.exit(0);// quit this version of QIT
} catch (IOException e) {
if (displayErrors)
printError("Error:\n"
+ e.getMessage()
+ "\n\nClick OK to continue using QIT.");
}
} else
printInfo("In order to finish installing the\nupdate, QIT needs to be restarted.");
} catch (Exception e) {
if (displayErrors)
printError("Error: Failed to download " + jnlpFile
+ ".\n\n" + e.getMessage()
+ "\n\nClick OK to continue using QIT.");
}
}
} else {
// modified dates are the same
// try to launch the current JNLP
if(oldFile.exists())
{
// run the JNLP file
try {
Runtime.getRuntime()
.exec("javaws "+jnlpFile);
System.exit(0);// quit this version of QIT
} catch (IOException e) {
if (displayErrors)
printError("Error:\n"
+ e.getMessage()
+ "\n\nClick OK to continue using QIT.");
}
}
// up to date
if (displayIsUpToDate)
printInfo("QIT is up to date.\n\nLast update was:\n"
+ (new Date(localDate).toString())
+ "\n\nClick OK to continue.");
}
}
return;
}
/**
* Downloads the urlString to the filename at the current directory.
*
* #param filename
* #param urlString
* #throws MalformedURLException
* #throws IOException
*/
public static void downloadUrlFile(String filename, String urlString)
throws MalformedURLException, IOException {
BufferedInputStream in = null;
FileOutputStream fout = null;
try {
URL url = new URL(urlString);
huc = (HttpURLConnection) url.openConnection();
in = new BufferedInputStream(url.openStream());
fout = new FileOutputStream(filename);
byte data[] = new byte[1024];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fout.write(data, 0, count);
}
} finally {
if (in != null)
in.close();
if (fout != null)
fout.close();
}
}
/**
* Display an error
*
* #param e
*/
private static void printError(String e) {
JOptionPane.showMessageDialog(null, e, "Error",
JOptionPane.ERROR_MESSAGE);
}
/**
* Display some information
*
* #param s
*/
private static void printInfo(String s) {
JOptionPane.showMessageDialog(null, s, "Information",
JOptionPane.INFORMATION_MESSAGE);
}
/**
* Prompt a Yes/No Question
*
* #param String
* q
* #return int 0 means YES, 1 means NO, -1 means they clicked "X" close
*/
private static int printQuestion(String q) {
return JOptionPane.showConfirmDialog(null, q, "Question",
JOptionPane.YES_NO_OPTION);
}
}
I am trying to achieve the automatic update for my java web-start application
Use the DownloadService of the JNLP API.
DownloadService service allows an application to control how its own resources are cached, to determine which of its resources are currently cached, to force resources to be cached, and to remove resources from the cache. The JNLP Client is responsible for providing a specific implementation of this service.
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 ....
The Java application that I support is logging some details in a flat file. the problem I face some times is that, the entry is very low compared to the previous day. This entry is most essential because our reports are generated based on the file. I went thro code for writing I couldn't figure out any issues. the method which is writing is sync method.
Any suggestions? I can also provide the code for you is you may need?
public synchronized void log (String connID, String hotline, String callerType,
String cli, String lastMenu, String lastInput,
String status, String reason)
{
//String absoluteFP = LOG_LOC + ls + this.getFilename();
//PrintWriter pw = this.getPrintWriter(absoluteFP, true, true);
try
{
pw.print (this.getDateTime ()+ ","+connID +","+hotline+","+callerType+","+ cli+"," + lastMenu + "," + lastInput + "," + status + "," + reason);
//end 1006
pw.print (ls);
pw.flush ();
//pw.close();
}
catch (Exception e)
{
e.printStackTrace ();
return;
}
}
private synchronized PrintWriter getPrintWriter (String absoluteFileName,
boolean append, boolean autoFlush)
{
try
{
//set absolute filepath
File folder = new File (absoluteFileName).getParentFile ();//2009-01-23
File f = new File (absoluteFileName);
if (!folder.exists ())//2009-01-23
{
//System.out.println ("Call Detailed Record folder NOT FOUND! Creating a new);
folder.mkdirs ();
//System.out.println ("Configure log folder");
this.setHiddenFile (LOG_LOC);//set tmp directory to hidden folder
if (!f.exists ())
{
//System.out.println ("Creating a new Call Detailed Record...");//2009-01-23
f.createNewFile ();//2009-01-23
}
}
else
{
if (!f.exists ())
{
//System.out.println ("Creating a new Call Detailed Record...");//2009-01-23
f.createNewFile ();//2009-01-23
}
}
FileOutputStream tempFOS = new FileOutputStream (absoluteFileName, append);
if (tempFOS != null)
{
return new PrintWriter (tempFOS, autoFlush);
}
else
{
return null;
}
}
catch (Exception ex)
{
ex.printStackTrace ();
return null;
}
}
/**
* Set the given absolute file path as a hidden file.
* #param absoluteFile String
*/
private void setHiddenFile (String absoluteFile)
{
//set hidden file
//2009-01-22, KC
Runtime rt = Runtime.getRuntime ();
absoluteFile = absoluteFile.substring (0, absoluteFile.length () - 1);//2009-01-23
try
{
System.out.println (rt.exec ("attrib +H " + "\"" + absoluteFile + "\"").getInputStream ().toString ());
}
catch (IOException e)
{
e.printStackTrace ();
}
}
private String getDateTime ()
{
//2011-076-09, KC-format up to milliseconds to prevent duplicate PK in CDR table.
//return DateUtils.now ("yyyy/MM/dd HH:mm:ss");
return DateUtils.now ("yyyy/MM/dd HH:mm:ss:SSS");
//end 0609
}
private String getFilename ()
{
///return "CDR_" + port + ".dat";//2010-10-01
return port + ".dat";//2010-10-01
}
public void closePW ()
{
if (pw != null)
{
pw.close ();
}
}
You've created a FileOutputStream, but aren't closing that stream. Close that stream and try again. That might be causing the problem.
Messages are getting logged sometime because the garbage collector kicks in at some intervals and closes the FileOutStream. This then allows messages to be logged again. You're getting the unreachable error since you have a return statement in both the if & else blocks. You'll have to take the PrintWriter and FileOutStreamWriter out of the getPrintWriter put it where you usually call the getPrintWriter(). Then you'll be able to close the streams correctly. getPrintWriter should only ensure file exists, so rename it to ensureFileExistance
If you can use Apache Common IO, try this:
public synchronized void log(String connID, String hotline, String callerType,
String cli, String lastMenu, String lastInput,
String status, String reason) {
String absoluteFP = LOG_LOC + ls + this.getFilename();
File file = new File(absoluteFP);
String message = this.getDateTime() + "," + connID + "," + hotline + "," + callerType + "," + cli + "," + lastMenu + "," + lastInput + "," + status + "," + reason;
try {
// note that you must explicitly add new line character if you want the line to end with newline
FileUtils.write(file, message + "\n", "UTF-8", true);
} catch (IOException ex) {
ex.printStackTrace ();
}
}
In Common IO 2.1, you can append a file that you are writting to. You can now get rid of the closePW and getPrintwriter and since the log method is synchronized, the file can be written one at a time from the same object. However, if you try to write the same file from different object at the same time, you will end up having overwritting problem.
Also, Common IO create the missing parent folder for you automatically. There is no need to explicitly check and create the folder.