Error in HTTPUnit Code - java

I am trying to learn HTTPUnit and have read cookbook mentioned on http://httpunit.sourceforge.net/doc/cookbook.html
But when I am trying this very simple code
package httpUnit.test;
import java.io.IOException;
import org.xml.sax.SAXException;
import com.meterware.httpunit.GetMethodWebRequest;
import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.WebLink;
import com.meterware.httpunit.WebRequest;
import com.meterware.httpunit.WebResponse;
/*** Hello world!**/
public class App{
public static void main( String[] args ) throws IOException, SAXException {
System.out.println( "Trying HTPUnit library");
WebConversation wc = new WebConversation();
WebRequest req = new GetMethodWebRequest("http://localhost:8080/proof/demo.html");
WebResponse resp = wc.getResponse(req);
/* WebLink[ ] link = resp.getLinks();
for (int i=0; i<link.length; i++) {
System.out.println(link[i].getText());
}
System.out.println(link.length);
*/
}
};
I am getting the following errors:
TypeError: undefined is not a function. (httpunit; line 15)
at org.mozilla.javascript.NativeGlobal.constructError(NativeGlobal.java:597)
at org.mozilla.javascript.NativeGlobal.constructError(NativeGlobal.java:557)
Error continues.....
and
Exception in thread "main" com.meterware.httpunit.ScriptException: Script '/*!
* jQuery JavaScript Library v1.6
* http://jquery.com/
Can somebody please figure out what could be the problem. I could not understand. I have created the maven project with maven dependency from http://mvnrepository.com/artifact/httpunit/httpunit/1.6.1
And I have hosted demo.html in proof folder in tomcat which is opening fine in browser.

I think the problem is with javascript only.
Checkout http://httpunit.sourceforge.net/doc/faq.html#javascript
And use HttpUnitOptions.setScriptingEnabled(false);
I think it will do.

Related

Get string with translation from Google translate

i have faced some problem - i need to integrate Google Translate API to my project but i'm new and can't understand how to do it properly. This code is made just for example.
What i have now when i launch:few seconds for input and then program is closing.
What i want to have: i put my input and get translation in console(+ in array if possible).
Also i made folder "libs" and added here gson-2.8.5.jar.
Thank you in advance.
package com.company;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class Connect {
public void gogo() throws IOException, InterruptedException {
String query = "key=AIzaSyB2HijQLlsmI1udH9ARl45oC5eAj4XfjTw"
+"&source=en"
+"&target=uk"
+"&q=hello";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://www.googlepis.com/language/translate/v2?"+ query))
.header("Referer", "https://www.daytranslations.com/free-translation-online/")
.GET()
.build();
String responseJson = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString())
.body();
System.out.println(responseJson);
}
}
package com.company;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException, InterruptedException {
Connect connect = new Connect();
connect.gogo();
}
}
There seems to be a typo in your request, try "https://www.googleapis.com/language/translate/v2?" instead.
A basic way to use Gson to deserialize the API response would be:
JsonParser.parseString(responseJson).getAsJsonObject()
.get("data").getAsJsonObject()
.get("translations").getAsJsonArray()
.get(0).getAsJsonObject()
.get("translatedText").getAsString();

Nashorn java.lang.NoClassDefFoundError: jdk/nashorn/api/scripting/JSObject

I am migrating my Eclipse RCP to use JDK 8 and I heavily use the JS ScriptEngine. Now that Nashorn is introduced I had to add the following line to get the importClass and importPackage functions to work:
load("nashorn:mozilla_compat.js");
After doing so, I got java.lang.NoClassDefFoundError: jdk/nashorn/api/scripting/JSObject.
I am using Nashorn inside an Eclipse RCP. The problem occurs when I call a Java function from the Javascript and try to use the parameter sent. The parameter I want to send is a Javascript function that I would like to execute call on later in the code.
I have the following code:
TestNashorn.java
package com.test.nashorn;
import java.io.FileNotFoundException;
import java.io.FileReader;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.script.Invocable;
import jdk.nashorn.api.scripting.JSObject;
public class TestNashorn {
public static void main(String[] args) {
ScriptEngine engine = (new ScriptEngineManager()).getEngineByName("js");
try {
engine.eval(new FileReader("C:/Users/user/workspace_nashorn/TestNashorn/src/com/test/nashorn/test.js"));
Object o = ((Invocable)engine).invokeFunction("generate");
} catch (ScriptException | FileNotFoundException | NoSuchMethodException e) {
e.printStackTrace();
}
}
public static int test(JSObject o1) {
System.out.println(o1.getClass().toString());
JSObject som = ((JSObject)o1);
return 1;
}
}
test.js
load("nashorn:mozilla_compat.js");
importClass(com.test.nashorn.TestNashorn);
function generate()
{
function asd(variablex) { print('Hello, ' + variablex); }
var result = TestNashorn.test(asd);
}
The problem occurs in line JSObject som = ((JSObject)o1);, although I can successfully import jdk.nashorn.api.scripting.JSObject;.
The exception message exactly says:
jdk.nashorn.api.scripting.JSObject cannot be found by com.test.nashorn_1.0.0.qualifier
So.. I got to fix my issue and was able to use JSObject in my code. What I have done was the following:
Added -Dorg.osgi.framework.bundle.parent=ext to myproduct.product file
This added it to the .ini file in my product build which revealed the classes found in Nashorn APIs.

