How to read captcha with tesseract, width and background variables - captcha

it's possible to read this captcha? How can i read?
captcha
---EDIT
Code:
public static String imgToTxt(String imgFileName) {
try {
Process pr = (new ProcessBuilder()).redirectOutput(new File("/tmp/tesseract.log"))
.redirectError(new File("/tmp/tesseract-error.log"))
.command("/opt/local/bin/tesseract", imgFileName + ".png", imgFileName).start();
pr.waitFor();
Reader input = new FileReader(new File(imgFileName + ".txt"));
StringWriter output = new StringWriter();
IOUtils.copy(input, output);
return output.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

For future assistance.
I had to treat the image using imagemagick tool. Remove the background and improved the font text.
public static String imgToTxt(String imgFileName) {
try {
ProcessBuilder pb = new ProcessBuilder("convert", imgFileName + ".png", "-fuzz", "15%", "-fill", "black",
"-opaque", "rgb(16,128,176)", "-fuzz", "40%", "-fill", "white", "+opaque", "black",
imgFileName + ".png");
pb.redirectErrorStream(true);
Process pr = pb.start();
BufferedReader br = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
pr.waitFor();
pr = (new ProcessBuilder()).redirectOutput(new File("/tmp/tesseract.log"))
.redirectError(new File("/tmp/tesseract-error.log"))
.command("/opt/local/bin/tesseract", imgFileName + ".png", imgFileName).start();
pr.waitFor();
Reader input = new FileReader(new File(imgFileName + ".txt"));
StringWriter output = new StringWriter();
IOUtils.copy(input, output);
return output.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

Related

Converting Docx to PDF getting spacing issues

I am trying to convert a document to PDF using apache POI or Docx4j ( Apache FOP) both are giving issues while conversion.
While using apache POI it leaves line spaces when it is not there in document also.
But while using Apache FOP the table heading and table is getting shifted on next page.
I am new to this.
Can you advise which one would be better and how to avoid these spaces.
Here are code samples
SampleCode1 using apache POI
try
{
oLog.error("function POI begin");
String WordDocFile= "C:\\PRPCPersonalEdition\\tomcat\\TestDocument.docx";
oLog.error("WordDocFile is"+WordDocFile);
String pdfDocFile="C:\\PRPCPersonalEdition\\tomcat\\TestDocument.pdf";
oLog.error("pdfDocFile is"+pdfDocFile);
InputStream iStream= new FileInputStream(WordDocFile);
OutputStream os = new FileOutputStream(pdfDocFile);
org.apache.poi.xwpf.usermodel.XWPFDocument document=new org.apache.poi.xwpf.usermodel.XWPFDocument(iStream);
oLog.error("Loaded XWPFDocument");
org.apache.poi.xwpf.converter.pdf.PdfOptions options= org.apache.poi.xwpf.converter.pdf.PdfOptions.create() ;
org.apache.poi.xwpf.converter.pdf.PdfConverter.getInstance().convert(document,os,options);
iStream.close();
os.close();
return "Success";
}
catch(Exception e)
{
e.printStackTrace();
oLog.error("print exception"+e);
return "FAIL";
}
SampleCode2 using Docx4j
try
{ final org.docx4j.wml.ObjectFactory objectFactory = new org.docx4j.wml.ObjectFactory();
String WordDocFile= "C:\\PRPCPersonalEdition\\tomcat\\TestDocument.docx";
String pdfDocFile="C:\\PRPCPersonalEdition\\tomcat\\TestDocument.pdf";
InputStream iStream= new FileInputStream(WordDocFile);
org.docx4j.openpackaging.packages.WordprocessingMLPackage pack = org.docx4j.openpackaging.packages.WordprocessingMLPackage.load(iStream);
org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart docPart = pack.getMainDocumentPart();
OutputStream os = new FileOutputStream(pdfDocFile);
org.docx4j.Docx4J.toPDF(pack,os);
iStream.close();
os.close();
return "Success";
}
catch(Exception e)
{
e.printStackTrace();
oLog.error("print exception"+e);
return "FAIL";
}
#Sample Code 3 using itext
try
{
java.util.List lstInputStream = new java.util.ArrayList < java.io.InputStream > ();
oLog.error("function PDF iText begin");
String WordDocFile= "C:\PRPCPersonalEdition\tomcat\DraftMin.docx";
String pdfDocFile="C:\PRPCPersonalEdition\tomcat\DraftMinItext12.pdf";
InputStream iStream= new FileInputStream(WordDocFile);
oLog.error("Read Input file"+iStream);
java.io.InputStream isCurrentStream = null;
OutputStream os = new FileOutputStream(pdfDocFile);
java.io.ByteArrayOutputStream osCurrentStream = null;
org.apache.poi.xwpf.usermodel.XWPFDocument document=new org.apache.poi.xwpf.usermodel.XWPFDocument(iStream);
fr.opensagres.poi.xwpf.converter.pdf.PdfOptions options = fr.opensagres.poi.xwpf.converter.pdf.PdfOptions.create();
fr.opensagres.poi.xwpf.converter.pdf.PdfConverter.getInstance().convert(document,(java.io.OutputStream)osCurrentStream, options);
com.itextpdf.text.Document finalDocument = new com.itextpdf.text.Document();
finalDocument.addAuthor("Your Corporation");
finalDocument.addCreationDate();
finalDocument.addProducer();
finalDocument.addCreator("System");
finalDocument.addTitle("Your Corporation");
finalDocument.setPageSize(com.itextpdf.text.PageSize.A4);
com.itextpdf.text.pdf.PdfCopy copy1 = new com.itextpdf.text.pdf.PdfCopy(finalDocument, (java.io.OutputStream) os);
finalDocument.open();
PRFile file = new PRFile("C:\PRPCPersonalEdition\tomcat\Savepdf.pdf");
PROutputStream prOS = new PROutputStream(file);
prOS.write(osCurrentStream.toByteArray());
oLog.debug("file write");
prOS.close();
PRInputStream prIS = new PRInputStream(file);
oLog.debug("file read");
isCurrentStream = (java.io.InputStream) prIS;
oLog.debug("casting to java.io.InputStream");
file.delete();
lstInputStream.add(isCurrentStream);
java.util.Iterator < java.io.InputStream > pdfIterator = lstInputStream.iterator();
while (pdfIterator.hasNext()) {
java.io.InputStream pdf = pdfIterator.next();
com.itextpdf.text.pdf.PdfReader.unethicalreading = true;
com.itextpdf.text.pdf.PdfReader readingpdf = new com.itextpdf.text.pdf.PdfReader(pdf);
int n = readingpdf.getNumberOfPages();
for ( int i=1;i<n;i++)
{
oLog.error("Entered in loop"+i);
copy1.addPage(copy1.getImportedPage(readingpdf, i));
oLog.error("Read Page n : "+i);
}
}
finalDocument.close();
iStream.close();
os.close();
return "Success";
}
catch(Exception e)
{
e.printStackTrace();
oLog.error("print exception"+e);
return "FAIL";
}

I got notification from FCM of google, but my messageBody was garbled. How to resolve it?

Post was successful, but the message body was garbled.
{"data":{"data_content":"測試","data_title":"Joyce"},"notification":{"body":"測試","title":"test"},"to":"myDeviceId"}
this.is my post code , is there any wrong? Thanks.
<pre><code>
public class HttpConnection {
public void startConnection(final String apiUrl, final String jsonStr, final OnPostNotificationListener listener) {
new Thread(new Runnable() {
#Override
public void run() {
HttpURLConnection conn = null;
StringBuilder response = new StringBuilder();
try {
URL url = new URL(apiUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Authorization","key=Key");
conn.setRequestProperty("Content-Type","application/json");
conn.setRequestMethod("POST");
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
OutputStream os = conn.getOutputStream();
DataOutputStream writer = new DataOutputStream(os);
writer.writeBytes(jsonStr);
writer.flush();
writer.close();
os.close();
//Get Response
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
response.append('\r');
}
listener.onSuccessful(response.toString());
reader.close();
} catch (Exception ex) {
ex.printStackTrace();
listener.onFail(ex.toString());
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
}).start();
}
public interface OnPostNotificationListener{
void onSuccessful(String result);
void onFail(String exception);
}
}
</code></pre>
Thank you for your help.The picture of the phone
The problem comes from writeBytes method and the representation of kanjis (or other non ISO-8859-1 characters). You should use writeUTF method instead :
writer.writeUTF(jsonStr);
You can take a look at this post explaning the difference between writeBytes and writeUTF. Basically, you should always use writeUTF when writing strings.

Java JList and JTextArea

I am stuck on a java project.
I am working with TXT files, and i have the open these TXT files from the JList.
Since i am a total noob at this, it took me a few hours to manage to make the JList work. But now i am stuck at the JTextArea.
The idea is this: clicking on a item from the JList (item = a TXT file from a folder), it should open that TXT file in the JTextArea to view it.
..here is my code so far ..it's a bit long:
-JButton for the search and putting the TXT files in the JList:
JButton searchSearchButton = new JButton("Search");
searchSearchButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultListModel model1 = new DefaultListModel();
File dir = new File("C:\\Users\\Zoli\\Desktop\\New folder");
File[] matches = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith(searchKeywordTextField.getText()) && name.endsWith(".txt");
}
});
for(File f : matches){
model1.addElement(f.getName());
}
searchList.setModel(model1);
}
});
searchSearchButton.setBounds(186, 43, 89, 23);
linuxSearchPane.add(searchSearchButton);
-This is the JTextArea and the JList code:
final JTextArea searchTextArea = new JTextArea();
JScrollPane searchTextAreaScrollPane = new JScrollPane(searchTextArea);
searchTextAreaScrollPane.setBounds(316, 43, 496, 430);
linuxSearchPane.add(searchTextAreaScrollPane);
final JList searchList = new JList();
searchList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
searchList.setVisibleRowCount(20);
searchList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
searchTextArea.setText("");
for(Object o : searchList.getSelectedValuesList()){
searchTextArea.append(o.toString()+"\r\n");
}
}
});
-All i managed to do is, when i select an item from the JList, it prints out the item name in the JTextArea not what it contains in the TXT.
Here is a picture to show you:
picture
could anyone please help me with this...i have zero idea...i have read about JList, and JTextArea, but nothing even points to what i need...
Please help.
I DID IT!!!
Here's the code:
final JTextArea searchTextArea = new JTextArea();
JScrollPane searchTextAreaScrollPane = new JScrollPane(searchTextArea);
searchTextAreaScrollPane.setBounds(316, 43, 496, 430);
linuxSearchPane.add(searchTextAreaScrollPane);
final JList searchList = new JList();
searchList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
searchList.setVisibleRowCount(20);
searchList.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
searchTextArea.setText("");
String root = "C:\\Users\\Zoli\\Desktop\\New folder\\";
String filename;
String lineRead = "";
String fileContent = "";
try {
for(Object o : searchList.getSelectedValuesList()){
filename = o.toString();
FileReader reader = new FileReader(root + filename);
BufferedReader buffer = new BufferedReader(reader);
while(lineRead != null){
try {
lineRead = buffer.readLine();
} catch (IOException e1) {
e1.printStackTrace();
}
if(lineRead != null){
fileContent = fileContent + lineRead + "\r\n";
searchTextArea.setText(fileContent);
}
}
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
Also here's the picture to see how it works: picture

Add a Bitmap image in a PDF document in Android

please, how can i directly pass a bitmap image to a pdf file. I have made a graph with GraphView and at the end i convert it to Bitmap, inside an OnClickListener:
write.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0) {
Bitmap bitmap;
graph.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(graph.getDrawingCache());
graph.setDrawingCacheEnabled(false);
String filename = "imagen";
FileOperations fop = new FileOperations();
fop.write(filename, bitmap);
if (fop.write(filename,bitmap)) {
Toast.makeText(getApplicationContext(),
filename + ".pdf created", Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(getApplicationContext(), "I/O error",
Toast.LENGTH_SHORT).show();
}
}
});
The problem is that in the class FileOperations:
public FileOperations() {
}
public Boolean write(String fname, Bitmap bm) {
try {
String fpath = "/sdcard/" + fname + ".pdf";
File file = new File(fpath);
if (!file.exists()) {
file.createNewFile();
}
Document document = new Document();
PdfWriter.getInstance(document,
new FileOutputStream(file.getAbsoluteFile()));
document.open();
String filename = bm.toString();
com.itextpdf.text.Image image =com.itextpdf.text.Image.getInstance(filename);
document.add(image);
document.add(new Paragraph("Hello World2!"));
// step 5
document.close();
Log.d("Suceess", "Sucess");
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
}
I want to know how can i pass the bitmap Image to add it in the pdf document, i do this but i think this works only when i give it a path.
String filename = bm.toString();
com.itextpdf.text.Image image =com.itextpdf.text.Image.getInstance(filename);
I just solve it:
document.open();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
Image myImg = Image.getInstance(stream.toByteArray());
myImg.setAlignment(Image.MIDDLE);
document.add(myImg);
in the FileOperations class

How to add screenshot into RallyDev using RAlly API

how to upload the screenshots into rally dev using the rally rest api. I am able to log defects. I need to log screenshots
Here is an example using Rally REST Api Tookit for Java that creates a defect and then creates an attachment on the defect:
public class CreateDefectAddAttachment{
public static void main(String[] args) throws URISyntaxException, IOException {
String host = "https://rally1.rallydev.com";
String apiKey = "_abc123";
String projectRef = "/project/12352608219";
String applicationName = "RestExample_createDefectAttachScreenshot";
RallyRestApi restApi = new RallyRestApi(new URI(host),apiKey);
restApi.setApplicationName(applicationName);
//Read User
QueryRequest userRequest = new QueryRequest("User");
userRequest.setQueryFilter(new QueryFilter("UserName", "=", "user#company.com"));
QueryResponse userQueryResponse = restApi.query(userRequest);
JsonArray userQueryResults = userQueryResponse.getResults();
JsonElement userQueryElement = userQueryResults.get(0);
JsonObject userQueryObject = userQueryElement.getAsJsonObject();
String userRef = userQueryObject.get("_ref").getAsString();
try {
for (int i=0; i<1; i++) {
//Create a defect
JsonObject newDefect = new JsonObject();
newDefect.addProperty("Name", "bug1234");
newDefect.addProperty("Project", projectRef);
CreateRequest createRequest = new CreateRequest("defect", newDefect);
CreateResponse createResponse = restApi.create(createRequest);
if (createResponse.wasSuccessful()) {
System.out.println(String.format("Created %s", createResponse.getObject().get("_ref").getAsString()));
//Read defect
String ref = Ref.getRelativeRef(createResponse.getObject().get("_ref").getAsString());
System.out.println(String.format("\nReading Defect %s...", ref));
String imageFilePath = "C:/";
String imageFileName = "pic.png";
String fullImageFile = imageFilePath + imageFileName;
String imageBase64String;
long attachmentSize;
// Open file
RandomAccessFile myImageFileHandle = new RandomAccessFile(fullImageFile, "r");
try {
long longLength = myImageFileHandle.length();
long maxLength = 5000000;
if (longLength >= maxLength) throw new IOException("File size >= 5 MB Upper limit for Rally.");
int fileLength = (int) longLength;
// Read file and return data
byte[] fileBytes = new byte[fileLength];
myImageFileHandle.readFully(fileBytes);
imageBase64String = Base64.encodeBase64String(fileBytes);
attachmentSize = fileLength;
// First create AttachmentContent from image string
JsonObject myAttachmentContent = new JsonObject();
myAttachmentContent.addProperty("Content", imageBase64String);
CreateRequest attachmentContentCreateRequest = new CreateRequest("AttachmentContent", myAttachmentContent);
CreateResponse attachmentContentResponse = restApi.create(attachmentContentCreateRequest);
String myAttachmentContentRef = attachmentContentResponse.getObject().get("_ref").getAsString();
System.out.println("Attachment Content created: " + myAttachmentContentRef);
//Create the Attachment
JsonObject myAttachment = new JsonObject();
myAttachment.addProperty("Artifact", ref);
myAttachment.addProperty("Content", myAttachmentContentRef);
myAttachment.addProperty("Name", "AttachmentFromREST.png");
myAttachment.addProperty("Description", "Attachment From REST");
myAttachment.addProperty("ContentType","image/png");
myAttachment.addProperty("Size", attachmentSize);
myAttachment.addProperty("User", userRef);
CreateRequest attachmentCreateRequest = new CreateRequest("Attachment", myAttachment);
CreateResponse attachmentResponse = restApi.create(attachmentCreateRequest);
String myAttachmentRef = attachmentResponse.getObject().get("_ref").getAsString();
System.out.println("Attachment created: " + myAttachmentRef);
if (attachmentResponse.wasSuccessful()) {
System.out.println("Successfully created Attachment");
} else {
String[] attachmentContentErrors;
attachmentContentErrors = attachmentResponse.getErrors();
System.out.println("Error occurred creating Attachment: ");
for (int j=0; j<attachmentContentErrors.length;j++) {
System.out.println(attachmentContentErrors[j]);
}
}
}catch (Exception e) {
System.out.println("Exception occurred while attempting to create Content and/or Attachment: ");
e.printStackTrace();
}
} else {
String[] createErrors;
createErrors = createResponse.getErrors();
System.out.println("Error occurred creating a defect: ");
for (int j=0; i<createErrors.length;j++) {
System.out.println(createErrors[j]);
}
}
}
} finally {
//Release all resources
restApi.close();
}
}
}