Translating using Google Translate API - java

I want to use the following code as the basis for a program that translates user input to English. I am getting the error "cannot find symbol - GoogleApi." Can someone please help me figure out what to do?
import com.google.api.translate.Language;
import com.google.api.translate.Translate;
public class Main {
public static void main(String[] args) throws Exception {
// Set the HTTP referrer to your website address.
GoogleAPI.setHttpReferrer(/* Enter the URL of your site here */);
// Set the Google Translate API key
// See: http://code.google.com/apis/language/translate/v2/getting_started.html
GoogleAPI.setKey(/* Enter your API key here */);
String translatedText = Translate.DEFAULT.execute("Bonjour le monde", Language.FRENCH, Language.ENGLISH);
System.out.println(translatedText);
}
}

what is exactly GoogleApi?
You have not declared that, in order to use it .. I did not understand the program fully, I suggest that you search the website or through google for a program to do that task, there are plenty.

A working code can be found here. It also has link to full codebase on github.
Things to keep in mind:
If you are behind proxy you need make jvm aware of this. One way of doing it is through a static initializer as below:
static
{
System.setProperty("http.proxyHost", HTTP_PROXY_HOST);
System.setProperty("http.proxyPort", HTTP_PROXY_PORT);
System.setProperty("https.proxyHost", HTTPS_PROXY_HOST);
System.setProperty("https.proxyPort", HTTPS_PROXY_PORT);
}
In Run configuration make your GOOGLE_API_KEY available by making it environment variable as below:
For setting up of API key Check section titled "Setting up an API Key".

Related

In Java, how do I extract the domain of a URL?

