I need an example to convert Spanish language to English language using Google Translation API. I tried with the following code. It gives some exception. can someone help me on the same.
Code :
import com.google.api.translate.*;
public class GoogleTranslator {
/**
* #param args
*/
#SuppressWarnings("deprecation")
public static void main(String[] args) {// TODO code application logic here
try {
Translate.setHttpReferrer("sp-en");
String translatedText = Translate.translate("Hola mundo", Language.SPANISH, Language.ENGLISH);
System.out.println(translatedText);
} catch (Exception ex) {
ex.printStackTrace(); }
}
}
Error :
java.lang.Exception: [google-api-translate-java] Error retrieving translation.
at com.google.api.GoogleAPI.retrieveJSON(GoogleAPI.java:136)
at com.google.api.translate.Translate.execute(Translate.java:69)
at com.google.api.translate.Translate.translate(Translate.java:192)
at GoogleTranslator.main(GoogleTranslator.java:15)
Caused by: java.net.UnknownHostException: ajax.googleapis.com
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(Unknown Source)
at com.google.api.GoogleAPI.retrieveJSON(GoogleAPI.java:115)
... 3 more
You need to figure out why you don't reach this host: ajax.googleapis.com
The Exception says:
java.net.UnknownHostException: ajax.googleapis.com
The javadoc says UnknownHostException is thrown to indicate that the IP address of a host could not be determined.
You should your DNS.
nslookup ajax.googleapis.com
Set your DNS to google one
if on linux machine
sudo gedit /etc/resolv.conf
add
nameserver 8.8.8.8
nameserver 8.8.4.4
or if on windows goto network setting and set DNS for active connection
you don't have an api key, for example GoogleAPI.setKey(); you need something like this to continue i guess
Related
I wonder about a Java error that is repeatedly occurs in MATLAB. It typically occurs when MATLAB is doing some heavy stuff with Java. This can for example be holding Ctrl + Z or Ctrl + Y.
I did by mistake erase the error message before I copied it, but I think that I can pass the core of the problem anyway.
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
...
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Why did this error occur? I have found some information about this from MATLAB r2007, this due to that Java Swing is thread unsafe and MATLAB lacked support to ensure thread safety. However, that is supposed to have been fixed in MATLAB r2008b. So why do I get it now?
Here is the full stack trace:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at org.netbeans.editor.BaseDocument.notifyUnmodify(BaseDocument.java:1465)
at org.netbeans.editor.BaseDocument.notifyModifyCheckEnd(BaseDocument.java:816)
at org.netbeans.editor.BaseDocumentEvent.redo(BaseDocumentEvent.java:336)
at javax.swing.undo.UndoManager.redoTo(Unknown Source)
at javax.swing.undo.UndoManager.redo(Unknown Source)
at com.mathworks.mwswing.undo.MUndoManager.redo(MUndoManager.java:255)
at org.netbeans.editor.ActionFactory$RedoAction.actionPerformed(ActionFactory.java:767)
at org.netbeans.editor.BaseAction.actionPerformed(BaseAction.java:259)
at javax.swing.SwingUtilities.notifyAction(Unknown Source)
at javax.swing.JComponent.processKeyBinding(Unknown Source)
at javax.swing.JComponent.processKeyBindings(Unknown Source)
at javax.swing.JComponent.processKeyEvent(Unknown Source)
at com.mathworks.widgets.SyntaxTextPaneBase.processKeyEvent(SyntaxTextPaneBase.java:1187)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.KeyboardFocusManager.redispatchEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(Unknown Source)
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Well, based on your stack trace, probably there isn’t any definitive answer to your question, as you have already seen in MATLAB's forum, but given this line, I think there's a possible explanation:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
...
at javax.swing.undo.UndoManager.redoTo(Unknown Source) // <-- here!
at javax.swing.undo.UndoManager.redo(Unknown Source)
at com.mathworks.mwswing.undo.MUndoManager.redo(MUndoManager.java:255)
...
UndoManager class keeps an internal collection of UndoableEdit objects. This collection is actually inherithed from its superclass: CompoundEdit.
The internal implementation of UndoManager#redo() and UndoManager#redoTo(UndoableEdit edit) looks like this:
public class UndoManager extends CompoundEdit implements UndoableEditListener {
...
public synchronized void redo() throws CannotRedoException {
if (inProgress) {
UndoableEdit edit = editToBeRedone();
if (edit == null) {
throw new CannotRedoException();
}
redoTo(edit);
} else {
super.redo();
}
}
...
protected void redoTo(UndoableEdit edit) throws CannotRedoException {
boolean done = false;
while (!done) {
UndoableEdit next = edits.elementAt(indexOfNextAdd++);
next.redo(); // NPE here?
done = next == edit;
}
}
...
}
Considering this implementation and given that Swing's Event Dispatch Thread (EDT) is prone to cause troubles, I think it's probably a threading issue between MATLAB threads and the EDT. Specifically speaking this MATLAB-invoked method could be the source of the problem:
at com.mathworks.mwswing.undo.MUndoManager.redo(MUndoManager.java:255)
Since you say MATLAB needs to do heavy work, it's not unreasonable to think this method is trying to redo some edit that might well not be available anymore or might not be available yet, due to synchronization problems with the EDT.
You can find the ~/.matlab folder which contains MATLAB settings, etc. Use ls -la to show all hidden files and folders.
Open a terminal and execute sudo chmod 757 -R ~/.matlab.
Similarly there is a folder, MATLAB, in Documents.
Execute sudo chmod 757 -R ~/Documents/MATLAB.
Now restart MATLAB without root privileges. It worked for me on Ubuntu 14.04 (Trusty Tahr) and MATLAB 2015a.
I want to run simple rmi server code below.
Firstly, I write command "rmiregistry 9260" and so I started the rmi register.
Then I run following code but I get errors.
What can cause these errors? Note that I tried different port numbers.
public class Server {
public static void main(String args[]) {
try {
PaymentImpl robj = new PaymentImpl();
Payment stub = (Payment) UnicastRemoteObject.exportObject(robj, 9260);
Registry registry = LocateRegistry.getRegistry();
registry.bind("Mortgage", stub);
System.out.println("Mortgage Server is ready to listen... ");
} catch (Exception e) {
System.err.println("Server exception thrown: " + e.toString());
e.printStackTrace();
}
}
}
Server exception thrown: java.rmi.server.ExportException: Port already in use
260; nested exception is:
java.net.BindException: Address already in use
java.rmi.server.ExportException: Port already in use: 9260; nested exception
java.net.BindException: Address already in use
at sun.rmi.transport.tcp.TCPTransport.listen(Unknown Source)
at sun.rmi.transport.tcp.TCPTransport.exportObject(Unknown Source)
at sun.rmi.transport.tcp.TCPEndpoint.exportObject(Unknown Source)
at sun.rmi.transport.LiveRef.exportObject(Unknown Source)
at sun.rmi.server.UnicastServerRef.exportObject(Unknown Source)
at java.rmi.server.UnicastRemoteObject.exportObject(Unknown Source)
at java.rmi.server.UnicastRemoteObject.exportObject(Unknown Source)
at Server.main(Server.java:14)
Caused by: java.net.BindException: Address already in use
at java.net.PlainSocketImpl.socketBind(Native Method)
at java.net.AbstractPlainSocketImpl.bind(Unknown Source)
at java.net.ServerSocket.bind(Unknown Source)
at java.net.ServerSocket.<init>(Unknown Source)
at java.net.ServerSocket.<init>(Unknown Source)
at sun.rmi.transport.proxy.RMIDirectSocketFactory.createServerSocket(
nown Source)
at sun.rmi.transport.proxy.RMIMasterSocketFactory.createServerSocket(
nown Source)
at sun.rmi.transport.tcp.TCPEndpoint.newServerSocket(Unknown Source)
... 8 more
If you're using 9260 for a separate Registry process you can't use it again in this process. You can use 9260 for both by starting the Registry in this process, with LocateRegistry.createRegistry(). Store the return value into a static variable to prevent GC.
I have a question/problem related to Java Applet security...
I use the Applet that has to take files from server (ASP.NET) and represent the information from it. Applet take files using the code:
URL u = new URL(getCodeBase(), filename);
BufferedReader d = new BufferedReader(new InputStreamReader(u.openStream()));
This code appears in two places:
Init() method
Some another method Test() that called manually from JavaScript
So, when I try to load the page with Applet using the URL http://127.0.0.1:8000/Test.aspx, everything works fine and I can read file content from both methods. But if I change the URL on http://localhost:8000/, only the first method works properly and I can get files content and for the second one I get the next error message in JavaConsole:
java.security.AccessControlException: access denied (java.net.SocketPermission 127.0.0.1:8000 connect,resolve)
What it the difference in this case? Why 'localhost' is impossible in this case? Is there any way how to grant access to 'localhost' the same as 127.0.0.1?
here is simplest applet's example:
public class TestApplet extends Applet {
public void init()
{
System.out.println( "init...");
readDocument();
}
public void readDocument()
{
System.out.println( "read test.txt file...");
URL base = getCodeBase();
String filename = "test.txt";
try {
URL u = new URL(base, filename);
BufferedReader d = new BufferedReader(new InputStreamReader(u.openStream()));
System.out.println(d.readLine());
System.out.println("Done!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
and next code used on the client side:
<applet archive="/Content/test.jar" code="test.TestApplet.class" name="testApplet" mayscript></applet>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
var testApplet = document.testApplet;
testApplet.readDocument();
});
</script>
this code works perfectly when I try to use http://127.0.0.1:8000/Test.aspx
and doesn't work when I user http://localhost:8000/Test.aspx. I java console I see the next:
init...
read test.txt file...
some text...
Done!
read test.txt file...
java.security.AccessControlException: access denied (java.net.SocketPermission 127.0.0.1:8000 connect,resolve)
at java.security.AccessControlContext.checkPermission(Unknown Source)
at java.security.AccessController.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkConnect(Unknown Source)
at sun.plugin2.applet.Applet2SecurityManager.checkConnect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.URL.openStream(Unknown Source)
at test.TestApplet.readDocument(TestApplet.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.plugin.javascript.JSInvoke.invoke(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.plugin.javascript.JSClassLoader.invoke(Unknown Source)
at sun.plugin2.liveconnect.JavaClass$MethodInfo.invoke(Unknown Source)
at sun.plugin2.liveconnect.JavaClass$MemberBundle.invoke(Unknown Source)
at sun.plugin2.liveconnect.JavaClass.invoke0(Unknown Source)
at sun.plugin2.liveconnect.JavaClass.invoke(Unknown Source)
at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo$DefaultInvocationDelegate.invoke(Unknown Source)
at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo.doObjectOp(Unknown Source)
at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo$LiveConnectWorker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
P.S.: Applet is signed.
The problem is the call from JavaScript. If you are using JavaScript to call your method, the permissions of the call get down to the intersection of the JavaScript bridge's permissions (i.e. nothing) and the permissions of your own code - even if your own code is signed.
To avoid this, and use the full privileges of your applet's code, put the security-relevant parts inside a AccessController.doPrivileged(...) call. (Of course, your applet should first check that this can't do anything malicious.)
I have no idea why it works if you are using the IP address directly instead of localhost, though.
localhost is an alias for 127.0.0.1 so you may have to set/fix it in your enviroment. Under Windows you have to edit the file C:\Windows\System32\drivers\etc\hosts.
localhost is typically resolved to both ::1 and 127.0.0.1 and the OS/libc is usually set up so that IPv6 is preferred in these circumstances.
Therefore, it's likely you're allowing only 127.0.0.1 and not IPv6 connections from ::1.
I've built this actionPerformed method so that it reads a string I pass to the button (I needed to make my own button class to hold this new string) and depending on what it says, it does a different action. One of the possibilities of the string is to be something like: shell(""). This is supposed to run a system command (command line in windows, shell command in unix/linux) in the background. This is the source of the method:
public void actionPerformed(ActionEvent e) {
if (e.getSource() == this.button) {
if (password != "") {
}
if (action.startsWith("shell(\"")) {
String tmpSHELL = action.substring(7, action.length() - 2);
try {
Process p = Runtime.getRuntime().exec(tmpSHELL);
} catch (IOException e1) {
ErrorDialog error = new ErrorDialog("Error handling your shell action");
System.exit(0);
}
}
else if (action.startsWith("frame(\"")) {
String tmpFRAME = action.substring(7, action.length() - 2);
MenuFrame target = ConfigReader.getFrame(tmpFRAME);
this.parent.setVisible(false);
this.parent.validate();
target.setVisible(true);
target.validate();
}
else if (action.equals("exit()")) {
System.exit(0);
}
else {
ErrorDialog error = new ErrorDialog("You config file contains an invalid action command. Use either shell(), frame() or exit()");
System.exit(0);
}
}
}
I know that I get into the method but I'm not sure if the command is being executed successfully. I'm currently in a windows environment so I made a simple batch script that echos some text then waits for a keystroke before printing the tree of the C: drive. I put the .bat into my working java directory and passed the string shell("test") (test is the name of the batch file). However, when I click the button I get an error dialog (the one I coded above).
Is there something wrong with my code or maybe my understanding of how executing a shell command works in java? The command is throwing an IO exception but I can't seem to figure out why. Thanks in advance for your help.
Stacktrace:
java.io.IOException: Cannot run program "test": CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at Button.actionPerformed(Button.java:52)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(Unknown Source)
at java.lang.ProcessImpl.start(Unknown Source)
... 30 more
The system cannot find the file specified
Your file path is not right. Try passing an absolute file path.
shell("C:/somedirectory/test.bat")
Also, you can test this by removing the string test altogether. Hard code the runtime execution of the batch file by making the if statement always true and passing the path to your batch file to the Runtime.getRuntime().exec()
if (password != "") {
}
if (true) {
String tmpSHELL = action.substring(7, action.length() - 2);
try {
Process p = Runtime.getRuntime().exec("test");
} catch (IOException e1) {
ErrorDialog error = new ErrorDialog("Error handling your shell action");
System.exit(0);
}
}
This should produce the same error. Then replace the file path with an absolute file path and you should be able to execute the batch file.
Process p = Runtime.getRuntime().exec("C:/somedirectory/test.bat");
On Windows try command line:
"cmd test /c"
It's because the command test isn't found in the system PATH environment variable.
If you go to the command line and type test it will fail. This is what the exception is indicating.
Loading classifier from D:\PROJECT\classifiers\NERDemo\classifiers\ner-eng-ie.crf-3-all2008.ser.gz ... done [2.0 sec].
Original Query was riot in India.
Parsing Queries and expanding tokens from the Ontologies..
{locations=[India], events=[riot]}
Search query is null
Something went wrong...
java.net.UnknownHostException: ajax.googleapis.com
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at org.girs2.SearchHandler.makeQuery(SearchHandler.java:35)
at org.girs2.GIRS.search(GIRS.java:37)
at org.girs2.GIRS.main(GIRS.java:62)
Exception in thread "main" java.lang.NullPointerException
at org.girs2.GIRS.search(GIRS.java:44)
at org.girs2.GIRS.main(GIRS.java:62)
Looks like you probably have or had a DNS lookup failure. This tells you what happened:
java.net.UnknownHostException: ajax.googleapis.com
If you always get this exception and you can otherwise access this host by name, then I don't know what this could be, but odds are that this was a temporary DNS failure.
What should you do when you get this Exception? Well, if the address is one that you fully expect you should be able to get to -- such as this one -- then when you catch the Exception, you sleep for a while (perhaps 10 or 15 seconds, maybe even 30 or 60 seconds, depending on your application's needs) and try again.
If after several retries -- don't just retry forever! -- you still cannot reach the site, then log a reasonable complaint or otherwise complain that you cannot reach the site and have your application exit.
There's not much you can do when DNS fails except give up or wait and try again.