Get string with translation from Google translate - java

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();

Related

e.getMessage().getContentDisplay() returns empty String

I'm learning jda and I coded my discord bot so that console send the message that I sent, but after executing this code, I send a random message in my test discord server, the console just prints nothing. Is anything wrong with my code? I also tried e.getMessage().getContentRaw(), but it returns same result.
Main Class
package net.lib.first;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.entities.Activity;
import net.dv8tion.jda.api.entities.Message;
import net.lib.first.event.Listener;
import javax.security.auth.login.LoginException;
public class Main {
public static void main(String[] args) throws LoginException {
String token = (my bot token);
JDABuilder builder = JDABuilder.createDefault(token);
builder.addEventListeners(new Listener());
builder.setActivity(Activity.playing("Type !ping"));
builder.build();
Message.suppressContentIntentWarning();
}
}
Listener Class
package net.lib.first.event;
import net.dv8tion.jda.api.events.message.MessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;
import org.jetbrains.annotations.NotNull;
public class Listener extends ListenerAdapter {
#Override
public void onMessageReceived(#NotNull MessageReceivedEvent e) {
System.out.println(e.getMessage().getContentDisplay());
}
}
Solved the problem, I didn't add the method enableIntents(GatewayIntent.MESSAGE_CONTENT) to builder.
I have the same problem, but there is no option to enable GatewayIntent.MESSAGE_CONTENT
only:
[...]
builder.createDefault("xxx")
.setActivity(Activity.playing("!help") )
.setStatus(OnlineStatus.ONLINE)
.addEventListeners(new CommandListener() )
.addEventListeners(new VoiceListener() )
.enableIntents(GatewayIntent.GUILD_MESSAGES)
.enableIntents(GatewayIntent.DIRECT_MESSAGES)
.build();
[...]
I have enabled the above ones.

How to load all the examples in to the #ExampleObject without specifying the ref so its visible in SwaggerUI?

I am developing a simple application where I would like to read the files from a remote URL and add them to the #ExampleObject. I am able to achieve this using CustomClass SchemaFileReader implements OASFilter but the only problem is that I need to manually specify the name of the file in the ref such as #ExampleObject(name = "Example1", ref = "Example1.json").
Since I am reading the URL there can be many files and I do not know the name of all the files so I need an approach where I can add the #ExampleObject dynamically directly without specifying ref. Rather it should read all the data from the examples. Can someone please specify some logic on how to achieve this?
I have posted my complete code on GitHub: https://github.com/Aravinda93/code-with-quarkus.
As of now, I have added manually 2 files to my #ExampleObject by specifying the ref but I need a dynamic approach to add all the 3 files present in the resourses/jsonfiles without providing the ref for all the files individually.
To run the application, please follow the following steps:
Open the terminal for the project and run mvn compile quarkus:dev
Press d in the command line this should open the Swagger-UI.
Select swagger-ui from SmallRye OpenAPI
Expand api/generate and there we will see only 2 files under examples. I need an approach to get all 3 field without specifying the ref for all of them.
After trying some things, finally, this worked for me. Posting here as it can be useful to someone in the future:
Following is my RestControllerResponse:
import org.eclipse.microprofile.openapi.annotations.media.Content;
import org.eclipse.microprofile.openapi.annotations.parameters.RequestBody;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.Map;
#Path("/api")
public class RestControllerResponse {
#Path("/generate")
#POST
#Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
#Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
#RequestBody(description = "Testing Example without ref",
content = #Content())
public String generator(final Map<String, Object> input) throws Exception {
return "Hello From Generator Method";
}
}
Following is my SchemaFileReader which has the capability to read all files and respective subfolder with files and get the file contents and add to examples, pass the required URL to the getFolderData method:
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.eclipse.microprofile.openapi.OASFactory;
import org.eclipse.microprofile.openapi.OASFilter;
import org.eclipse.microprofile.openapi.models.Components;
import org.eclipse.microprofile.openapi.models.OpenAPI;
import org.eclipse.microprofile.openapi.models.examples.Example;
import org.json.JSONArray;
import org.json.JSONObject;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
public class SchemaFileReader implements OASFilter {
private final ObjectMapper objectMapper = new ObjectMapper();
private final CloseableHttpClient httpClient = HttpClients.createDefault();
#Override
public void filterOpenAPI(OpenAPI openAPI) {
Components defaultComponents = OASFactory.createComponents();
if (openAPI.getComponents() == null) {
openAPI.setComponents(defaultComponents);
}
try {
//generateExamples().forEach(openAPI.getComponents()::addExample);
generateExamples().entrySet().forEach(ex -> openAPI.getPaths().getPathItem("/api/generate").getPOST().getRequestBody().getContent().getMediaType(MediaType.APPLICATION_JSON).addExample(ex.getKey(), ex.getValue()));
} catch (Exception e) {
e.printStackTrace();
}
}
Map<String, Example> generateExamples() throws Exception {
final Map<String, Example> examples = new LinkedHashMap<>();
getFolderData(examples, "PLACE YOUR URL HERE");
//getExamples(examples);
return examples;
}
//If user has provided the folder then recursively loop over it to get the files and their contents
private void getFolderData(final Map<String, Example> examples, final String inputURL) throws IOException {
//Make the request to provided folder path and get the folder/files from it.
final CloseableHttpResponse folderResponse = httpClient.execute(new HttpGet(inputURL));
final String responseBody = EntityUtils.toString(folderResponse.getEntity(), StandardCharsets.UTF_8);
//If the folder API request provides valid response and contains the list of files or folders then loop over it else its plain/text with direct contents
if (folderResponse.getStatusLine().getStatusCode() == 200 && ContentType.get(folderResponse.getEntity()).toString().equalsIgnoreCase("application/json; charset=utf-8")) {
final JSONArray jsonArray = new JSONArray(responseBody);
jsonArray.forEach(item -> {
final JSONObject obj = (JSONObject) item;
if (obj.getString("type").equalsIgnoreCase("file")) {
//Make request to each file in the GitHub folder and obtain its contents
try {
final CloseableHttpResponse fileResponse = httpClient.execute(new HttpGet(obj.getString("download_url")));
//If the response code is 200 then add the contents to Example
if (fileResponse.getStatusLine().getStatusCode() == 200) {
final String fileResponseBody = EntityUtils.toString(fileResponse.getEntity(), StandardCharsets.UTF_8);
if (obj.getString("download_url").contains(".json")) {
examples.put(obj.getString("name"), OASFactory.createExample().value(objectMapper.readValue(fileResponseBody, ObjectNode.class)));
} else if (obj.getString("download_url").contains(".xml")) {
examples.put(obj.getString("name"), OASFactory.createExample().value(fileResponseBody));
}
}
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
getFolderData(examples, obj.getString("url"));
} catch (IOException e) {
e.printStackTrace();
}
}
});
} else if (folderResponse.getStatusLine().getStatusCode() == 200 && ContentType.get(folderResponse.getEntity()).toString().equalsIgnoreCase("text/plain; charset=utf-8")) {
//if direct file provided then add its content
examples.put(inputURL.substring(inputURL.lastIndexOf("/")), OASFactory.createExample().value(objectMapper.readValue(responseBody, ObjectNode.class)));
}
}
}

