I have a Jframe form class like this
public class LoginForm extends javax.swing.JFrame
In this,i get username & password from user and then send it to php server for validation and
will get the response as OK or Invalid User. I have another class named 'public class LoginTimer implements Runnable' . In this class i have some code to execute. I want that in 'LoginForm' when i got response as OK, the control will move to second class 'LoginTimer' means second class will be
called. please tell me how to do it??
=====================================================================
private void sendGet(String username,String pwd) throws Exception
{
String url = "http://localhost/login.php?username="+username+ "&password="+pwd;
final String USER_AGENT = "Mozilla/5.0";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null)
{
response.append(inputLine);
}
in.close();
//print result
String r=response.toString();
System.out.println("String "+r);
if(r.equals("OK"))
{
System.out.println("you are a valid user");
}
else
{
System.out.println("You are an invalid user");
}
}
Below is my code for LoginTimer class. In this, I am getting names of visible windows and then thread starts and in run() method i call sendGet() method for sending window names to php server page. I want that when I got the OK response in LoginForm class,the LoginTimer class will be called and executed automatically.I mean, when user logged in & verified then sending of window names to php server will start automatically.
public class LoginTimer implements Runnable
{
LoginTimer lk1;
String s3;
static int arraySize=10;
static int arrayGrowth=2;
static String[] m=new String[arraySize];
static int count=0;
#Override
public void run()
{
for(int ck=0;ck<3;ck++)
{File file=new File("G:\\check.txt");
Scanner scanner = null;
try
{
scanner = new Scanner(file);
}
catch (FileNotFoundException ex)
{
Logger.getLogger(LoginTimer.class.getName()).log(Level.SEVERE, null, ex);
}
while(scanner.hasNext())
{
String[] tokens = scanner.nextLine().split(":");
String last = tokens[1];
// System.out.println(last);
if(last!=null)
{
try
{
lk1.sendGet(last,m);
}
catch (Exception ex)
{
Logger.getLogger(LoginTimer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
Logger.getLogger(LoginTimer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static void main(String[] args)
{
(new Thread(new LoginTimer())).start();
final List<WindowInfo> inflList=new ArrayList<WindowInfo>();
final List<Integer> order=new ArrayList<Integer>();
int top = User32.instance.GetTopWindow(0);
while (top!=0)
{
order.add(top);
top = User32.instance.GetWindow(top, User32.GW_HWNDNEXT);
}
User32.instance.EnumWindows(new WndEnumProc()
{
public boolean callback(int hWnd, int lParam)
{
if (User32.instance.IsWindowVisible(hWnd))
{
RECT r = new RECT();
User32.instance.GetWindowRect(hWnd, r);
if (r.left>-32000)
{ // minimized
byte[] buffer = new byte[1024];
User32.instance.GetWindowTextA(hWnd, buffer, buffer.length);
String title = Native.toString(buffer);
//lk1.getid(title);
if (m.length == count)
{
// expand list
m = Arrays.copyOf(m, m.length + arrayGrowth);
}
m[count]=Native.toString(buffer);
System.out.println("title===="+m[count]);
count++;
inflList.add(new WindowInfo(hWnd, r, title));
}
}
return true;
}
}, 0);
Collections.sort(inflList, new Comparator<WindowInfo>()
{
public int compare(WindowInfo o1, WindowInfo o2)
{
return order.indexOf(o1.hwnd)-order.indexOf(o2.hwnd);
}
});
for (WindowInfo w : inflList)
{
System.out.println(w);
}
}
public static interface WndEnumProc extends StdCallLibrary.StdCallCallback
{
boolean callback (int hWnd, int lParam);
}
public static interface User32 extends StdCallLibrary
{
final User32 instance = (User32) Native.loadLibrary ("user32", User32.class);
boolean EnumWindows (WndEnumProc wndenumproc, int lParam);
boolean IsWindowVisible(int hWnd);
int GetWindowRect(int hWnd, RECT r);
void GetWindowTextA(int hWnd, byte[] buffer, int buflen);
int GetTopWindow(int hWnd);
int GetWindow(int hWnd, int flag);
final int GW_HWNDNEXT = 2;
}
public static class RECT extends Structure
{
public int left,top,right,bottom;
}
public static class WindowInfo
{
int hwnd;
RECT rect;
String title;
public WindowInfo(int hwnd, RECT rect, String title)
{
this.hwnd = hwnd; this.rect = rect; this.title = title;
}
public String toString()
{
return String.format("(%d,%d)-(%d,%d) : \"%s\"",
rect.left ,rect.top,rect.right,rect.bottom,title);
}
}
public static void sendGet(String last1,String[] get) throws Exception
{
for(int t=0;t<get.length;t++)
{
if(get[t]!=null)
{
String url = "http://localhost/add_windows.php?username="+last1+"&windowname="+get[t];
final String USER_AGENT = "Mozilla/5.0";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null)
{
response.append(inputLine);
}
in.close();
String r=response.toString();
System.out.println("String "+r);
}
}
}
}
As u are implementing runnable class you are creating thread. So create an object of LoginTimer as
LoginTimer lt = new LoginTimer();
in LoginForm class after you get result from php page.
Now call
lt.start();
after ur creation of object ; which will call ur run method of thread.
Now in ur LoginTimer class override the run method like
class LoginTimer implements Runnable
{
public void run()
{
//put your code which you want to execute now ...
}
}
As your class implements java.lang.Runnable.
To have the run() method executed by a thread, pass an instance of your class_implementing_Runnable to a Thread in its constructor.Something like
Thread thread = new Thread(new LoginTimer());
thread.start();
Related
I am new to the HTTP request in java. I have been trying to send an HTTP Post request to my NODE.JS server with the parameter key:12345. However, it doesn't send anything to my server. I tried tested my NOEDJS server to see if it worked in POSTMAN, and it did. So I am sure that this is something with the java that I made. I think a look at my code would help. Here it is down below.
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
public class ConnectionFactory {
private double API_VERSION = 0;
private String API = "";
private String METHOD = "POST";
private String USER_AGENT = "Mozilla/5.0";
private String TYPE = "application/x-www-form-urlencoded";
private String data = "";
private URL connection;
private HttpURLConnection finalConnection;
private HashMap<String, String> fields = new HashMap<String, String>();
public ConnectionFactory(String[] endpoint, String url, double version) {
this.API_VERSION = version;
this.API = url;
fields.put("version", String.valueOf(version));
for (int i = 0; i < endpoint.length; i++) {
String[] points = endpoint[i].split(";");
for (int f = 0; f < points.length; f++) {
fields.put(points[f].split(":")[0], points[f].split(":")[1]);
}
}
}
public String buildConnection() {
StringBuilder content = new StringBuilder();
if (!this.getEndpoints().equalsIgnoreCase("") && !this.getEndpoints().isEmpty()) {
String vars = "";
String vals = "";
try {
for (Map.Entry<String, String> entry: fields.entrySet()) {
vars = entry.getKey();
vals = entry.getValue();
data += ("&" + vars + "=" + vals);
}
if (data.startsWith("&")) {
data = data.replaceFirst("&", "");
}
connection = new URL(API);
BufferedReader reader = new BufferedReader(new InputStreamReader(readWithAccess(connection, data)));
String line;
while ((line = reader.readLine()) != null) {
content.append(line + "\n");
}
reader.close();
return content.toString();
} catch (Exception e) {
System.err.println(e.getMessage());
}
} else {
return null;
}
return null;
}
private InputStream readWithAccess(URL url, String data) {
try {
byte[] out = data.toString().getBytes();
finalConnection = (HttpURLConnection) url.openConnection();
finalConnection.setRequestMethod(METHOD);
finalConnection.setDoOutput(true);
finalConnection.addRequestProperty("User-Agent", USER_AGENT);
finalConnection.addRequestProperty("Content-Type", TYPE);
finalConnection.connect();
try {
OutputStream os = finalConnection.getOutputStream();
os.write(out);
} catch (Exception e) {
System.err.println(e.getMessage());
}
return finalConnection.getInputStream();
} catch (Exception e) {
System.err.println(e.getMessage());
return null;
}
}
public String getApiVersion() {
return String.valueOf(API_VERSION);
}
public String getEndpoints() {
return fields.toString();
}
public String getEndpointValue(String key) {
return fields.get(key);
}
public void setUserAgent(String userAgent) {
this.USER_AGENT = userAgent;
}
public void setMethod(String method) {
this.METHOD = method;
}
public void setSubmissionType(String type) {
this.TYPE = type;
}
}
public class example {
public static void main(String[] args) {
double version = 0.1;
String url = "http://localhost:3000";
String[] fields = {
"key:12345"
};
ConnectionFactory connection = new ConnectionFactory(fields, url, version);
connection.setUserAgent("Mozilla/5.0");
String response = connection.buildConnection();
System.out.println(response);
}
}
Here is the code for my node.js server
var http = require('http');
var url = require('url');
var queryString = require('querystring')
var StringDecoder = require('string_decoder').StringDecoder;
var server = http.createServer(function(req, res) {
//parse the URL
var parsedURL = url.parse(req.url, true);
//get the path
var path = parsedURL.pathname;
var trimmedPath = path.replace(/^\/+|\/+$/g, '');
//queryString
var queryStringObject = parsedURL.query;
console.log(queryStringObject);
if (queryStringObject.key == 12345) {
console.log("true")
res.end("true")
} else {
console.log("failed")
res.end("false")
}
// var query = queryStringObject.split()
});
server.listen(3000, function() {
console.log("Listening on port 3000");
});
The is no problem with your java client
The problem is that you are sending the content of your POST request as ""application/x-www-form-urlencoded" and then in your nodeJS server you are reading it as a query string
Here is a correct example using ExpressJS :
const express = require('express')
const app = express()
app.get('/', function (req, res) {
res.send('Hello World!')
})
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
app.post('/test', function(req, res) {
var key = req.body.key;
if (key==12345)
res.send(true );
else
res.send(false);
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
I tried to implement multithreading in Java by using executor service approach. Here is my code:
public class GetResponseContentWithExecutorService {
private static final int MYTHREADS = 30;
public static void main(String args[]) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(MYTHREADS);
String[] urlList ={"url1", "url2", "url3" ...};
for (int i = 0; i < urlList.length; i++) {
String baseUrl = "myUrl";
Runnable worker = new MyRunnable(baseUrl, urlList[i].split("-")[0], urlList[i].split("-")[1]);
executor.execute(worker);
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("\nCompleted all threads");
}
}
public class MyRunnable implements Runnable {
private final String baseUrl;
private final String a;
private final String b;
MyRunnable(String baseUrl, String a, String b) {
this.baseUrl = baseUrl;
this.a= a;
this.b= b;
}
#Override
public void run() {
String result = "";
int code = 200;
try {
URL siteURL = new URL(baseUrl + a + b);
HttpURLConnection connection = (HttpURLConnection) siteURL.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(3000);
connection.connect();
code = connection.getResponseCode();
if (code == 200) {
result = "-> Succ<-\t" + "Code: " + code;
} else {
result = "-> NoSuc <-\t" + "Code: " + code;
}
}
catch (Exception e) {
result = e.getMessage();
}
System.out.println(code);
}
}
The thing is that for about 30 urls I need to wait approx.40seconds and I would like to make it way faster. Any suggestions to what am I doing wrong here?
Any help is appreciated!!
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
In the first method, I just want to create a thread for each URL in the array and parse it:
public void readFriendData(String[] urls) {
Thread[] urlThreads = new Thread[urls.length];
for (int x = 0; x < urls.length; x++) {
Runobject input = new Runobject(urls[x], this);
Thread one = new Thread(input);
urlThreads[x] = one;
}
for(int x = 0; x< urls.length; x++){
urlThreads[x].start();
}
}
And then I made a separate class for my runnable object, where the run method creates a bufferedReader to scan the html file and parses it.
package twitbook;
public class Runobject implements Runnable {
public String address;
public Twitbook net;
public Runobject(String theAdress, Twitbook net) {
address = theAdress;
this.net = net;
}
#Override
public void run() {
try {
URL url = new URL(address);
URLConnection urlConnection = url.openConnection();
BufferedReader scanner = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
String input = scanner.readLine();
while (!input.equals("</body>")) {
if (input.startsWith("<tr> <td>addperson</td>")) {
input.replaceAll("<tr> <td>addperson</td>", "");
input.replaceAll(" <td>", "");
input.replaceAll("</td> </tr>", "");
net.addUser(input);
} else if (input.startsWith("<tr> <td>addfriend</td>")) {
String[] bits = new String[2];
input.replaceAll("<tr> <td>addfriend</td>", "");
bits = input.split("</td> <td>");
input.replaceAll(" <td>", "");
input.replaceAll("</td> </tr>", "");
net.friend(bits[0], bits[1]);
net.friend(bits[1], bits[0]);
}
input = scanner.readLine();
}
scanner.close();
} catch (IOException e) {
System.out.println("bad URL");
}
}
}
I know when the first method is called, even though I started the threads, it doesn't go through the run method in the runObject class. Why is this?
Your code works perfectly. You simply do not realize it. Add few logging/output messages and you will see it. Oh, by the way, anticipate end of input. Here is simplified code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
public class Runobject implements Runnable {
public String address;
public static void main(String a[]) {
System.out.println("Start");
readFriendData(new String[] { "http://google.com", "http://yahoo.com" });
System.out.println("End");
}
public static void readFriendData(String[] urls) {
Thread[] urlThreads = new Thread[urls.length];
for (int x = 0; x < urls.length; x++) {
Runobject input = new Runobject(urls[x]);
Thread one = new Thread(input);
urlThreads[x] = one;
}
for (int x = 0; x < urls.length; x++) {
urlThreads[x].start();
}
}
public Runobject(String theAdress) {
address = theAdress;
System.out.println(address);
}
#Override
public void run() {
try {
URL url = new URL(address);
URLConnection urlConnection = url.openConnection();
BufferedReader scanner = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
int countOfLines = 0;
String input = scanner.readLine();
while (input != null && !input.equals("</body>")) {
countOfLines++;
if (input.startsWith("<tr> <td>addperson</td>")) {
input.replaceAll("<tr> <td>addperson</td>", "");
input.replaceAll(" <td>", "");
input.replaceAll("</td> </tr>", "");
// net.addUser(input);
} else if (input.startsWith("<tr> <td>addfriend</td>")) {
String[] bits = new String[2];
input.replaceAll("<tr> <td>addfriend</td>", "");
bits = input.split("</td> <td>");
input.replaceAll(" <td>", "");
input.replaceAll("</td> </tr>", "");
// net.friend(bits[0], bits[1]);
// net.friend(bits[1], bits[0]);
}
input = scanner.readLine();
}
scanner.close();
System.out.println(address + " has " + countOfLines + " lines");
} catch (IOException e) {
System.out.println("bad URL");
}
}
}
and here is output:
Start
http://google.com
http://yahoo.com
End
http://google.com has 8 lines
http://yahoo.com has 63 lines
Pay attention that your main thread is already finished when your readers just started yet. One word - multithreading.
Though, I don't like the quality of it. I know I am not code reviewer. Please try this!
public static void main(String[] args) {
Twitbook twitbook = new Twitbook();
String[] urls = new String[2];
urls[0] = "www.google.com";
urls[0] = "www.yahoo.com";
twitbook.readFriendData(urls);
}
public void readFriendData(String[] urls) {
CountDownLatch latch = new CountDownLatch(urls.length);
for (int x = 0; x < urls.length; x++) {
Runobject input = new Runobject(urls[x], this, latch);
input.run();
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
return;
}
public synchronized void addUser(String input) {
return;
}
public synchronized void friend(String bits1, String bits2) {
return;
}
RunObject class here
public class Runobject implements Runnable {
public String address;
public Twitbook net;
public CountDownLatch latch;
public Runobject(String theAdress, Twitbook net, CountDownLatch latch) {
address = theAdress;
this.net = net;
}
#Override
public void run() {
try {
URL url = new URL(address);
URLConnection urlConnection = url.openConnection();
BufferedReader scanner = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
String input = scanner.readLine();
while (!input.equals("</body>")) {
if (input.startsWith("<tr> <td>addperson</td>")) {
input.replaceAll("<tr> <td>addperson</td>", "");
input.replaceAll(" <td>", "");
input.replaceAll("</td> </tr>", "");
net.addUser(input);
} else if (input.startsWith("<tr> <td>addfriend</td>")) {
String[] bits = new String[2];
input.replaceAll("<tr> <td>addfriend</td>", "");
bits = input.split("</td> <td>");
input.replaceAll(" <td>", "");
input.replaceAll("</td> </tr>", "");
net.friend(bits[0], bits[1]);
net.friend(bits[1], bits[0]);
}
input = scanner.readLine();
}
scanner.close();
} catch (IOException e) {
System.out.println("bad URL");
} finally {
latch.countDown();
}
}
Please consider better design. These links may help you to do better coding.
Thread pool is a good option.
http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html
CountDownLatch for finish all threads http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/CountDownLatch.html
Runobject can be a private inner class as well.
Wait until child threads completed : Java
disclaimer :- Answered with help of other question and answers.
I have created a small console application to do OCR on a .tiff image file, I have done this using tess4j.
public class JavaApplication10 {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
File imageFile = new File("C:\\Users\\Manesh\\Desktop\\license_plate.tiff");
Tesseract instance = Tesseract.getInstance(); // JNA Interface Mapping
// Tesseract1 instance = new Tesseract1(); // JNA Direct Mapping
try
{
String result = instance.doOCR(imageFile); //Empty result
System.out.println("hahahaha");
System.out.println("The result is: " + result);
}
catch (TesseractException e)
{
System.out.println("error:" + e);
}
}
}
I'm not getting any value inside result, when I looked into the code of Tesseract class and inserted a couple of System.out.println those are also not getting printed in the console. My Tesseract code is given below.
public class Tesseract
{
private static Tesseract instance;
private final static Rectangle EMPTY_RECTANGLE = new Rectangle();
private String language = "eng";
private String datapath = "tessdata";
private int psm = TessAPI.TessPageSegMode.PSM_AUTO;
private boolean hocr;
private int pageNum;
private int ocrEngineMode = TessAPI.TessOcrEngineMode.OEM_DEFAULT;
private Properties prop = new Properties();
public final static String htmlBeginTag =
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\""
+ " \"http://www.w3.org/TR/html4/loose.dtd\">\n"
+ "<html>\n<head>\n<title></title>\n"
+ "<meta http-equiv=\"Content-Type\" content=\"text/html;"
+ "charset=utf-8\" />\n<meta name='ocr-system' content='tesseract'/>\n"
+ "</head>\n<body>\n";
public final static String htmlEndTag = "</body>\n</html>\n";
private Tesseract()
{
System.setProperty("jna.encoding", "UTF8");
}
public static synchronized Tesseract getInstance()
{
if (instance == null)
{
instance = new Tesseract();
}
return instance;
}
public void setDatapath(String datapath)
{
this.datapath = datapath;
}
public void setLanguage(String language)
{
this.language = language;
}
public void setOcrEngineMode(int ocrEngineMode)
{
this.ocrEngineMode = ocrEngineMode;
}
public void setPageSegMode(int mode)
{
this.psm = mode;
}
public void setHocr(boolean hocr)
{
this.hocr = hocr;
prop.setProperty("tessedit_create_hocr", hocr ? "1" : "0");
}
public void setTessVariable(String key, String value)
{
prop.setProperty(key, value);
}
public String doOCR(File imageFile) throws TesseractException
{
System.out.println("hiiiiiii "); //not getting printed
return doOCR(imageFile, null);
}
public String doOCR(File imageFile, Rectangle rect) throws TesseractException
{
try
{
System.out.println("be: "); //not getting printed
return doOCR(ImageIOHelper.getIIOImageList(imageFile), rect);
}
catch (IOException ioe)
{
throw new TesseractException(ioe);
}
}
public String doOCR(BufferedImage bi) throws TesseractException
{
return doOCR(bi, null);
}
public String doOCR(BufferedImage bi, Rectangle rect) throws TesseractException
{
IIOImage oimage = new IIOImage(bi, null, null);
List<IIOImage> imageList = new ArrayList<IIOImage>();
imageList.add(oimage);
return doOCR(imageList, rect);
}
public String doOCR(List<IIOImage> imageList, Rectangle rect) throws TesseractException
{
StringBuilder sb = new StringBuilder();
pageNum = 0;
for (IIOImage oimage : imageList)
{
pageNum++;
try
{
ByteBuffer buf = ImageIOHelper.getImageByteBuffer(oimage);
RenderedImage ri = oimage.getRenderedImage();
String pageText = doOCR(ri.getWidth(), ri.getHeight(), buf, rect, ri.getColorModel().getPixelSize());
sb.append(pageText);
}
catch (IOException ioe)
{
//skip the problematic image
System.err.println(ioe.getMessage());
}
}
if (hocr)
{
sb.insert(0, htmlBeginTag).append(htmlEndTag);
}
return sb.toString();
}
public String doOCR(int xsize, int ysize, ByteBuffer buf, Rectangle rect, int bpp) throws TesseractException
{
TessAPI api = TessAPI.INSTANCE;
TessAPI.TessBaseAPI handle = api.TessBaseAPICreate();
api.TessBaseAPIInit2(handle, datapath, language, ocrEngineMode);
api.TessBaseAPISetPageSegMode(handle, psm);
Enumeration em = prop.propertyNames();
while (em.hasMoreElements())
{
String key = (String) em.nextElement();
api.TessBaseAPISetVariable(handle, key, prop.getProperty(key));
}
int bytespp = bpp / 8;
int bytespl = (int) Math.ceil(xsize * bpp / 8.0);
api.TessBaseAPISetImage(handle, buf, xsize, ysize, bytespp, bytespl);
if (rect != null && !rect.equals(EMPTY_RECTANGLE))
{
api.TessBaseAPISetRectangle(handle, rect.x, rect.y, rect.width, rect.height);
}
Pointer utf8Text = hocr ? api.TessBaseAPIGetHOCRText(handle, pageNum - 1) : api.TessBaseAPIGetUTF8Text(handle);
String str = utf8Text.getString(0);
api.TessDeleteText(utf8Text);
api.TessBaseAPIDelete(handle);
return str;
}
}
I'm using tesseract for the first time please tell me what I'm doing wrong.
For Tesseract you have to pass the exact image you want to do OCR on, for example, suppose you are reading the chest numbers of players, if you pass the cropped and gray scaled image of the chest number only it will read the text, where as if you pass the whole image it will not read. You can do this using.
String doOCR(BufferedImage img, Rectangle rect);
Well i'm passing the cropped image directly so I'm not using the above method, My code looks like this rite now.
public class JavaApplication10 {
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
try
{
File imageFile = new File("C:\\Users\\Manesh\\Desktop\\116.jpg"); //This is a cropped image of a chest number.
BufferedImage img = ImageIO.read(imageFile);
//BufferedImageOp grayscaleConv = new ColorConvertOp(colorFrame.getColorModel().getColorSpace(), grayscaleConv.filter(colorFrame, grayFrame);
Tesseract instance = Tesseract.getInstance(); // JNA Interface Mapping
ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
ColorConvertOp op = new ColorConvertOp(cs, null);
op.filter(img, img); // gray scaling the image
// Tesseract1 instance = new Tesseract1(); // JNA Direct Mapping
try
{
String result = instance.doOCR(img);
System.out.println("hahahaha");
System.out.println("The result is: " + result);
}
catch (TesseractException e)
{
System.out.println("error:" + e);
}
}
catch (IOException ex)
{
Logger.getLogger(JavaApplication10.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
This is what I found please feel free to correct me if I'm wrong anywhere.
I want to get google contacts in my Blackberry Application. Is there any public libraries availabile for blackberry to do this?
I try to use Oauth-SignPost. But the libraies used in it not supported by blackberry.Then I try the following code
public static String requestToken(){
String url = C.REQUEST_URL;
String header = oauth_header(url, HttpProtocolConstants.HTTP_METHOD_GET);
String requestTokenUrl = concatURL(url, header);
HttpConnection httpConn = null;
InputStream input = null;
try{
HttpConnectionFactory factory = new HttpConnectionFactory( requestTokenUrl,
HttpConnectionFactory.TRANSPORT_WIFI |
HttpConnectionFactory.TRANSPORT_WAP2 |
HttpConnectionFactory.TRANSPORT_BIS |
HttpConnectionFactory.TRANSPORT_BES |
HttpConnectionFactory.TRANSPORT_DIRECT_TCP);
httpConn = factory.getNextConnection();
httpConn.setRequestMethod(HttpProtocolConstants.HTTP_METHOD_GET);
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
input = httpConn.openDataInputStream();
int resp = httpConn.getResponseCode();
if (resp == HttpConnection.HTTP_OK) {
StringBuffer buffer = new StringBuffer();
int ch;
while ( (ch = input.read()) != -1){
buffer.append( (char) ch);
}
String content = buffer.toString();
System.out.println("Response"+content);
}
return "";
} catch (IOException e) {
return "exception";
} catch (NoMoreTransportsException nc) {
return "noConnection";
} finally {
try {
httpConn.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The oauth_header() which create the appending parameters
public static String oauth_header(String url, String method) {
String nonce = nonce();
long timestamp = timestamp();
Hashtable pairs = new Hashtable();
pairs.put(C.OAUTH_CONSUMER_KEY, C.CONSUMER_KEY);
pairs.put(C.OAUTH_NONCE, nonce);
pairs.put(C.OAUTH_SIGNATURE_METHOD, C.SIGNATURE_METHOD);
pairs.put(C.OAUTH_TIMESTAMP, Long.toString(timestamp));
pairs.put(C.OAUTH_SCOPE,C.SCOPE);
pairs.put(C.OAUTH_VERSION, "1.0");
String sig = signature(method, url, pairs);
StringBuffer header_sb = new StringBuffer();
header_sb.append(C.OAUTH_CONSUMER_KEY).append("=").append(C.CONSUMER_KEY).append(",");
header_sb.append(C.OAUTH_NONCE).append("=").append(nonce).append(",");
header_sb.append(C.OAUTH_SIGNATURE).append("=").append(URLUTF8Encoder.encode(sig)).append(",");
header_sb.append(C.OAUTH_SIGNATURE_METHOD).append("=").append(C.SIGNATURE_METHOD).append(",");
header_sb.append(C.OAUTH_TIMESTAMP).append("=").append(Long.toString(timestamp)).append(",");
header_sb.append(C.OAUTH_SCOPE).append("=").append(C.SCOPE);
header_sb.append(C.OAUTH_VERSION).append("=").append("1.0");
return header_sb.toString();
}
Signature() and concatUrl() here
private static String signature(String method, String requestURL, Hashtable pairs) {
StringBuffer sb = new StringBuffer();
String[] keys = new String[pairs.size()];
Enumeration e = pairs.keys();
int i = 0;
while(e.hasMoreElements()) {
String k = (String)e.nextElement();
keys[i++] = k + "=" + URLUTF8Encoder.encode((String)pairs.get(k));
}
Arrays.sort(keys, new Comparator() {
public int compare(Object arg0, Object arg1) {
return ((String)arg0).compareTo((String)arg1);
}
});
for(i = 0; i < keys.length; i++) {
sb.append(keys[i]).append('&');
}
sb.deleteCharAt(sb.length()-1);
String msg = method.toUpperCase() +"&" + URLUTF8Encoder.encode(requestURL) + "&" + URLUTF8Encoder.encode(sb.toString());
System.out.println(msg);
StringBuffer key = new StringBuffer();
if(C.CONSUMER_SECRET != null) key.append(URLUTF8Encoder.encode(C.CONSUMER_SECRET));
key.append('&');
/* if(Const.tokenSecret != null){
key.append(URLUTF8Encoder.encode(Const.tokenSecret));
}*/
try {
return hmacsha1(key.toString(), msg);
} catch (Exception ex) {
return null;
}
}
private static String hmacsha1(String key, String message)
throws CryptoTokenException, CryptoUnsupportedOperationException, IOException {
HMACKey k = new HMACKey(key.getBytes());
HMAC hmac = new HMAC(k, new SHA1Digest());
hmac.update(message.getBytes());
byte[] mac = hmac.getMAC();
return Base64OutputStream.encodeAsString(mac, 0, mac.length, false, false);
}
public static String concatURL(String url, String header){
String newurl=url;
header = header.replace(',', '&');
newurl = newurl+"?"+header;
return newurl;
}
Then I get the signature_invalid Message. please Help me to find out the error.