I'm using Java 8. I want to extract the domain portion of a URL. Just in case I'm using the word "domain" incorrectly, what i want is if my server name is
test.javabits.com
I want to extract "javabits.com". Similarly, if my server name is
firstpart.secondpart.lastpart.org
I want to extract "lastpart.org". I tried the below
final String domain = request.getServerName().replaceAll(".*\\.(?=.*\\.)", "");
but its not extracting the domain properly. Then I tried what this guy has in his site -- https://www.mkyong.com/regular-expressions/domain-name-regular-expression-example/, e.g.
private static final String DOMAIN_NAME_PATTERN = "^((?!-)[A-Za-z0-9-]{1,63}(?<!-)\\.)+[A-Za-z]{2,6}$";
but that is also not extracting what I want. How can I extract the domain name portion properly?
Summary: Do not use regex for this. Use whois.
If I try to extrapolate from your question, to find out what you really want to do, I guess you want to find the domain belonging to some non-infrastructural owner from the host part of a URL. Additionally, from the tag of your question, you want to do it with the help of a regex.
The task you are undertaking is at best impractical, but probably impossible.
There are a number of corner cases that you would have to weed out. Apart from the list of infrastructural domains kindly provided by Lennart in https://publicsuffix.org/list/public_suffix_list.dat, you also have the cases of an empty host field in the URL or an IP-address forming the host part.
So, is there a better approach to this? Of course there is. What you do want to do is query a public database for the data you need. The protocol for such queries is called WHOIS.
Apache Commons provide an easy way to access WHOIS information in the WhoisClient. From there you can query the domain field, and find some more information that may be useful to you.
It shouldn't be harder than
import org.apache.commons.net.whois.WhoisClient;
import java.io.IOException;
public class CommonsTest {
public static void main(String args) {
WhoisClient c = new WhoisClient();
try {
c.connect(WhoisClient.DEFAULT_HOST);
System.out.println(c.query(URL));
c.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Using this will get you the whois information aboutt he domain you are asking for. If the domain is uregistered, that is, is a private domain, as in the case of www.stackexchange.com you will get an error saying no domain is registered. Remove the first part of the address and try again. Once you found the registered domain, you will also find the registrar and the registrer.
Now, unfortunately, whois is not as simple as one would think. Read further on https://manpages.debian.org/jessie/whois/whois.1.en.html for an elaboration on how to use it and what information you can expect from different sources.
Also, check related questions here.
try it like this:
String parts[] = longDomain.split(".");
String domain = parts[parts.length-2] + "." + [parts.length -1];

Serenity + Rest services

I am trying to demo serenity with Restassured at my workplace here and show them how awesome and easy it is to use in comparison to using jasmine.js
How ever I am stuck with few things in the basic test I am trying to do
My test says
Given we have valid credentials for the client using this test
When we try to serach for a medicine '<medicine>'
Then we get a valid '<perfLabel>' response with search results
|medicine|perflabel|
|Salbutamol|perflabel1|
|Panadol|perflabel2|
|Salbutamol (GA)|perflabel3|
When I go into the next step
#When("we try to serach for a medicine '(.*)' ")
public void tryToSearchUsingEquals(String medicine)
{
tsApiActions.requestServiceSearchWhichEquals(medicine);
}
In my Step method
#Step
public void requestServiceSearchWhichEquals(String medicine)
{
host = "http://www.int.abc.com.au/api/cs/v1/terminology-service/trade-product/search-summary?offset=0&limit=20&prefLabel=eq "+medicine+"&sort=prefLabel DESC&cache=false";
requestSend(host);
}
The questions I have are
How do i inject the variables(Salbutamol, Panadol) into the uri?
How do I put this URI into a seperate properties file and call it in the Step method?
Any help is really appreciated
Thanks
RestAssured requests follow the same code structure which should be added into your sendRequest method:
given().
param("prefLabel", medicine).
when().
get(URL).
then().
body(containsString(medicine));
URL can come from property file, but you need to create a method to upload it before test run and then you have to create a getPropety() method to get the current value you need.
I suggest to read the official documentation here:
https://github.com/rest-assured/rest-assured

Processing 2: Posting to Facebook error "The type Post is ambiguous"

Using Processing and the Temboo library to update a status to Facebook but I am encountering the following error: "The type Post is ambiguous" with this line seeming to be the highlighted cause "Post postChoreo = new Post(session);". Any advice on how to resolve this would be excellent.
import com.temboo.core.*;
import com.temboo.Library.Facebook.Publishing.*;
// Create a session using your Temboo account application details
TembooSession session = new TembooSession("dylabaloo", "myFirstApp",
"xxxxxxxxxxxxxxxxxxxx");
void setup() {
// Run the Post Choreo function
runPostChoreo();
}
void runPostChoreo() {
// Create the Choreo object using your Temboo session
Post postChoreo = new Post(session);
// Set inputs
postChoreo.setAccessToken("xxxxxxxxxxxxxxxxxx");
postChoreo.setMessage("Your High Score is:");
// Run the Choreo and store the results
PostResultSet postResults = postChoreo.run();
// Print results
println(postResults.getResponse());
}
Just looking at the code and the error you are getting, i guess that Post class could exist in both com.temboo.core.* package and also in com.temboo.Library.Facebook.Publishing.* package or in the same package, where you wrote your class.
I guess you are trying to use Facebook publishing Post so you should import Post as the following to avoid ambiguity.
import com.temboo.Library.Facebook.Publishing.Post;
It is not a good idea to import using wildcards. One, you will run into such issues because same class names could be existing in multiple packages imported using wildcards. Second, it is just too much un-necessary classes imported. Third, It is just not a good coding practice.
Most IDEs, especially all eclispe based IDEs, provide easy shortcuts to organize imports (like Ctrl-Shift-O for windows), which can help you organize your imports and avoid such issues.

Java -how can I open URL and insert the URL user and password?

I want to learn how to:
Step1: open URL – for example Gmail
Step 2: insert user and password and press sign-in.
How can I inset user and password and press the sign-in button?
Do I need/must use selenium?
This code is only for open the browser(step 1)
import java.io.IOException;
public class Website
{
public void openWebsite() //throws IOException
{
try
{
#SuppressWarnings("unused")
Process p = Runtime.getRuntime().exec("cmd /c start http://accounts.google.com/ServiceLogin ");
}
catch (IOException e1)
{
System.out.println(e1);
}
}
}
First you need to open the URL. Right now you are actually not opening the URL. You are asking the Windows operating system "What would you do with http://accounts.google.com/ServiceLogin?"
Because it is windows, it will make a guess, which sort of follows this line of logic:
it sort of looks like a URL, so I'll fire up explorer and
ask explorer to do something with it.
Which means that your code is now a few programs away from being able to get the data, and none of the intermediate programs will (because they're not built to do so), transmit the need for input into your program.
What you need to do is to avoid asking other programs to open the URL, it's just too problematic. First, they might get it wrong, second they'll never know how to ask you the input. To open a URL directly:
import java.net.URL;
... somewhere in the code ...
URL url = new URL("http://accounts.google.com/ServiceLogin");
InputStream in = url.openStream();
do some googling on various java.net.URL tutorials, and you will soon find the right combination of techniques needed to handle your particular credential challenge. Here's one resource, but it seems you need to do a bit of homework before what they say will make sense to you. If you stumble, at least you'll have a better, more specific question to ask the next time around (and don't forget to post your source code).

Searching a key word with java client programme from wsdl

Heyy I have a problem
I generated a client programme using http://api.search.live.net/search.wsdl this service for searching a key words..
I generated client by help of Eclipse-web project from this service.
I have done searched on this service(live.net) but ı can't show on the console. How ı can do that?
public static void main(String[] args) throws RemoteException {
LiveSearchPortTypeProxy bb=new LiveSearchPortTypeProxy();
SearchRequest request=new SearchRequest();
SearchRequestType1 bbs=new SearchRequestType1();
aas.setParameters(request);
sorgu.setAppId("*****************************************"); //you can take this ID from live service for using this service
sorgu.setSources(new SourceType[]{SourceType.Web});
sorgu.setQuery("keyword");
SearchResponseType0 cevap= bb.search(bbs);
}
Have a look at the cevap variable and its public get methods in a debugger, and see what you have.
You will most likely end up with an instance of org.w3c.Node which represents the root of the parsed response. This can then be treated like any other DOM tree.

Categories

Resources