How to fetch discussion for a given defect using the Java Rally API

I am trying to determine how to extract the discussion data for a defect in Rally using the Java Rally API. Unfortunately I can find no help online or in the documentation that tells me how to do this. I am able to obtain the URL to the discussion data and return it as a JSON element but I am not sure how to take the final step of querying that URL to get the discussions as another JSON object - I'd really appreciate help!
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.rallydev.rest.RallyRestApi;
import com.rallydev.rest.request.*;
import com.rallydev.rest.response.*;
import com.rallydev.rest.util.Fetch;
import com.rallydev.rest.util.QueryFilter;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class ExtractDiscussions
{
public static void main(String args[]) throws URISyntaxException, IOException {
RallyRestApi restApi = new RallyRestApi(new URI("https://rally1.rallydev.com"), "myApiKey");
restApi.setApplicationName("DANA Example");
restApi.setProxy(new URI("myProxy"),"myUsername","myPassword");
try {
QueryRequest defectRequest = new QueryRequest("defect");
defectRequest.setQueryFilter(new QueryFilter("FormattedID","=","DE123456"));
defectRequest.setFetch(new Fetch());
//defectRequest.setPageSize(25);
//defectRequest.setLimit(100);
QueryResponse queryResponse = restApi.query(defectRequest);
System.out.println(queryResponse.getTotalResultCount());
JsonObject obj = queryResponse.getResults().get(0).getAsJsonObject();
obj = obj.getAsJsonObject("Discussion");
JsonElement discussionLink = obj.get("_ref");
System.out.println(discussionLink);
//Code would go here to fetch the discussion using the discussion link
}finally{
restApi.close();
}
}
}
My Results:
1
"https://rally1.rallydev.com/slm/webservice/v2.0/Defect/1321234562/Discussion"
If you do a GetRequest on that URL, you will be given back the collection of Conversation Posts. Handy tips are in here: https://rally1.rallydev.com/slm/doc/webservice/

Testing URL and URLConnection

