I'm developing a Eclipse plugin that reads from and writes to the console. I expect the following code to flash an alert window with "Hello World" on it.
public void run(IAction action) {
ConsoleCommands.writeToConsole("Hello World!");
Alert(ConsoleCommands.readConsole());
}
However, the alert simply shows blank. Some investigation showed that the read was happening before the write (the display on the console was fine, just the alert was showing the previous state of the console) so I tried,
public void run(IAction action) {
ConsoleCommands.writeToConsole("Hello Wolrd!");
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Alert(ConsoleCommands.readConsole());
}
in case there was a threading issue, but this simply delays the writing to the console as well. Any ideas what is happening?
----EDIT-----
In case it's useful, here's the code for the methods...
import org.eclipse.jface.text.IDocument;
import org.eclipse.ui.console.ConsolePlugin;
import org.eclipse.ui.console.IConsole;
import org.eclipse.ui.console.IConsoleManager;
import org.eclipse.ui.console.MessageConsole;
import org.eclipse.ui.console.MessageConsoleStream;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.ui.console.ConsolePlugin;
import org.eclipse.ui.console.IConsole;
import org.eclipse.ui.console.IConsoleManager;
import org.eclipse.ui.console.MessageConsole;
import org.eclipse.ui.console.MessageConsoleStream;
public class ConsoleCommands {
private static MessageConsole findConsole(String name) {
ConsolePlugin plugin = ConsolePlugin.getDefault();
IConsoleManager conMan = plugin.getConsoleManager();
IConsole[] existing = conMan.getConsoles();
for (int i = 0; i < existing.length; i++)
if (name.equals(existing[i].getName()))
return (MessageConsole) existing[i];
// no console found, so create a new one
MessageConsole myConsole = new MessageConsole(name, null);
conMan.addConsoles(new IConsole[] { myConsole });
return myConsole;
}
public static String readConsole() {
MessageConsole myConsole = findConsole("Joe's Console");
IDocument doc = myConsole.getDocument();
return doc.get();
}
public static MessageConsole writeToConsole(String output) {
MessageConsole myConsole = findConsole("Joe's Console");
MessageConsoleStream out = myConsole.newMessageStream();
out.println(output);
return myConsole;
}
}
Try writing to the console using myConsole.getDocument().set(output) instead of using the stream.
I don't know if this is recommended practice but it solved the problem for us...
Related
I have images of codes that I want to decode. How can I use zxing so that I specify the image location and get the decoded text back, and in case the decoding fails (it will for some images, that's the project), it gives me an error.
How can I setup zxing on my Windows machine? I downloaded the jar file, but I don't know where to start. I understand I'll have to create a code to read the image and supply it to the library reader method, but a guide how to do that would be very helpful.
I was able to do it. Downloaded the source and added the following code. Bit rustic, but gets the work done.
import com.google.zxing.NotFoundException;
import com.google.zxing.ChecksumException;
import com.google.zxing.FormatException;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.DecodeHintType;
import com.google.zxing.Reader;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.Result;
import com.google.zxing.LuminanceSource;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.util.*;
import com.google.zxing.qrcode.QRCodeReader;
class qr
{
public static void main(String args[])
{
Reader xReader = new QRCodeReader();
BufferedImage dest = null;
try
{
dest = ImageIO.read(new File(args[0]));
}
catch(IOException e)
{
System.out.println("Cannot load input image");
}
LuminanceSource source = new BufferedImageLuminanceSource(dest);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Vector<BarcodeFormat> barcodeFormats = new Vector<BarcodeFormat>();
barcodeFormats.add(BarcodeFormat.QR_CODE);
HashMap<DecodeHintType, Object> decodeHints = new HashMap<DecodeHintType, Object>(3);
decodeHints.put(DecodeHintType.POSSIBLE_FORMATS, barcodeFormats);
decodeHints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
Result result = null;
try
{
result = xReader.decode(bitmap, decodeHints);
System.out.println("Code Decoded");
String text = result.getText();
System.out.println(text);
}
catch(NotFoundException e)
{
System.out.println("Decoding Failed");
}
catch(ChecksumException e)
{
System.out.println("Checksum error");
}
catch(FormatException e)
{
System.out.println("Wrong format");
}
}
}
The project includes a class called CommandLineRunner which you can simply call from the command line. You can also look at its source to see how it works and reuse it.
There is nothing to install or set up. It's a library. Typically you don't download the jar but declare it as a dependency in your Maven-based project.
If you just want to send an image to decode, use http://zxing.org/w/decode.jspx
I want to know the JUnit test cases for the following program.please help. I have not included the main method here. Want to know the JUnit test cases for the url() method in the code. This code is to read HTML from a website and save it in a file in local machine
package Java3;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Urltohtml
{
private String str;
public void url() throws IOException
{
try
{
FileOutputStream f=new FileOutputStream("D:/File1.txt");
PrintStream p=new PrintStream(f);
URL u=new URL("http://www.google.com");
BufferedReader br=new BufferedReader(new InputStreamReader(u.openStream()));
//str=br.readLine();
while((str=br.readLine())!=null)
{
System.out.println(str+"\n");
p.println(str);
}
}
catch (MalformedURLException ex)
{
Logger.getLogger(Urltohtml.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I would rename that class to UrlToHtml and write a single JUnit test class UrlToHtmlTest.
Part of the reason why you're having problems testing this is that the class is poorly designed and implemented:
You should pass in the URL you want to scrape, not hard code it.
You should return the content as a String or List, not print it to a file.
You might want to throw that exception rather than catch it. Your logging isn't exactly "handling" the exceptional situation. Let it bubble out and have clients log if they wish.
You don't need that private data member; return the contents. That lets you make this method static.
Good names matter. I don't like what you have for the class or the method.
Why are you writing this when you could use a library to do it?
Here's what the test class might look like:
public class UrlToHtmlTest {
#Test
public void testUrlToHtml() {
try {
String testUrl = "http://www.google.com" ;
String expected = "";
String actual = UrlToHtml.url(testUrl);
Assert.assertEquals(expected, actual);
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
}
}
}
I used SeleniumHQ to record my actions and then exported them to Java Unity WebDrive. Then I edited exported code and added many small extra things like looping over array, time-stamps, etc.
My code does following:
Log into my site.
Goto my profile.
Delete my previous announcement.
Post new announcement.
Log out.
I have tried using FirefoxDriver and HtmlUnitDriver, but every single of them gives me this weird problem. My code start doing its work and randomly stops in random spot and hangs there forever.
For example it could log in -> goto profile -> delete previous and then stop, or it could hang right in the login. I loop over those steps over and over again, and more I loop more likely it is to get stuck.
First loops success rate is 90% second loop is around 40% etc. Also which Driver I use also affects this. It is most likely to hang with HtmlUnitDriver and I would really want to use HtmlUnitDrive because I want to run my code headless on Ubuntu Server.
Has anyone else had similar problems?
EDIT : Now after many hours of testing, I noticed that its only HtmlUnitDriver that hangs and not Firefox. When using Firefox I can see what it is doing and it is doing everything as it should. Problem occurs with HtmlUnitDriver.
And here is the code itself:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
public class WebUpdater {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new HtmlUnitDriver(true); // JavaScript enabled.
baseUrl = "http://exampleurl.com";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testUnity() throws Exception {
openAndLogin();
gotoProfile();
deletePreviousPost();
uploadPost();
logOut();
System.out.println("Done!");
}
private void openAndLogin() {
driver.get(baseUrl);
driver.findElement(By.linkText("Login")).click();
driver.findElement(By.id("jsid-login-id")).clear();
driver.findElement(By.id("jsid-login-id")).sendKeys("bilgeis.babayan#gmail.com");
driver.findElement(By.id("jsid-login-password")).clear();
driver.findElement(By.id("jsid-login-password")).sendKeys("volume1991");
driver.findElement(By.cssSelector("input.right")).click();
}
private void gotoProfile() {
driver.findElement(By.cssSelector("img[alt=\"Profile\"]")).click();
}
private void deletePreviousPost() {
try {
driver.findElement(By.cssSelector("img[alt=\"ExampleName\"]")).click();
driver.findElement(By.linkText("Delete")).click();
assertTrue(closeAlertAndGetItsText().matches("^Confirm to delete this post[\\s\\S]$"));
} catch (Exception e) {
System.out.println(e);
}
}
private void uploadPost() {
driver.findElement(By.linkText("ExampleAction")).click();
driver.findElement(By.id("example_url")).clear();
driver.findElement(By.id("example_url")).sendKeys("Example text that gets typed in textfield.");
driver.findElement(By.cssSelector("input[name=\"example\"]")).clear();
driver.findElement(By.cssSelector("input[name=\"example\"]")).sendKeys("ExampleName");
driver.findElement(By.linkText("ExampleAction2")).click();
System.out.println("Done");
}
private void logOut() {
driver.get("http://exampleurl.com/logout");
System.out.println("Logged out.");
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alert.getText();
} finally {
acceptNextAlert = true;
}
}
}
in my main class I call WebUpdater class like this:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main {
public static void main(String[] args) {
Logger logger = Logger.getLogger("");
logger.setLevel(Level.OFF);
scan();
}
private static void scan() {
while (true) {
try {
// Test if connection is available and target url is up.
URL url = new URL("http://exampleurl.com");
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.connect();
// Start tests.
WebUpdater updater = new WebUpdater();
updater.setUp();
updater.testUnity();
updater.tearDown();
} catch (Exception ex) {
System.out.println(ex);
}
try {
Thread.sleep(12000);
} catch (InterruptedException e) {
}
}
}
}
I had a bad experience with HtmlUnitDriver. Some time ago I wrote testing framework which were supposed to be fired at Hudson, and finally I decided to use Firefox driver which was more predictable and easier to debug. The point is that in my case it was a page full of javascripts - dynamically loaded fields, etc., and working with HtmlUnitDriver was really a can of worms.
If you really need to use HtmlUnitDriver try do debug 'pagesource' which is accessible for Selenium in 'current' (hanging) moment.
HtmlUnit 2.11 is flawed (see here and here), and since HtmlUnit 2.12 went live march 6th, the current version of HtmlUnitDriver is probably still based on HtmlUnit 2.11.
If you post your "http://exampleurl.com/" source code (or just give me a working url to the page if it's public) I could run the page with scripts through HtmlUnit 2.12.
I created an eclipse plugin that will hook into the save action to create a minified javascript file with the goolge closure compiler. See files below.
That worked until eclipse 3.7.2. Unfortunately now in eclipse 4.2.1 it seems that this creates an endless loop sometimes. The job "compile .min.js" (line 64 in ResourceChangedListener.java) seems the be the cause. It results in the case that the workspaced starts to build over and over. I guess this is because that job creates or changes a file triggering the workspace build again, which again triggers the job which triggers the build and so on.
But I can not figure out how to prevent this.
// Activator.java
package closure_compiler_save;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
/**
* The activator class controls the plug-in life cycle
*/
public class Activator extends AbstractUIPlugin {
// The plug-in ID
public static final String PLUGIN_ID = "closure-compiler-save"; //$NON-NLS-1$
// The shared instance
private static Activator plugin;
/**
* The constructor
*/
public Activator() {
}
#Override
public void start(BundleContext context) throws Exception {
super.start(context);
Activator.plugin = this;
ResourceChangedListener listener = new ResourceChangedListener();
ResourcesPlugin.getWorkspace().addResourceChangeListener(listener);
}
#Override
public void stop(BundleContext context) throws Exception {
Activator.plugin = null;
super.stop(context);
}
/**
* Returns the shared instance
*
* #return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
}
// ResourceChangedListener.java
package closure_compiler_save;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
public class ResourceChangedListener implements IResourceChangeListener {
public void resourceChanged(IResourceChangeEvent event) {
if (event.getType() != IResourceChangeEvent.POST_CHANGE)
return;
IResourceDelta delta = event.getDelta();
try {
processDelta(delta);
} catch (CoreException e) {
e.printStackTrace();
}
}
// find out which class files were just built
private void processDelta(IResourceDelta delta) throws CoreException {
IResourceDelta[] kids = delta.getAffectedChildren();
for (IResourceDelta delta2 : kids) {
if (delta2.getAffectedChildren().length == 0) {
if (delta.getKind() != IResourceDelta.CHANGED)
return;
IResource res = delta2.getResource();
if (res.getType() == IResource.FILE && "js".equalsIgnoreCase(res.getFileExtension())) {
if (res.getName().contains("min"))
return;
compile(res);
}
}
processDelta(delta2);
}
}
private void compile(final IResource res) throws CoreException {
final IPath fullPath = res.getFullPath();
final IPath fullLocation = res.getLocation();
final String fileName = fullPath.lastSegment().toString();
final String outputFilename = fileName.substring(0, fileName.lastIndexOf(".")).concat(".min.js");
final String outputPath = fullPath.removeFirstSegments(1).removeLastSegments(1).toString();
final IProject project = res.getProject();
final IFile newFile = project.getFile(outputPath.concat("/".concat(outputFilename)));
Job compileJob = new Job("Compile .min.js") {
public IStatus run(IProgressMonitor monitor) {
byte[] bytes = null;
try {
bytes = CallCompiler.compile(fullLocation.toString(), CallCompiler.SIMPLE_OPTIMIZATION).getBytes();
InputStream source = new ByteArrayInputStream(bytes);
if (!newFile.exists()) {
newFile.create(source, IResource.NONE, null);
} else {
newFile.setContents(source, IResource.NONE, null);
}
} catch (IOException e) {
e.printStackTrace();
} catch (CoreException e) {
e.printStackTrace();
}
return Status.OK_STATUS;
}
};
compileJob.setRule(newFile.getProject()); // this will ensure that no two jobs are writing simultaneously on the same file
compileJob.schedule();
}
}
After I setup a blank eclipse classic environment, started a new eclipse plugin project there and recreated all files it works again partly.
In this environment starting a debug session I can save .js files and .min.js files are created automatically.
So far so good!
But when I install the plugin to my real developing eclipse environment automatic saving does not work.
At least one step further!
Step 2:
There were some files not included in the build obviously needed, like manifest. No idea why they were deselected.
Anyway it seems just setting up a blank eclipse 4 classic and going through the eclipse plugin wizard fixed my original problem. I still would love to know what was the actual problem...
hello:
I'm writing code in java for nutch(open source search engine) to remove the movments from arabic words in the indexer.
I don't know what is the error in it.
Tthis is the code:
package com.mycompany.nutch.indexing;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
import org.apache.log4j.Logger;
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.crawl.Inlinks;
import org.apache.nutch.indexer.IndexingException;
import org.apache.nutch.indexer.IndexingFilter;
import org.apache.nutch.indexer.NutchDocument;
import org.apache.nutch.parse.getData().parse.getData();
public class InvalidUrlIndexFilter implements IndexingFilter {
private static final Logger LOGGER =
Logger.getLogger(InvalidUrlIndexFilter.class);
private Configuration conf;
public void addIndexBackendOptions(Configuration conf) {
// NOOP
return;
}
public NutchDocument filter(NutchDocument doc, Parse parse, Text url,
CrawlDatum datum, Inlinks inlinks) throws IndexingException {
if (url == null) {
return null;
}
char[] parse.getData() = input.trim().toCharArray();
for(int p=0;p<parse.getData().length;p++)
if(!(parse.getData()[p]=='َ'||parse.getData()[p]=='ً'||parse.getData()[p]=='ُ'||parse.getData()[p]=='ِ'||parse.getData()[p]=='ٍ'||parse.getData()[p]=='ٌ' ||parse.getData()[p]=='ّ'||parse.getData()[p]=='ْ' ||parse.getData()[p]=='"' ))
new String.append(parse.getData()[p]);
return doc;
}
public Configuration getConf() {
return conf;
}
public void setConf(Configuration conf) {
this.conf = conf;
}
}
I think that the error is in using parse.getdata() but I don't know what I should use instead of it?
The line
char[] parse.getData() = input.trim().toCharArray();
will give you a compile error because the left hand side is not a variable. Please replace parse.getData() by a unique variable name (e.g. parsedData) in this line and the following lines.
Second the import of
import org.apache.nutch.parse.getData().parse.getData();
will also fail. Looks a lot like a text replace issue.