Permalink
Browse files

- extra options for processTextField

- proxy configuration options
  • Loading branch information...
1 parent b0478d7 commit 5b55c486fcd5d0229695e50cccc7b92f01e06468 Vasily Panferov committed Jun 13, 2012
@@ -7,4 +7,23 @@
public class ClientSettings {
public static final String APPLICATION_ID = "";
public static final String PASSWORD = "";
+
+ public static void setupProxy()
+ {
+ // Uncomment this if you are behind a proxy
+ /*
+ String host = "";
+ String port = "";
+ String user = "";
+ String password = "";
+ System.getProperties().put("http.proxyHost", host );
+ System.getProperties().put("https.proxyHost", host );
+ System.getProperties().put("http.proxyPort", port);
+ System.getProperties().put("https.proxyPort", port);
+ System.getProperties().put("http.proxyUser", user);
+ System.getProperties().put("https.proxyUser", user);
+ System.getProperties().put("http.proxyPassword", password);
+ System.getProperties().put("https.proxyPassword", password);
+ */
+ }
}
@@ -19,6 +19,8 @@ public static void main(String[] args) {
return;
}
+ ClientSettings.setupProxy();
+
restClient = new Client();
restClient.applicationId = ClientSettings.APPLICATION_ID;
restClient.password = ClientSettings.PASSWORD;
@@ -44,12 +46,11 @@ public static void main(String[] args) {
performFieldsRecognition(argList);
} else {
System.out.println("Unknown mode: " + mode);
+ return;
}
-
- // FIXME: remove
- return;
} catch (Exception e) {
System.out.println("Exception occured:" + e.getMessage());
+ //e.printStackTrace();
}
}
@@ -235,20 +236,28 @@ private static void displayTextFieldHelp() {
.println("Recognize printed or handprinted text field.\n"
+ "\n"
+ "Usage:\n"
- + "java TestApp textField [--lang=<languages>] <file> <output file>\n"
- + "\n" + "Examples:\n"
- + "java TestApp textField image.tif result.xml\n");
+ + "java TestApp textField [--lang=<languages>] [--options=<options] <file> <output file>\n"
+ + "\n"
+ + "<options> - options passed directly to processTextField RESTful call\n"
+ + "\n"
+ + "Examples:\n"
+ + "java TestApp textField image.tif result.xml\n"
+ + "java TestApp textField --options='letterSet=0123456789/&regExp=[0-9][0-9]' image.tif result.xml\n");
}
private static void performTextFieldRecognition(Vector<String> argList)
throws Exception {
String language = extractRecognitionLanguage(argList);
+ String options = extractExtraOptions(argList);
String outputPath = argList.lastElement();
argList.remove(argList.size() - 1);
// argList now contains list of source images to process
TextFieldSettings settings = new TextFieldSettings();
settings.setLanguage(language);
+ if (options != null) {
+ settings.setOptions(options);
+ }
// TODO - different processing options
@@ -309,7 +318,7 @@ private static void displayProcessFieldsHelp() {
}
/**
- * Perform field-level recognition using processFields call
+ * Perform field-level recognition using processFields call.
*
* For details see
* http://ocrsdk.com/documentation/apireference/processFields/
@@ -377,24 +386,41 @@ private static void waitAndDownloadResult(Task task, String outputPath)
}
/**
- * Extract recognition language from command-line parameters. After
- * extraction parameter is removed
+ * Extract value of given parameter from command-line parameters. Parameter
+ * is removed after extraction
*
- * @return recognition language
+ * @return value of parameter or null
*/
- private static String extractRecognitionLanguage(Vector<String> args) {
- // Recognition language parameter has form --lang=<languges>
- String prefix = "--lang=";
+ private static String extractParameterValue(String parameterName,
+ Vector<String> args) {
+ String prefix = "--" + parameterName + "=";
for (int i = 0; i < args.size(); i++) {
String arg = args.elementAt(i);
if (arg.startsWith(prefix)) {
- String lang = arg.substring(prefix.length());
+ String value = arg.substring(prefix.length());
args.remove(i);
- return lang;
+ return value;
}
}
+ return null;
+ }
+
+ /**
+ * Extract recognition language from command-line parameters. After
+ * extraction parameter is removed
+ *
+ * @return recognition language
+ */
+ private static String extractRecognitionLanguage(Vector<String> args) {
+ // Recognition language parameter has form --lang=<languges>
+
+ String lang = extractParameterValue("lang", args);
+ if (lang != null) {
+ return lang;
+ }
+
System.out
.println("Warning! The document will be processed with English language.\n"
+ "To change this, specify --lang=<languages> option.\n");
@@ -403,6 +429,17 @@ private static String extractRecognitionLanguage(Vector<String> args) {
}
/**
+ * Extract extra RESTful options from command-line parameters. Parameter is
+ * removed after extraction
+ *
+ * @return extra options string or null
+ */
+ private static String extractExtraOptions(Vector<String> args) {
+ // Extra options parameter has from --options=<options>
+ return extractParameterValue("options", args);
+ }
+
+ /**
* Extract output format from extension of output file.
*/
private static ProcessingSettings.OutputFormat outputFormatByFileExt(
@@ -3,6 +3,14 @@
import java.io.*;
import java.net.*;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+import org.xml.sax.InputSource;
+
public class Client {
public String applicationId;
public String password;
@@ -28,9 +36,7 @@ public Task submitImage(String filePath, String taskId) throws Exception {
Integer.toString(fileContents.length));
connection.getOutputStream().write(fileContents);
- BufferedReader reader = new BufferedReader(new InputStreamReader(
- connection.getInputStream()));
- return new Task(reader);
+ return getResponse(connection);
}
public Task processImage(String filePath, ProcessingSettings settings)
@@ -44,21 +50,16 @@ public Task processImage(String filePath, ProcessingSettings settings)
Integer.toString(fileContents.length));
connection.getOutputStream().write(fileContents);
- BufferedReader reader = new BufferedReader(new InputStreamReader(
- connection.getInputStream()));
- return new Task(reader);
+ return getResponse(connection);
}
public Task processDocument(String taskId, ProcessingSettings settings)
throws Exception {
URL url = new URL(serverUrl + "/processDocument?taskId=" + taskId + "&"
+ settings.asUrlParams());
- URLConnection connection = openGetConnection(url);
-
- BufferedReader reader = new BufferedReader(new InputStreamReader(
- connection.getInputStream()));
- return new Task(reader);
+ HttpURLConnection connection = openGetConnection(url);
+ return getResponse(connection);
}
public Task processBusinessCard(String filePath, BusCardSettings settings)
@@ -73,9 +74,7 @@ public Task processBusinessCard(String filePath, BusCardSettings settings)
Integer.toString(fileContents.length));
connection.getOutputStream().write(fileContents);
- BufferedReader reader = new BufferedReader(new InputStreamReader(
- connection.getInputStream()));
- return new Task(reader);
+ return getResponse(connection);
}
public Task processTextField(String filePath, TextFieldSettings settings)
@@ -90,9 +89,7 @@ public Task processTextField(String filePath, TextFieldSettings settings)
Integer.toString(fileContents.length));
connection.getOutputStream().write(fileContents);
- BufferedReader reader = new BufferedReader(new InputStreamReader(
- connection.getInputStream()));
- return new Task(reader);
+ return getResponse(connection);
}
public Task processBarcodeField(String filePath, BarcodeSettings settings)
@@ -107,9 +104,7 @@ public Task processBarcodeField(String filePath, BarcodeSettings settings)
Integer.toString(fileContents.length));
connection.getOutputStream().write(fileContents);
- BufferedReader reader = new BufferedReader(new InputStreamReader(
- connection.getInputStream()));
- return new Task(reader);
+ return getResponse(connection);
}
public Task processCheckmarkField(String filePath) throws Exception {
@@ -122,9 +117,7 @@ public Task processCheckmarkField(String filePath) throws Exception {
Integer.toString(fileContents.length));
connection.getOutputStream().write(fileContents);
- BufferedReader reader = new BufferedReader(new InputStreamReader(
- connection.getInputStream()));
- return new Task(reader);
+ return getResponse(connection);
}
/**
@@ -147,18 +140,14 @@ public Task processFields(String taskId, String settingsPath)
Integer.toString(fileContents.length));
connection.getOutputStream().write(fileContents);
- BufferedReader reader = new BufferedReader(new InputStreamReader(
- connection.getInputStream()));
- return new Task(reader);
+ return getResponse(connection);
}
public Task getTaskStatus(String taskId) throws Exception {
URL url = new URL(serverUrl + "/getTaskStatus?taskId=" + taskId);
- URLConnection connection = openGetConnection(url);
- BufferedReader reader = new BufferedReader(new InputStreamReader(
- connection.getInputStream()));
- return new Task(reader);
+ HttpURLConnection connection = openGetConnection(url);
+ return getResponse(connection);
}
public void downloadResult(Task task, String outputFile) throws Exception {
@@ -200,8 +189,8 @@ private HttpURLConnection openPostConnection(URL url) throws Exception {
return connection;
}
- private URLConnection openGetConnection(URL url) throws Exception {
- URLConnection connection = url.openConnection();
+ private HttpURLConnection openGetConnection(URL url) throws Exception {
+ HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// connection.setRequestMethod("GET");
setupAuthorization(connection);
return connection;
@@ -243,4 +232,49 @@ private String encodeUserPassword() {
return Base64.encode(toEncode);
}
+ /**
+ * Read server response from HTTP connection and return task description.
+ *
+ * @throws Exception
+ * in case of error
+ */
+ private Task getResponse(HttpURLConnection connection) throws Exception {
+ int responseCode = connection.getResponseCode();
+ if (responseCode == 200) {
+ InputStream inputStream = connection.getInputStream();
+ BufferedReader reader = new BufferedReader(new InputStreamReader(
+ inputStream));
+ return new Task(reader);
+ } else if (responseCode == 401) {
+ throw new Exception(
+ "HTTP 401 Unauthorized. Please check your application id and password");
+ } else if (responseCode == 407) {
+ throw new Exception("HTTP 407. Proxy authentication error");
+ } else {
+ String message = "";
+ try {
+ InputStream errorStream = connection.getErrorStream();
+
+ BufferedReader reader = new BufferedReader(
+ new InputStreamReader(errorStream));
+
+ // Parse xml error response
+ InputSource source = new InputSource();
+ source.setCharacterStream(reader);
+ DocumentBuilder builder = DocumentBuilderFactory.newInstance()
+ .newDocumentBuilder();
+ Document doc = builder.parse(source);
+
+ NodeList error = doc.getElementsByTagName("error");
+ Element err = (Element) error.item(0);
+
+ message = err.getTextContent();
+ } catch (Exception e) {
+ throw new Exception("Error getting server response");
+ }
+
+ throw new Exception("Error: " + message);
+ }
+ }
+
}
@@ -7,7 +7,13 @@
public String asUrlParams() {
// For all possible parameters, see documentation at
// http://ocrsdk.com/documentation/apireference/processTextField/
- return String.format("language=%s&textType=%s", language, textType);
+ String params = String.format("language=%s&textType=%s", language,
+ textType);
+ if (options != null && !options.isEmpty()) {
+ params += "&" + options;
+ }
+
+ return params;
}
/*
@@ -33,6 +39,22 @@ public void setTextType(String newTextType) {
textType = newTextType;
}
+ /**
+ * Set extra options directly passed to RESTful call.
+ */
+ public void setOptions(String newOptions) {
+ options = newOptions;
+ }
+
+ public String getOptions() {
+ return options;
+ }
+
private String language = "English";
private String textType = "normal,handprinted";
+
+ /**
+ * Extra options passed directly to RESTful call.
+ */
+ private String options = null;
}

0 comments on commit 5b55c48

Please sign in to comment.