I don't know how should I test this without really taking connection to real url to server.
I have read few articles about using Mockito in this kind of situation and tried to search around, but can not find good tutorial or advices how should I make jUnit-test for URL and URLConnection in my project.
Here is the code that I have problems when trying to test it:
public JSONObject getJSONObj()
throws MalformedURLException, IOException, ParseException {
String jsonString;
try (InputStream is = getURLConnection("RealUrlStringGoesHere").getInputStream();) {
jsonString = IOUtils.toString(is);
}
return (JSONObject) JSONValue.parseWithException(jsonString);
}
public URLConnection getURLConnection(String urlStr) throws MalformedURLException, IOException {
URL url = new URL(urlStr);
URLConnection conn = url.openConnection();
return conn;
}
Here is also used imports I use for these, if someone wants to know:
import java.net.URLConnection;
import org.apache.commons.io.IOUtils;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.ParseException;
EDITED
Thanks for you answers, but it seems that I'm totally lost with this. Maybe I'm trying to think too complicated, but unit testing is pretty new stuff for me, but really want to learn it more.
Yes, I try to test getJSONObj-method, but those URL & URLConnection is making it difficult for me to understand how to test my method by "faking" it to believe it really takes connection.
Can't realize what you really mean, so here is the current code when I tried to do as you said Jeff Bowman. (Still using that big String, because I tried to get it first done with the current style and then get better performance with Reader's after this is working.)
Discusser.java
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import org.apache.commons.io.IOUtils;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.ParseException;
public class Discusser implements URLOpener {
public JSONObject getJSONObj() throws IOException, ParseException {
String jsonString;
try (InputStream is = openURL("RealUrlStringGoesHere");) {
jsonString = IOUtils.toString(is);
}
return (JSONObject) JSONValue.parseWithException(jsonString);
}
#Override
public InputStream openURL(String urlStr) throws IOException {
URL url = new URL(urlStr);
URLConnection urlConnection = url.openConnection();
return urlConnection.getInputStream();
}
}
URLOpener.java
import java.io.IOException;
import java.io.InputStream;
public interface URLOpener {
InputStream openURL(String urlStr) throws IOException;
}
This test is almost useless to show, because I think it's totally wrong how I try to use the mock. (It's returning null when discusser.getJSONObj())
DiscusserTest.java
import static org.junit.Assert.assertEquals;
import java.io.ByteArrayInputStream;
import org.json.simple.JSONObject;
import org.junit.Test;
import org.mockito.Mockito;
public class DiscusserTest {
#Test
public void testGetJSONObj() throws Exception {
JSONObject expectedJSONObject = createExpected();
ByteArrayInputStream inputForMock = new ByteArrayInputStream(generateJSONString().getBytes("UTF-8"));
// Should I mock like this or...
Discusser discusser = Mockito.mock(Discusser.class);
Mockito.when(discusser.openURL("asd")).thenReturn(inputForMock);
//
assertEquals(expectedJSONObject, discusser.getJSONObj());
}
private String generateJSONString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("\"id\":\"123\",");
sb.append("\"name\":\"test\"");
sb.append("}");
return sb.toString();
}
#SuppressWarnings("unchecked")
private JSONObject createExpected() {
JSONObject obj = new JSONObject();
obj.put("id", 123);
obj.put("name", "test");
return obj;
}
}
Could you or someone else give guidance / example how getJSONObj()-method in Discusser should be tested?
You could start a server within your test and test against this server. You can use MockServer for this.
I managed to get it working and here are the results. If you have improving ideas or other suggestions, I'm very pleased to have them.
I added setter for URLOpener in Discusser, so then I can put that mocked one there quite easily.
Discusser.java
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.ParseException;
public class Discusser implements URLOpener {
private URLOpener urlOpener;
public JSONObject getJSONObj() throws IOException, ParseException {
JSONObject jsonObj;
try (InputStream is = openURL("RealUrlStringGoesHere");) {
jsonObj = (JSONObject) JSONValue.parse(new InputStreamReader(is));
}
return jsonObj;
}
#Override
public InputStream openURL(String urlStr) throws IOException {
return urlOpener.openURL(urlStr);
}
public void setURLOpener(URLOpener urlOpener) {
this.urlOpener = urlOpener;
}
}
DiscusserTest.java
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import org.json.simple.JSONObject;
import org.junit.Test;
public class DiscusserTest {
#Test
public void testGetJSONObj() throws Exception {
Discusser discusser = new Discusser();
discusser.setURLOpener(createMockURLOpener());
assertEquals(createExpected(), discusser.getJSONObj());
}
private URLOpener createMockURLOpener() throws IOException {
URLOpener mockUrlOpener = mock(URLOpener.class);
ByteArrayInputStream input = new ByteArrayInputStream(generateJSONString().getBytes("UTF-8"));
when(mockUrlOpener.openURL("RealUrlStringGoesHere")).thenReturn(input);
return mockUrlOpener;
}
private String generateJSONString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
sb.append("\"id\":\"123\",");
sb.append("\"name\":\"test\"");
sb.append("}");
return sb.toString();
}
#SuppressWarnings("unchecked")
private JSONObject createExpected() {
JSONObject obj = new JSONObject();
obj.put("id", "123");
obj.put("name", "test");
return obj;
}
}
URLOpener.java
import java.io.IOException;
import java.io.InputStream;
public interface URLOpener {
InputStream openURL(String urlStr) throws IOException;
}
What are you trying to test?
If you're trying to test that interactions happen correctly with the real server, then no amount of mocking will help you. You'd want to write an integration test.
If you're trying to test that interactions happen through Java's URLConnection, then a mock server might work the way Stefan Birkner describes. I don't think that's necessarily a useful thing, though, as the Java URLConnection framework is exceedingly well-tested third-party code.
It looks like the component that is most testable here is getJSONObj(), where the part that is not so testable is the function that turns a URL into an InputStream. Make that your interface, instead:
interface URLOpener {
InputStream openURL(String url);
}
At that point, you can use a very simple real implementation in your production code, or pass in a dead-simple mock that returns a ByteArrayInputStream.
Side note: You may find you have better performance if you use JSONValue.parse(Reader) instead of trying to construct one big String containing the entire JSON file. This wouldn't interfere with mocking, as you could just use StringReader instead.
/* in prod, within your actual URLOpener */
return new InputStreamReader(urlConnection.getInputStream());
/* in test, for your mock URLOpener */
when(mockUrlOpener.openURL(expectedURL)).thenReturn(new StringReader(testJSON));
JSONValue value = JSONValue.parse(new BufferedReader(readerFromUrl));

