heres the code
it basically takes a message and echos it back.
the problem is it is not replying at all :(
in google app engine, my applications page, i get error-"The requested URL /guestbook was not found on this server."
package guestbook;
import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.http.*;
import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.MessageBuilder;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;
#SuppressWarnings("serial")
public class GuestbookServlet extends HttpServlet {
private static final Logger LOG =
Logger.getLogger(GuestbookServlet.class.getName());
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
// Parse incoming message
XMPPService xmpp = XMPPServiceFactory.getXMPPService();
Message msg = xmpp.parseMessage(req);
JID jid = msg.getFromJid();
String body = msg.getBody();
LOG.info(jid.getId() + " --> JEliza: " + body);
// Get a response from Eliza
String response = "echo: " + body;
LOG.info(jid.getId() + " <-- JEliza: " + response);
// Send out response
msg = new MessageBuilder()
.withRecipientJids(jid)
.withBody(response)
.build();
xmpp.sendMessage(msg);
/*Message message = xmpp.parseMessage(req);
JID fromJid = message.getFromJid();
String body = message.getBody();
String respMsg = null;
if (body.equals("/list")) {
respMsg = "Hi";
} else if (body.equals("/help")) {
respMsg = "Welcome to the Guestbook Chatbot!\nThe following commands are supported: \n /list \n /help";
} else {
respMsg = "Command '" + body + "' not supported! \nEnter '/help' for list of commands.";
}
JID tojid = new JID(fromJid.getId());
Message msg = new MessageBuilder().withRecipientJids(tojid).withBody(respMsg).build();
boolean messageSent = false;
xmpp = XMPPServiceFactory.getXMPPService();
if (xmpp.getPresence(tojid).isAvailable()) {
SendResponse status = xmpp.sendMessage(msg);
messageSent = (status.getStatusMap().get(tojid) == SendResponse.Status.SUCCESS);
}*/
}
}
As per the details you have given i think the problem should be with the web.xml file
<servlet><servlet-name>GuestbookServlet</servlet-name><servlet-class>your.package.structure.GuestbookServlet</servlet-class></servlet><servlet-mapping><servlet-name>GuestbookServlet</servlet-name><url-pattern>/_ah/xmpp/message/chat/</url-pattern></servlet-mapping>
try adding this into the web.xml change your.package.structure.GuestbookServlet accordingly for example mine would be com.appengine.capp
JDK settings had to be changed from 1.7 to 1.6.
under window-> preferences -> java -> compiler
Related
In the next sample code, Twilio puts in conversation OPERATOR_PHONE_NUMBER to CLIENT_PHONE_NUMBER, and records the call.
But I don't know what should be the code to control some things, one or both of the phones...:
does not exist.
exists but communicates.
exists, does not communicate but does not pick up.
exists, does not communicate, picks up and the conversation takes place.
import com.twilio.Twilio;
import com.twilio.rest.api.v2010.account.Call;
import com.twilio.rest.api.v2010.account.CallCreator;
import com.twilio.type.PhoneNumber;
import com.twilio.type.Twiml;
public class SimpleCallWithRecording2 {
private static final String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
private static final String AUTH_TOKEN = "9ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ";
private static final String ASSIGNED_PHONE_NUMBER = "+15999999999999";
//Must be verified numbers in trial account
private static final String OPERATOR_PHONE_NUMBER = "+34888888888";
private static final String CLIENT_PHONE_NUMBER = "+34777777777";
public static void main(String[] args) throws Exception {
Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
PhoneNumber to = new PhoneNumber(OPERATOR_PHONE_NUMBER);
PhoneNumber from = new PhoneNumber(ASSIGNED_PHONE_NUMBER);
Twiml twiml = new Twiml(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?> " +
"<Response> " +
" <Say voice=\"woman\">This is said by a robotic woman</Say> " +
" <Dial> " +
" <Number> " + CLIENT_PHONE_NUMBER + "</Number> " +
" </Dial> " +
"</Response> " );
CallCreator callCreator = Call.creator(to, from, twiml);
callCreator.setRecord(true);
Call call = callCreator.create();
System.out.println(call);
}
}
In the doc I see something could be done with callCreator.setStatusCallback(URI.create("https://www.myapp.com/events")), and some clasification of events: "initiated", "ringing", "answered", "completed". BUT I havent find the code "on the other side", I mean in https://www.myapp.com/events extreme ¿?
You need to setup a that rest endpoint and set it as status callback url.
The url will recieve events from twilio.
Refer this
edit: if you also need events from the nested verb, define attribute 'action' to it.
ie
<Dial action="//callbackURL">
<Number> CLIENT_PHONE_NUMBER </Number>
</Dial>
that way you'll know your cases 1 ,2 ,3 ,4.
and to "control" the call, you just respond with the desired TwiML to the callback request. Hope this clarifies.
edit2: You need to do something like:
//handles callback url
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
{ //...
TwiMLResponse twiml = new TwiMLResponse();
String callSid = request.getParameter("CallSid");
//handle call specific data
switch(request.getParameter("CallStatus")){
case "no-answer": //construct twiML
case "ringing" ://...
}
//...
response.setContentType("application/xml");
response.getWriter().print(twiml.toXML());
}
See: IVR - Example
When I run Microsoft Azure Media Services code written using Java in local it is working but when I deploy the same code in dev environment , I am unable to access the Azure and its throwing java.net.HostNotFoundException.
What is the best approach to use network proxy to connect to Azure
Below is the code I am using via java and using azure-java-sdk
import java.io.*;
import java.security.NoSuchAlgorithmException;
import java.util.EnumSet;
import com.microsoft.windowsazure.Configuration;
import com.microsoft.windowsazure.exception.ServiceException;
import com.microsoft.windowsazure.services.media.MediaConfiguration;
import com.microsoft.windowsazure.services.media.MediaContract;
import com.microsoft.windowsazure.services.media.MediaService;
import com.microsoft.windowsazure.services.media.WritableBlobContainerContract;
import com.microsoft.windowsazure.services.media.models.AccessPolicy;
import com.microsoft.windowsazure.services.media.models.AccessPolicyInfo;
import com.microsoft.windowsazure.services.media.models.AccessPolicyPermission;
import com.microsoft.windowsazure.services.media.models.Asset;
import com.microsoft.windowsazure.services.media.models.AssetFile;
import com.microsoft.windowsazure.services.media.models.AssetFileInfo;
import com.microsoft.windowsazure.services.media.models.AssetInfo;
import com.microsoft.windowsazure.services.media.models.Job;
import com.microsoft.windowsazure.services.media.models.JobInfo;
import com.microsoft.windowsazure.services.media.models.JobState;
import com.microsoft.windowsazure.services.media.models.ListResult;
import com.microsoft.windowsazure.services.media.models.Locator;
import com.microsoft.windowsazure.services.media.models.LocatorInfo;
import com.microsoft.windowsazure.services.media.models.LocatorType;
import com.microsoft.windowsazure.services.media.models.MediaProcessor;
import com.microsoft.windowsazure.services.media.models.MediaProcessorInfo;
import com.microsoft.windowsazure.services.media.models.Task;
public class HelloMediaServices
{
// Media Services account credentials configuration
private static String mediaServiceUri = "https://media.windows.net/API/";
private static String oAuthUri = "https://wamsprodglobal001acs.accesscontrol.windows.net/v2/OAuth2-13";
private static String clientId = "account name";
private static String clientSecret = "account key";
private static String scope = "urn:WindowsAzureMediaServices";
private static MediaContract mediaService;
// Encoder configuration
private static String preferedEncoder = "Media Encoder Standard";
private static String encodingPreset = "H264 Multiple Bitrate 720p";
public static void main(String[] args)
{
try {
// Set up the MediaContract object to call into the Media Services account
Configuration configuration = MediaConfiguration.configureWithOAuthAuthentication(
mediaServiceUri, oAuthUri, clientId, clientSecret, scope);
mediaService = MediaService.create(configuration);
// Upload a local file to an Asset
AssetInfo uploadAsset = uploadFileAndCreateAsset("BigBuckBunny.mp4");
System.out.println("Uploaded Asset Id: " + uploadAsset.getId());
// Transform the Asset
AssetInfo encodedAsset = encode(uploadAsset);
System.out.println("Encoded Asset Id: " + encodedAsset.getId());
// Create the Streaming Origin Locator
String url = getStreamingOriginLocator(encodedAsset);
System.out.println("Origin Locator URL: " + url);
System.out.println("Sample completed!");
} catch (ServiceException se) {
System.out.println("ServiceException encountered.");
System.out.println(se.toString());
} catch (Exception e) {
System.out.println("Exception encountered.");
System.out.println(e.toString());
}
}
private static AssetInfo uploadFileAndCreateAsset(String fileName)
throws ServiceException, FileNotFoundException, NoSuchAlgorithmException {
WritableBlobContainerContract uploader;
AssetInfo resultAsset;
AccessPolicyInfo uploadAccessPolicy;
LocatorInfo uploadLocator = null;
// Create an Asset
resultAsset = mediaService.create(Asset.create().setName(fileName).setAlternateId("altId"));
System.out.println("Created Asset " + fileName);
// Create an AccessPolicy that provides Write access for 15 minutes
uploadAccessPolicy = mediaService
.create(AccessPolicy.create("uploadAccessPolicy", 15.0, EnumSet.of(AccessPolicyPermission.WRITE)));
// Create a Locator using the AccessPolicy and Asset
uploadLocator = mediaService
.create(Locator.create(uploadAccessPolicy.getId(), resultAsset.getId(), LocatorType.SAS));
// Create the Blob Writer using the Locator
uploader = mediaService.createBlobWriter(uploadLocator);
File file = new File("BigBuckBunny.mp4");
// The local file that will be uploaded to your Media Services account
InputStream input = new FileInputStream(file);
System.out.println("Uploading " + fileName);
// Upload the local file to the asset
uploader.createBlockBlob(fileName, input);
// Inform Media Services about the uploaded files
mediaService.action(AssetFile.createFileInfos(resultAsset.getId()));
System.out.println("Uploaded Asset File " + fileName);
mediaService.delete(Locator.delete(uploadLocator.getId()));
mediaService.delete(AccessPolicy.delete(uploadAccessPolicy.getId()));
return resultAsset;
}
// Create a Job that contains a Task to transform the Asset
private static AssetInfo encode(AssetInfo assetToEncode)
throws ServiceException, InterruptedException {
// Retrieve the list of Media Processors that match the name
ListResult<MediaProcessorInfo> mediaProcessors = mediaService
.list(MediaProcessor.list().set("$filter", String.format("Name eq '%s'", preferedEncoder)));
// Use the latest version of the Media Processor
MediaProcessorInfo mediaProcessor = null;
for (MediaProcessorInfo info : mediaProcessors) {
if (null == mediaProcessor || info.getVersion().compareTo(mediaProcessor.getVersion()) > 0) {
mediaProcessor = info;
}
}
System.out.println("Using Media Processor: " + mediaProcessor.getName() + " " + mediaProcessor.getVersion());
// Create a task with the specified Media Processor
String outputAssetName = String.format("%s as %s", assetToEncode.getName(), encodingPreset);
String taskXml = "<taskBody><inputAsset>JobInputAsset(0)</inputAsset>"
+ "<outputAsset assetCreationOptions=\"0\"" // AssetCreationOptions.None
+ " assetName=\"" + outputAssetName + "\">JobOutputAsset(0)</outputAsset></taskBody>";
Task.CreateBatchOperation task = Task.create(mediaProcessor.getId(), taskXml)
.setConfiguration(encodingPreset).setName("Encoding");
// Create the Job; this automatically schedules and runs it.
Job.Creator jobCreator = Job.create()
.setName(String.format("Encoding %s to %s", assetToEncode.getName(), encodingPreset))
.addInputMediaAsset(assetToEncode.getId()).setPriority(2).addTaskCreator(task);
JobInfo job = mediaService.create(jobCreator);
String jobId = job.getId();
System.out.println("Created Job with Id: " + jobId);
// Check to see if the Job has completed
checkJobStatus(jobId);
// Done with the Job
// Retrieve the output Asset
ListResult<AssetInfo> outputAssets = mediaService.list(Asset.list(job.getOutputAssetsLink()));
return outputAssets.get(0);
}
public static String getStreamingOriginLocator(AssetInfo asset) throws ServiceException {
// Get the .ISM AssetFile
ListResult<AssetFileInfo> assetFiles = mediaService.list(AssetFile.list(asset.getAssetFilesLink()));
AssetFileInfo streamingAssetFile = null;
for (AssetFileInfo file : assetFiles) {
if (file.getName().toLowerCase().endsWith(".ism")) {
streamingAssetFile = file;
break;
}
}
AccessPolicyInfo originAccessPolicy;
LocatorInfo originLocator = null;
// Create a 30-day readonly AccessPolicy
double durationInMinutes = 60 * 24 * 30;
originAccessPolicy = mediaService.create(
AccessPolicy.create("Streaming policy", durationInMinutes, EnumSet.of(AccessPolicyPermission.READ)));
// Create a Locator using the AccessPolicy and Asset
originLocator = mediaService
.create(Locator.create(originAccessPolicy.getId(), asset.getId(), LocatorType.OnDemandOrigin));
// Create a Smooth Streaming base URL
return originLocator.getPath() + streamingAssetFile.getName() + "/manifest";
}
private static void checkJobStatus(String jobId) throws InterruptedException, ServiceException {
boolean done = false;
JobState jobState = null;
while (!done) {
// Sleep for 5 seconds
Thread.sleep(5000);
// Query the updated Job state
jobState = mediaService.get(Job.get(jobId)).getState();
System.out.println("Job state: " + jobState);
if (jobState == JobState.Finished || jobState == JobState.Canceled || jobState == JobState.Error) {
done = true;
}
}
}
}
I verified following code below which is working through fiddler proxy. Thanks to how to Capture https with fiddler, in java post which gave me hints:
System.setProperty("http.proxyHost", "127.0.0.1");
System.setProperty("https.proxyHost", "127.0.0.1");
System.setProperty("http.proxyPort", "8888");
System.setProperty("https.proxyPort", "8888");
System.setProperty("javax.net.ssl.trustStore", "C:\\Program Files\\Java\\jdk1.8.0_102\\bin\\FiddlerKeyStore");
System.setProperty("javax.net.ssl.trustStorePassword", "mypassword");
For others who face issue like me we can connect to azure mediaservices using network proxy by using below code
// Set up the MediaContract object to call into the Media Services account
Configuration configuration = MediaConfiguration.configureWithOAuthAuthentication(
mediaServiceUri, oAuthUri, clientId, clientSecret, scope);
configuration.getProperties().put(Configuration.PROPERTY_HTTP_PROXY_HOST, "Hostvalue");
configuration.getProperties().put(Configuration.PROPERTY_HTTP_PROXY_PORT, "Portvalue");
configuration.getProperties().put(Configuration.PROPERTY_HTTP_PROXY_SCHEME, "http");
MediaContract mediaService = MediaService.create(configuration);
Now use the mediaService to perform other operations.
I have recently had to some trouble trying to get OpenID to work in Java (servlet). I'm trying to make a user able to login to my website using their Steam account. I've tried mutliple libraries but some of them are outdated and for others is almost no documentation available so the library I'm trying right now is JOpenID. It works as expected until I need to verify the information sent back by Steam (http://steamcommunity.com/openid). This is my Servlet:
#WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private OpenIdManager manager;
static final long ONE_HOUR = 3600000L;
static final long TWO_HOUR = ONE_HOUR * 2L;
static final String ATTR_MAC = "openid_mac";
static final String ATTR_ALIAS = "openid_alias";
public LoginServlet() {
super();
}
#Override
public void init() throws ServletException {
super.init();
manager = new OpenIdManager();
manager.setRealm("http://localhost:8080/TestServletProject/LoginServlet");
manager.setReturnTo("http://localhost:8080/TestServletProject/LoginServlet?login=verify");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String login = request.getParameter("login");
if(login != null){
if(login.equals("steam")){
out.print("<h2>Redirecting</h2>");
Endpoint endpoint = manager.lookupEndpoint("http://steamcommunity.com/openid");
Association association = manager.lookupAssociation(endpoint);
request.getSession().setAttribute(ATTR_MAC, association.getRawMacKey());
request.getSession().setAttribute(ATTR_ALIAS, endpoint.getAlias());
String url = manager.getAuthenticationUrl(endpoint, association);
response.sendRedirect(url);
}else if(login.equals("verify")){
checkNonce(request.getParameter("openid.response_nonce"));
byte[] mac_key = (byte[]) request.getSession().getAttribute(ATTR_MAC);
String alias = (String) request.getSession().getAttribute(ATTR_ALIAS);
Authentication authentication = manager.getAuthentication(request, mac_key, alias);
response.setContentType("text/html; charset=UTF-8");
showAuthentication(response.getWriter(), authentication);
return;
}else if(login.equals("logout")){
out.print("<h2>Loggin out</h2>");
}
return;
}
String id = (String) request.getSession().getAttribute("steamid");
if (id != null) {
out.print("<h2>Welcome ");
out.print(id);
out.print("</h2>");
out.print("Logout");
} else {
out.print("Login");
}
}
void showAuthentication(PrintWriter pw, Authentication auth) {
pw.print("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /><title>Test JOpenID</title></head><body><h1>You have successfully signed on!</h1>");
pw.print("<p>Identity: " + auth.getIdentity() + "</p>");
pw.print("<p>Email: " + auth.getEmail() + "</p>");
pw.print("<p>Full name: " + auth.getFullname() + "</p>");
pw.print("<p>First name: " + auth.getFirstname() + "</p>");
pw.print("<p>Last name: " + auth.getLastname() + "</p>");
pw.print("<p>Gender: " + auth.getGender() + "</p>");
pw.print("<p>Language: " + auth.getLanguage() + "</p>");
pw.print("</body></html>");
pw.flush();
}
void checkNonce(String nonce) {
// check response_nonce to prevent replay-attack:
if (nonce==null || nonce.length()<20)
throw new OpenIdException("Verify failed.");
// make sure the time of server is correct:
long nonceTime = getNonceTime(nonce);
long diff = Math.abs(System.currentTimeMillis() - nonceTime);
if (diff > ONE_HOUR)
throw new OpenIdException("Bad nonce time.");
if (isNonceExist(nonce))
throw new OpenIdException("Verify nonce failed.");
storeNonce(nonce, nonceTime + TWO_HOUR);
}
private Set<String> nonceDb = new HashSet<String>();
// check if nonce is exist in database:
boolean isNonceExist(String nonce) {
return nonceDb.contains(nonce);
}
// store nonce in database:
void storeNonce(String nonce, long expires) {
nonceDb.add(nonce);
}
long getNonceTime(String nonce) {
try {
return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.parse(nonce.substring(0, 19) + "+0000")
.getTime();
}
catch(ParseException e) {
throw new OpenIdException("Bad nonce time.");
}
}
}
I'm getting a org.expressme.openid.OpenIdException: Invalidate handle on line 65: Authentication authentication = manager.getAuthentication(request, mac_key, alias);
While doing some research I found out that this had to do with the Assosiaction sent to steam being expired. This is the JOpenID class that causes the OpenIdException: https://github.com/michaelliao/jopenid/blob/master/src/main/java/org/expressme/openid/OpenIdManager.java
Does anybody know how I can get this to work, or alternatively, know a better library to use. I'm quite new to this and I'm not sure if I'm using the right library or if there's better ways to do this.
So for anyone still wondering: I looked into the JOpenID code and it seems like the code in the getAuthentication() method that goes before the code that throws the exception is enough to retrieve the Steam ID (which is what I tried to get from Steam). So instead of Authentication authentication = manager.getAuthentication(request, mac_key, alias); I now just put String identity = request.getParameter("openid.identity");. This returns http://steamcommunity.com/openid/id/76561198206376959, last part being the Steam ID.
In GWT how do I display an image from the appengine server side blobstore given the string version of the key?
I think I have stored an image as a blob on the appengine. can someone tell me if it's correct?
try
{
FileService fileService = FileServiceFactory.getFileService();
AppEngineFile file = fileService.createNewBlobFile(content_type, fileName);
boolean lock = true;
FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock);
byte[] b1 = new byte[BUFFER_SIZE];
int readBytes1;
while ((readBytes1 = is.read(b1)) != -1)
{
writeChannel.write(ByteBuffer.wrap(b1, 0, readBytes1));
}
writeChannel.closeFinally();
item_image_blob_key = fileService.getBlobKey(file).getKeyString();
}
catch (Exception e)
{
System.out.println(e.getLocalizedMessage());
e.printStackTrace(response.getWriter());
}
I sent the key back to the client and I am trying to present the image. I tried using :
ImagesService imagesService = ImagesServiceFactory
.getImagesService();
// Get the image serving URL
String imageUrl = imagesService.getServingUrl(blobKey);
but it is deprecated so I tried:
ImagesService imagesService = ImagesServiceFactory.getImagesService();
ServingUrlOptions suo = ServingUrlOptions.Builder.withBlobKey(blobKey);
String image_url = imagesService.getServingUrl(suo);
item.setProperty("image_url", image_url);
Now I get a URL which looks like this:
http://0.0.0.0:8888/_ah/img/5nXYgHwfiMmblDFldDXSew
and get create an image on the client thus:
String image_url = result.get_image_url();
System.out.println("image url is: " + image_url);
Image image = new Image();
image.setUrl(image_url);
RootPanel.get("dynamicDate").add(image);
Only a default image icon appears on the UI
so I created a servlet which accesses the blobstore thus:
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
public class ImageServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
#Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException
{
String blob_key = req.getParameter("blob-key");
if (blob_key != null)
{
BlobKey blobKey = new BlobKey(blob_key);
BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
blobstoreService.serve(blobKey, res);
}
else
{
res.sendError(400, "One or more parameters are not set");
}
}
}
and a client http request:
RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, "/itemmanager/image");
try
{
Request request = requestBuilder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception)
{
System.out.println(exception.getMessage());
}
public void onResponseReceived(Request request, Response response)
{
System.out.println("so far so good");
System.out.println(response.getHeadersAsString());
if (200 == response.getStatusCode())
{
}
else
{
// Handle the error. Can get the status text from response.getStatusText()
}
}
});
} catch (RequestException e) {
// Couldn't connect to server
}
I seem to be getting text how do i get an input stream or something i can get an image with?
Finally after two days of scouring Google and stack-overflow and trying I got it!
On the server I got the upload url thus:
ImagesService imagesService = ImagesServiceFactory.getImagesService();
ServingUrlOptions suo = ServingUrlOptions.Builder.withBlobKey(blobKey);
String image_url = imagesService.getServingUrl(suo);
item.setProperty("image_url", image_url);
The appengine API produced a url which didn't work on the local mode [I think it has to do with sop cross platform issues]
http://0.0.0.0:8888/_ah/img/mR9SOTSEizec4gZYsRnuEw
but it provided a clue: namely the /_ah/img/ part of the String
So I decided to try it and gave this URL to the image "/_ah/img/mR9SOTSEizec4gZYsRnuEw"
Here is the client side code.
String imageKey = result.get_image_key();
System.out.println("category is: " + result.get_category() + " image blob key is: " + imageKey);
String image_url = result.get_image_url();
System.out.println("image url is: " + image_url);
//This doesn't work at least locally
/*Image image = new Image();
image.setUrl(image_url);
RootPanel.get("dynamicDate").add(image);*/
Image image2 = new Image();
image2.setUrl("/_ah/img/" + imageKey);
RootPanel.get("dynamicDate").add(image2);
I have a project where you can ask for resources that are served by jax-rs in the json format. Everything works properly in the browser when I query the rest URL the json appears.
Now I want my GWT project to request those resources and process them and show them in my interface. The simplest way I found to do so is using a request builder and an overlay. Code is lower. The problem is, it seems when the code is running it never goes into the actual RequestCallback(). The status string is never changed. I thought it could be a SOP so I added the <add-linker name="xs"/> but still doesn't work. Any ideal?
package com.workoutcell.client;
//import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.http.client.*;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
/**
*
* #author
*/
public class RestToInfoSession{
String queryReturn = null;
JsArray<InfoJSO> arrayOfInfo = null;
String host = "http://localhost:8080/mysite";
String restModule = "/calendar/getinfo";
String id = null;
String year = null;
String month = null;
String status = "Not Initialized";
public RestToInfoSession(String id, String year, String month){
this.id =id;
this.year = year;
this.month = month;
String url = host + restModule + "/"+this.id + "/"+this.year + "/"+this.month;
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
try {
status = "Initialized at Url " + builder.getUrl();
Request request = builder.sendRequest(null, new RequestCallback() {
public void onError(Request request, Throwable exception) {
// Couldn't connect to server (could be timeout, SOP violation, etc.)
status = "Error on connecting to Server";
}
public void onResponseReceived(Request request, Response response) {
if (200 == response.getStatusCode()) {
// arrayOfInfo = jsonToJsArray(response.getText());
status = "JSON has been Fetched. Result is:" + response.getText();
} else if(0 == response.getStatusCode()) {
status = "Error is 0";
} else {
status = "Error in JSON Request:" + response.getStatusCode();
//response.getStatusText();
}
}
});
} catch (RequestException ex) {
status = "Error in Request Builder Startup";
}
}
//get an jso object in array
private final native JsArray<InfoJSO> jsonToJsArray(String json) /*-{
return eval(json);
}-*/;
public JsArray<InfoJSO> getInfoArray (){
return arrayOfInfo;
}
}
UPDATE: My problem is the same as Referring to a non-final variable data inside an inner class . I wasn't aware of asynchronous calls working mechanism. I still don't know how to pass my response.getText() to update a label that isn't part of my RestToInfoSession class any ideas?
Consider using the RestyGWT project. It will make calling JAXRS JSON resources as easy as using GWT-RPC. Plus you can typically reuse the same request response DTOs from the server side on the client side.
I have put a timer that checks every 1000ms if my json string has updated from null to the xhttp requested data. This works, but I got a feeling there is a more elegant way of resolving this problem.