Could not find or load main class FaceDetect in java with angus.ai

I get the following error when I try to run
java -cp 'angus-sdk-java-0.0.2-jar-with-dependencies.jar:.' FaceDetect
I am following a tutorial for face detection in http://angus-doc.readthedocs.io/en/latest/getting-started/java.html . Below is my java code,
import java.io.IOException;
import org.json.simple.JSONObject;
import ai.angus.sdk.Configuration;
import ai.angus.sdk.Job;
import ai.angus.sdk.ProcessException;
import ai.angus.sdk.Root;
import ai.angus.sdk.Service;
import ai.angus.sdk.impl.ConfigurationImpl;
import ai.angus.sdk.impl.File;
public class FaceDetect {
public static void main(String[] args) throws IOException, ProcessException {
Configuration conf = new ConfigurationImpl();
Root root = conf.connect();
Service service = root.getServices().getService("age_and_gender_estimation", 1);
JSONObject params = new JSONObject();
params.put("image", new File("Downloads/IMG_1060.jpg"));
Job job = service.process(params);
System.out.println(job.getResult().toJSONString());
}
}
I don't understand the problem with it. I have tried all the answers in the stack overflow but nothing is working for me.
remove the single qoutes around the classpath:
java -cp angus-sdk-java-0.0.2-jar-with-dependencies.jar:. FaceDetect

IBM Watson TextToSpeech examples do not accept AUDIO_WAV as contentType

Trying to run RecognizeUsingWebSocketsExample provided with IBM Watson SpeechToText Java SDK, but it's failing to create a valid RecognizeOptions object for the sample .wav file provided with the distribution:
Exception in thread "main" java.lang.IllegalArgumentException: When using PCM the audio rate should be specified.
at com.ibm.watson.developer_cloud.util.Validator.isTrue(Validator.java:38)
at com.ibm.watson.developer_cloud.speech_to_text.v1.RecognizeOptions$Builder.contentType(RecognizeOptions.java:95)
at com.ibm.watson.developer_cloud.speech_to_text.v1.RecognizeUsingWebSocketsExample.main(RecognizeUsingWebSocketsExample.java:30)
It appears that the contentType(HttpMediaType.AUDIO_WAV) is being misinterpreted as RAW. Here's the actual (unmodified from distro) code:
package com.ibm.watson.developer_cloud.speech_to_text.v1;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import com.ibm.watson.developer_cloud.http.HttpMediaType;
import com.ibm.watson.developer_cloud.speech_to_text.v1.model.SpeechResults;
import com.ibm.watson.developer_cloud.speech_to_text.v1.websocket.BaseRecognizeCallback;
/**
* Recognize using WebSockets a sample wav file and print the transcript into the console output.
*/
public class RecognizeUsingWebSocketsExample {
private static CountDownLatch lock = new CountDownLatch(1);
public static void main(String[] args) throws FileNotFoundException, InterruptedException {
SpeechToText service = new SpeechToText();
service.setUsernameAndPassword("<username>", "<password>");
FileInputStream audio = new FileInputStream("src/test/resources/speech_to_text/sample1.wav");
RecognizeOptions options = new RecognizeOptions.Builder()
.continuous(true)
.interimResults(true)
.contentType(HttpMediaType.AUDIO_WAV)
.build();
service.recognizeUsingWebSocket(audio, options, new BaseRecognizeCallback() {
#Override
public void onTranscription(SpeechResults speechResults) {
System.out.println(speechResults);
if (speechResults.isFinal())
lock.countDown();
}
});
lock.await(1, TimeUnit.MINUTES);
}
}
I'm using 3.0.0-RC2 snapshot. No problems running examples which do not use RecognizeOptions, like SpeechToTextExample. Thx.
-rg
Sorry, false alarm. I recreated the example project from scratch and it compiled and ran without a hitch. Must have been some weirdness with my Eclipse setup.

Missing scheme (IllegalArgumentException) while using java.nio.file.Paths interface

this is a really simple java question. I am using Java 8 with eclipse kepler on a linux system. I've been trying to try out NIO.2. My code is:
package lucasTest;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.*;
public class Lucas {
public static void main(String[] args) throws URISyntaxException{
URI u = new URI("./Lucas.java");
Path p = Paths.get(u);
}
}
I get the following error:
Exception in thread "main" java.lang.IllegalArgumentException: Missing scheme
at java.nio.file.Paths.get(Paths.java:134)
at lucasTest.Lucas.main(Lucas.java:10)
Please help!
Thanks,
Lucas
Your uri declaration is missing the scheme for files (file:///):
u = new URI("file:///./Lucas.java");
Path p = Paths.get(u);
should work. As an alternative you can try
Path p2 = Paths.get(".", "Lucas.java");

Categories

Resources