I'm a newbie to Java and Watson Conversation. Is this possible to add images to Watson Conversation response? I want to add an image to Watson Conversation I made a Chatbot on Watson Conversation and integrated it with Facebook as Java web application.I want to add images in Watson response.
public class TestConversation {
public static void main(String[] args) {
BufferedReader br = null;
MessageResponse response = null;
Map context = new HashMap();
try {
br = new BufferedReader(new InputStreamReader(System.in));
String userName = br.readLine();
// Add userName to context to be used by Conversation.
context.put("userName", userName);
while (true) {
String input = br.readLine();
response = conversationAPI(input, context);
System.out.println("Watson Response: " + response.getText().get(0));
context = response.getContext();
System.out.println("———–");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static MessageResponse conversationAPI(String input, Map context) {
ConversationService service = new ConversationService(ConversationService.VERSION_DATE_2016_07_11);
// Credentials of Workspace of Conversation
service.setUsernameAndPassword("******************", "****************");
MessageRequest newMessage = new MessageRequest.Builder().inputText(input).context(context).build();
// Workspace ID of Conversation current workspace
String workspaceId = "******************";
MessageResponse response = service.message(workspaceId, newMessage).execute();
return response;
}
}
Watson conversation is just text that is sent back. So it is up to your application to render the image.
If you use the conversation simple application, you can use HTML to render. For example, set the output text to the following value.
Here is a picture of a tiger:<br><img src="https://upload.wikimedia.org/wikipedia/commons/0/01/Tiger.25.jpg">
When you display that text in conversation simple it will show the following:
Another option is you can store the image within conversation by saving as base64 format. However you have a limit of 10MB on a conversation file, so it's unlikely to be useful except for small icons.
Example:
Smile: <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPAAAADwCAYAAAA+VemSAAAABmJLR0QA/wD/AP+gvaeTAAAgAElEQVR4nO3deXxU5b0/8M/3nJlsk52EbBNkR4ggq1ogIK64oai4tlqtS6tW21qq16tW6a+KXmzdqt57UYt1u1ZURGkVNZAEhAquBQXZJAtJSCDrzGTmnPP9/RGWAElmJpmZM2fyfb9evoTMmTPfDPOZ5znPec55ACGEEEIIIYQQQgghhBBCCCGEEEIIIYQQQgghhBBCCCGEEEIIIYQQQoQcmV2A8I/XOjPh03M0UgcSGfkEJRvgFM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i5IPCanIG6YZsNxvkAZgNIMbsmYWluAGuI6T0Fxls0s7rC7IKCYbkAd8ZrnYmabkyDgQuIaC6AQrNrEhbAqAXhQxCWq5r3H93dstUKLB3go3nXFIxXDZzHjHMATIEcN4sOXgCfEeEfuoL346ZVfWl2QaESUwHujNc6EzXDmKSwMo2ZpwMoBpBmdl0iIlwAvmDmcij4yKYqa2hqpdvsosIhZgN8NH4Dqi8vb7xqqNOZeBqA0wAMMLsuERItANYz0xooRrmtJamMzt3WLxYk6DcBPhozFJTlHq+zbQITxhN4AjoutpAZYdFtH4AvGPQFMb5QoX+BGXu2HFyxvr/ptwHuDpcX5uusT2JDmUTEYxhURODRkPfKDHsAbGLmzaTQRp3UjXHTdm+OpokUZpMPZQC4JD9LUzGKQCMYGEHACGKMYMJwAMlm12dxrcTYxoTvGfiegO+ZeavNwFaaVV1vdnHRTgLcR1xemK8ZPIKAjnATD4eBfACFIORArrbygVEHoAIKqplpG6EjrDaFvqfpFdVmF2hlEuAw6jjOPi7HB1+eQpRPBgoMUB6RUQBQHgFO7hhIS4P1JqS0AGgioIGBSoD3MCtVioJqBlcbzNV2Pa4ap+6qlS5v+EiAowS/ARVOZxp0Jd3HWjoZlEYqpYM5jZjSQEaaAUonhgMAQLDjcPedAKR32l0qgdQj9g/WATR3+lEjcChYrWD4AIAJrQq4Caw0MXETwI1sUBMr3GQnWyNUoxE/qmzsr4NGQgghhBBCCCGEEEIIIYQQQgghhBBCCCGEEEIIIYQQQgghhBBCCCGE6Af+P+HhSrt5F5C5AAAAAElFTkSuQmCC">
Related
I am new to server programming and websockets and I've learnt a little bit of Java 8 this year. In school we had a project where a client webpage opens your webcam, takes a photo of a barcode and then shows a photo and the nutritional value of said product. You can also just send a raw barcode number and that is what is done in this example
My side of the project was to implement a java websocket server (the backend) using the glassfish tyrus library, then receiving the number of the barcode in string format and making a request to openfoodfacts.org using their api. Finally I parsed the json file and sent it back as string format so the client app can read the string and show the correct information (product name, image url, etc)
My code is organized into two files, Serveur.java establishes a websocket server for the client to connect to and ProduitApi.java gets the information from openfoodfacts.org with the given barcode from the client.
public class Serveur {
#javax.websocket.server.ServerEndpoint(value = "/websocket")
public static class EndPoint {
#javax.websocket.OnClose
public void onClose(javax.websocket.Session session, javax.websocket.CloseReason close_reason) {
System.out.println("onClose: " + close_reason.getReasonPhrase());
}
#javax.websocket.OnError
public void onError(javax.websocket.Session session, Throwable throwable) {
System.out.println("onError: " + throwable.getMessage());
}
#javax.websocket.OnMessage
public void onMessage(javax.websocket.Session session, String message) {
System.out.println("Message from client: " + message);
//Creation du produit avec le message du client
try {
ProduitApi produit = new ProduitApi(message);
session.getBasicRemote().sendText(produit.print());
} catch (Exception e) {
e.printStackTrace();
}
}
#javax.websocket.OnOpen
public void onOpen(javax.websocket.Session session, javax.websocket.EndpointConfig ec) throws java.io.IOException {
System.out.println("OnOpen... " + ec.getUserProperties().get("Author"));
session.getBasicRemote().sendText("{\"Handshaking\": \"Yes\"}");
}
}
public static void main(String[] args) {
Server server;
server = new Server ("localhost", 8025, "/BetterFood", null, EndPoint.class);
try {
server.start();
System.out.println("--- server is running");
System.out.println(java.nio.file.FileSystems.getDefault().getPath("client") );
System.out.print("Please press a key to stop the server.");
java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
reader.readLine();
} catch (Exception e) {
e.printStackTrace();
} finally {
server.stop();
}
}
}
as you can see, when I receive the 'barcode' message, onMessage() gets called. There I instantiate an object of class ProduitApi to use the barcode to then return the information
This is my ProduitApi file without some unnecessary details
package com.gabi.serveur;
/**
*
* #author gabriel
*/
[imports]
public class ProduitApi {
private java.lang.String barcode;
final private java.net.URL url;
private java.net.URLConnection connection;
JsonObjectBuilder constructeur_objet = Json.createObjectBuilder();
String string_json;
ProduitApi(java.lang.String barcode)throws MalformedURLException, IOException {
this.barcode = barcode;
this.url = new java.net.URL("http://world.openfoodfacts.org/api/v0/product/" + this.barcode + ".json");
connection = url.openConnection();
stream();
}
public void stream() throws IOException{
if (connection != null) {
java.io.InputStreamReader response = new java.io.InputStreamReader(connection.getInputStream());
javax.json.stream.JsonParser parser=javax.json.Json.createParser(response);
while (parser.hasNext()) {
[parsing inputStream into JsonObject]
}
public String print()throws IOException{
string_json = constructeur_objet.build().toString();
System.out.print(string_json);
//FileWriter file = new FileWriter("serveur/src/main/java/com/gabi/serveur/json/final.json");
//file.write(string_json);
//file.close();
return string_json;
}
}
My problem comes from the last function ProduitApi.print() , it is supposed to return the parsed json in string form so I can send it via the sendText() as well as printing the result into my console so I can see if everything went right. As you can see there are somme commented lines; The FileWriter object that I had created was used with the purpose of writing said string to a file in my pc and let me check inside.
HOWEVER
and here is what I don't understand, If I uncomment those lines so that the print function can also write the file to my drive, The Connection Closes and then Opens again
It can be seen in the console where after printing the json string, it prints OnClose, followed by OnOpen Signaling the connection was reset for some reason.
If I remove the FileWriter section, the connection works normally, the client's connection stays open and he can make another request
End of Console Message after request:
...cuits x22 biscuits fourrés - 304g","qte":"304 g","img":"https://images.openfoodfacts.org/images/products/800/050/031/0427/front_fr.177.400.jpg"}onClose: OnOpen... null...
Finally, my question is just why writing to a file makes my program behave this way (resetting the connection). Does it have anything to do with how streams work?
I accidentally commented the filewriter portion when another Ide said it didn't find the file because I had opened the project from a different directory.
When I run the following code, the client mail service opens up with the To:, Subject:, Body: except the attachment which is highly needed. I couldn't figure out why the attachment is not adding into the mail.
public static void main(String[] args) throws FileNotFoundException, IOException {
final String HTML = "<h1>Hello</h1>"
+ "<p>This was created using iText</p>"
+ "<a href='hmkcode.com'>hmkcode.com</a>";
String filePath = "C:/Users/HP/Desktop/pdfTest/a.txt";
HtmlConverter.convertToPdf(HTML, new FileOutputStream(filePath, true));
Desktop desktop = Desktop.getDesktop();
try {
// Open user-default mai
// l client application.
String message = "mailto:username#domain.com?subject=New_Profile&body=see%20body%20content&attachment=" + filePath;
URI uri = URI.create(message);
desktop.mail(uri);
} catch (IOException e) {
e.printStackTrace();
}
SpringApplication.run(DemoApplication.class, args);
}
According to using mailto to send email with an attachment there is no support for attachments in mailto uri. And I, too, think that this is quite a logical behavior, for file access being extremly dangerous in a security point of view.
If possible add some code snippet. I have used Java for coding.
DSS: I would like to add multiple graphical image signature using CoSign Signature Soap API, how can I achieve it? If possible add some code snippet.
Here is a code sample in Java that demonstrates how to add a graphical signature using CoSign Signature SOAP API:
public static void AddGraphicalImage(String username, String domain, String password, byte[] imageBuffer, String imageName) throws Exception {
try {
SignRequest request = new SignRequest();
RequestBaseType.OptionalInputs optInputs = new RequestBaseType.OptionalInputs();
// Set signature type
optInputs.setSignatureType("http://arx.com/SAPIWS/DSS/1.0/set-graphic-image");
// Set user credentials
ClaimedIdentity claimedIdentity = new ClaimedIdentity();
NameIdentifierType nameIdentifier = new NameIdentifierType();
nameIdentifier.setValue(username);
nameIdentifier.setNameQualifier(domain);
CoSignAuthDataType coSignAuthData = new CoSignAuthDataType();
coSignAuthData.setLogonPassword(password);
claimedIdentity.setName(nameIdentifier);
claimedIdentity.setSupportingInfo(coSignAuthData);
optInputs.setClaimedIdentity(claimedIdentity);
// Set graphical image data
GraphicImageType graphicImage = new GraphicImageType();
graphicImage.setGraphicImage(imageBuffer);
graphicImage.setDataFormat(Long.valueOf(6)); //JPG
graphicImage.setGraphicImageName(imageName);
optInputs.setGraphicImageToSet(graphicImage);
request.setOptionalInputs(optInputs);
// Initiate service client
DSS client = new DSS(new URL("https://prime.cosigntrial.com:8080/sapiws/dss.asmx"));
// Send the request
DssSignResult response = client.getDSSSoap().dssSign(request);
// Check result
String errmsg = "" + response.getResult().getResultMajor();
if (errmsg.compareTo("urn:oasis:names:tc:dss:1.0:resultmajor:Success") == 0) {
System.out.println("Graphical image was added successfully!");
return;
}
else {
throw new Exception(response.getResult().getResultMessage().toString());
}
}
catch (Exception e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
I am taking some data from a database via a servlet and a db handler java class and hosting it at a url. Since the database is changing I'm taking care only to host the changes rather than the entire db data.
I'm getting the required functionality by a browser i.e after every (manual) reload, I'm getting the data as required by me,
1. at the first page load, entire data gets displayed.
2. at subsequent reloads, I get either null data if there is no change in the database, or the appended rows if the database extends. (the database can only extend).
But then in a java program, I'm not getting the same functionality. The java program using HttpUrlConnection.
This is the code for the java client for servlet...
public class HTTPClient implements Runnable {
private CallbackInterface callbackinterface;
private URL url;
private HttpURLConnection http;
private InputStream response;
private String previousMessage = "";
public HTTPClient() {
try {
url = new URL("http://localhost:8080/RESTful-Server/index.jsp");
http = (HttpURLConnection) url.openConnection();
http.connect();
} catch (IOException e) {
}
}
#Override
public void run() {
while (true) {
try {
String currentmessage = "";
response = http.getInputStream();
if (http.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader buffread = new BufferedReader(new InputStreamReader(response));
String line;
for (; (line = buffread.readLine()) != null;) {
currentmessage += line;
}
if ((!currentmessage.equals(previousMessage)
|| !previousMessage.equals(""))
&& !currentmessage.equals("")) {
//this.callbackinterface.event(currentmessage);\
System.out.println(currentmessage + "\t" + previousMessage);
}
previousMessage = currentmessage;
Thread.sleep(2500);
} else {
throw new IOException();
}
} catch (IOException | InterruptedException e) {
System.err.println("Exception" + e);
}
}
}
The shown class is a thread which read the connections every 2.5 s. If it gets something significant in the getline(), it will issue a callback to a worker method, which takes care of remaining things.
I am thinking the issues is because of the class variable conn, and that reload as in the browser is not getting replicated..
Any idea how to do this?
You're basically connecting (requesting) only once and trying to read the response multiple times, while it can be read only once. You basically need to create a new connection (request) everytime. You need to move the creation of the connection by url.openConnection() to inside the loop. The line http.connect() is by the way superfluous. You can safely omit it. The http.getInputStream() will already implicitly do it.
See also:
Using java.net.URLConnection to fire and handle HTTP requests
After reading: Getting the 'external' IP address in Java
code:
public static void main(String[] args) throws IOException
{
URL whatismyip = new URL("http://automation.whatismyip.com/n09230945.asp");
BufferedReader in = new BufferedReader(new InputStreamReader(whatismyip.openStream()));
String ip = in.readLine(); //you get the IP as a String
System.out.println(ip);
}
I thought I was a winner but I get the following error
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: http://automation.whatismyip.com/n09230945.asp
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.URL.openStream(Unknown Source)
at getIP.main(getIP.java:12)
I think this is because the server isnt responding quick enough, is there anyway to ensure that it will get the external ip?
EDIT: okay so its getting rejected, anyone else know of another site that can do the same function
public static void main(String[] args) throws IOException
{
URL connection = new URL("http://checkip.amazonaws.com/");
URLConnection con = connection.openConnection();
String str = null;
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
str = reader.readLine();
System.out.println(str);
}
Before you run the following code take a look at this: http://www.whatismyip.com/faq/automation.asp
public static void main(String[] args) throws Exception {
URL whatismyip = new URL("http://automation.whatismyip.com/n09230945.asp");
URLConnection connection = whatismyip.openConnection();
connection.addRequestProperty("Protocol", "Http/1.1");
connection.addRequestProperty("Connection", "keep-alive");
connection.addRequestProperty("Keep-Alive", "1000");
connection.addRequestProperty("User-Agent", "Web-Agent");
BufferedReader in =
new BufferedReader(new InputStreamReader(connection.getInputStream()));
String ip = in.readLine(); //you get the IP as a String
System.out.println(ip);
}
While playing with Go I saw your question. I made a quick App on Google App Engine using Go:
Hit this URL:
http://agentgatech.appspot.com/
Java code:
new BufferedReader(new InputStreamReader(new URL('http://agentgatech.appspot.com').openStream())).readLine()
Go code for the app which you can copy and make your own app:
package hello
import (
"fmt"
"net/http"
)
func init() {
http.HandleFunc("/", handler)
}
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, r.RemoteAddr)
}
Some servers has triggers that blocks access from "non-browsers". They understand that you are some kind of automatic app that can do a DOS attack. To avoid this, you can try to use a lib to access the resource and set the "browser" header.
wget works in this way:
wget -r -p -U Mozilla http://www.site.com/resource.html
Using Java, you can use the HttpClient lib and set the "User-Agent" header.
Look the topic 5 of "Things To Try" section.
Hope this can help you.
A 403 response indicates that the server is explicitly rejecting your request for some reason. Contact the operator of WhatIsMyIP for details.
We've set up CloudFlare and as designed they're challenging unfamiliar useragents. If you can set your UA to something common, you should be able to gain access.
You can use another web service like this; http://freegeoip.net/static/index.html
Using the Check IP address link on AWS worked for me.Please note that MalformedURLException,IOException are to be added as well
public String getPublicIpAddress() throws MalformedURLException,IOException {
URL connection = new URL("http://checkip.amazonaws.com/");
URLConnection con = connection.openConnection();
String str = null;
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
str = reader.readLine();
return str;
}
This is how I do it with rxJava2 and Butterknife. You'll want to run the networking code in another thread because you'll get an exception for running network code on the main thread!
I use rxJava instead of AsyncTask because the rxJava cleans up nicely when the user moves on to the next UI before the thread is finished. (this is super useful for very busy UI's)
public class ConfigurationActivity extends AppCompatActivity {
// VIEWS
#BindView(R.id.externalip) TextInputEditText externalIp;//this could be TextView, etc.
// rxJava - note: I have this line in the base class - for demo purposes it's here
private CompositeDisposable compositeSubscription = new CompositeDisposable();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_wonderful_layout);
ButterKnife.bind(this);
getExternalIpAsync();
}
// note: I have this code in the base class - for demo purposes it's here
#Override
protected void onStop() {
super.onStop();
clearRxSubscriptions();
}
// note: I have this code in the base class - for demo purposes it's here
protected void addRxSubscription(Disposable subscription) {
if (compositeSubscription != null) compositeSubscription.add(subscription);
}
// note: I have this code in the base class - for demo purposes it's here
private void clearRxSubscriptions() {
if (compositeSubscription != null) compositeSubscription.clear();
}
private void getExternalIpAsync() {
addRxSubscription(
Observable.just("")
.map(s -> getExternalIp())
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe((String ip) -> {
if (ip != null) {
externalIp.setText(ip);
}
})
);
}
private String getExternalIp() {
String externIp = null;
try {
URL connection = new URL("http://checkip.amazonaws.com/");
URLConnection con = connection.openConnection(Proxy.NO_PROXY);
con.setConnectTimeout(1000);//low value for quicker result (otherwise takes about 20secs)
con.setReadTimeout(5000);
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
externIp = reader.readLine();
} catch (Exception e) {
e.printStackTrace();
}
return externIp;
}
}
UPDATE - I've found that URLConnection is really quite shit; it'll take a long time to get a result, not really time out very well, etc. The code below improves the situation with OKhttp
private String getExternalIp() {
String externIp = "no connection";
OkHttpClient client = new OkHttpClient();//should have this as a member variable
try {
String url = "http://checkip.amazonaws.com/";
Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute();
ResponseBody responseBody = response.body();
if (responseBody != null) externIp = responseBody.string();
} catch (IOException e) {
e.printStackTrace();
}
return externIp;
}