Parsing nested JSON nodes to POJOs using Google Http Java Client

For example I have a response with the following JSON:
{
response: {
id: 20,
name: Stas
}
}
And I want to parse it to the following object:
class User {
private int id;
private String name;
}
How to skip the response node?
I use Google Http Java Client and it will be good if someone will answer how to do it there.
How will this lines have changed?
request.setParser(new JacksonFactory().createJsonObjectParser());
return request.execute().parseAs(getResultType());
You can now implement this in one step:
new JsonObjectParser.Builder(jsonFactory)
.setWrapperKeys(Arrays.asList("response"))
.build()
http://javadoc.google-http-java-client.googlecode.com/hg/1.15.0-rc/index.html
I do not know the Google Http Java Client, but if you can access the Jackson ObjectMapper you could do the following:
1.) Enable root unwrapping:
objectMapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
2.) Add annotation to User.class:
#JsonRootName("response")
class User {
…
}
I hope you can use this approach.
Edit: I dug through the google-http-java-client API and have come to the conclusion that you cannot access the ObjectMapper directly. In order to use the full power of Jackson you would have to write your own implementation of JsonObjectParser to wrap a 'real' Jackson parser. Sorry about that, maybe someone else could come up with a better solution.
I didn't find a native way (for this library) to solve my task. As a result I solved this problem by extending the functionality of JsonObjectParser. It entails expanding of the JacksonFactory, but it's a final class, so I used aggregation.
I wrote the following classes:
JacksonFilteringFactory
import com.google.api.client.json.JsonObjectParser;
import com.google.api.client.json.jackson2.JacksonFactory;
public class JacksonFilteringFactory {
private final JacksonFactory factory = new JacksonFactory();
public JsonObjectParser createJsonObjectParser(String filteringNode) {
return new FilteringJsonObjectParser(factory, filteringNode);
}
}
FilteringJsonObjectParser
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.JsonObjectParser;
import com.vkredmessenger.AppController;
import com.vkredmessenger.util.StringUtils;
public class FilteringJsonObjectParser extends JsonObjectParser {
private String mFilteringNode;
public FilteringJsonObjectParser(JsonFactory jsonFactory,
String filteringNode) {
super(jsonFactory);
mFilteringNode = filteringNode;
}
#Override
public Object parseAndClose(InputStream in,
Charset charset, Type dataType)
throws IOException {
String originalResponse =
StringUtils.convertStreamToString(in, charset);
String response = null;
try {
JSONTokener tokener = new JSONTokener(originalResponse);
JSONObject originalResponseObject =
(JSONObject) tokener.nextValue();
JSONObject responseObject =
originalResponseObject.getJSONObject(mFilteringNode);
response = responseObject.toString();
} catch (JSONException e) {
e.printStackTrace();
}
InputStream filteredIn =
new ByteArrayInputStream(response.getBytes(charset));
return super.parseAndClose(filteredIn, charset, dataType);
}
}
So, for example from my question, the result parsing code will be the following:
request.setParser(new JacksonFilteringFactory().createJsonObjectParser("response"));
return request.execute().parseAs(getResultType());

Categories

Resources