i have a jquery cod with me and i want to port it to java. Is there any options available to do this task quickly since i am not familiar with java
Here is my code
ASDR.PostStore = function(ec, options) {
this.ec = ec;
this.target = options && options.target;
var self = this;
var _send = function(url, transaction, pre, post) {
$(transaction).trigger(pre);
$(self).trigger(pre, transaction);
$(self).trigger('sending', transaction);
$.ajax({
type : "POST",
url : url,
data : transaction.toString(),
dataType: "json",
success : function(data) {
ec.expand(data, true);//Always updateOnIntern
$(self).trigger('sent', data);
$(self).trigger(post, data);
$(transaction).trigger(post, data);
},
error : function(data){
console.log("Logging error", data);
}
});
};
this.get = function(transaction) {
var url = (this.target + "get");
_send(url, transaction, 'getting', 'gotten');
}
this.persist = function(transaction) {
var url = (this.target + "persist");
_send(url, transaction, 'persisting', 'persisted');
}
/**
* Always asynchronous.
*/
this.is_async = function(){
return true;
}
}
}
Thanks in advance
Renjith Raj
jQuery is Javascript, which is usually executed on the client side. Java is a program language which is executed on the server side. You cannot directly convert jQuery to Java.
You can however use a library such as GWT which translates Java to Javascript. There is also the possibility to statically render content server side. If you search for JSP/JSTL you'll find many resources.
Related
Hi im trying to send data from my titanium app to my Apache Web Service. The snippet of titanium code works as the output to the console is success. Now what im trying to do is when the post is sent, display the contents of the post on the web service page. Is my doPost correct?
Titanium Snippet
button.addEventListener('click', function(e) {
var params = {
"places" : {
Country : textCountry.getValue(),
Capital : textCapital.getValue()
}
};
var xhr = Ti.Network.createHTTPClient({});
// function to deal with errors
xhr.onerror = function() {
Ti.API.info('error, HTTP status = ' + this.status);
alert('Error Sending Data');
};
// function to deal with response
xhr.onload = function() {
console.log('success, HTTP status = ' + this.status);
};
xhr.open("POST", 'http://130.206.127.43:8080/Test');
//set enconding
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xhr.send(JSON.stringify(params));
});
Java Servlet/Apache Tomcat Snippet
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
String jsonData = request.getParameter("json");
response.setContentType("applicaiton/json");
PrintWriter out= response.getWriter();
out.println(jsonData);
out.close();
}
18/02/205
// function to deal with response
xhr.onload = function() {
console.log('success, HTTP status = ' + this.status);
Ti.API.info('json' + this.responseText);
};
[INFO] : success, HTTP status = 200
[INFO] : json = null
Set a breakpoint in the xhr.onload and look at the variables that are present before your write your log.
You are looking for the this.responseText, which will have the response from your call to the Java servlet. I mainly use WCF and C# and if I don't setup the WCF service specifically to clean-up the output, it will add the function name to the response.
Generally, my onload looks like this.
xhr.onload = function(){
var result = JSON.parse(this.responseText);
Ti.API.log(result);
}
* Look closer at your Java Servlet return type. It is a VOID return type so no data will be returned to the http call. *
http://docs.appcelerator.com/titanium/3.0/#!/api/Titanium.Network.HTTPClient
I have an angular webapp.
It has one service that will query a simple node api on the same server.
That api takes the name of an environment variable as parameter and return the path to the java api that matches that environment variable.
servicesModule.factory('EnvVarApi', function($http){
var url = 'http://localhost:8080/api/variable_env/';
return {
getUrlApi : function(var_env, callbackSuccess) {
$http.get(url+ var_env).success(callbackSuccess);
}
}
});
This works fine. It returns an object of the form:
{"cle" : API_KEY, "valeur" : API_PATH}
Now i want to create another service, that will query that java api (I will have 3 of them at the end)..
How would i go about retrieving the path to that API only ONCE? And once it loaded return the correct resource. Atm it's breaking because the resource returned has a null path before the callback.
servicesModule.factory('ApiRef', function($resource, EnvVarApi){
var url = null;
EnvVarApi.getUrlApi('APIREF_KEY', function(data) {
if (data) {
url = data.valeur;
}
});
return $resource(url, {'cle' : '#cle'}, {
put : {method : 'PUT'}
});
});
The first call is made fine and return the path, however as expected it breaks because i'm return a $resource with a null url at first.
And there is maybe a better way to do that than to inject my first service in my second service.
EDIT : FIXED thanks to answer marked bellow.
Here the final code:
servicesModule.factory('EnvVarApi', function($http){
var url = 'http://localhost:8080/api/variable_env/';
return {
getUrlApi : function(var_env) {
return $http.get(url+ var_env);
}
}
});
And
servicesModule.factory('ApiRef',['$q','$http', 'EnvVarApi',function ($q,$http, EnvVarApi) {
var defer = $q.defer();
EnvVarApi.getUrlApi('APIREF_KEY').then(function (resp) {
defer.resolve($http.get(resp.data.valeur));
});
return defer.promise;
}]);
You can use $q service, check code below
app.factory('call2',['$q','$http',function ($q,$http) {
var url = 'whatever url';
var defer = $q.defer();
$http.get(url).then(function (resp) {
defer.resolve($http.get(resp.data));
//resp.data contains the returned by $http request URL object
});
return defer.promise;
}]);
At Controller o Directive side (remember to inject service into controller)
call2.then(function (resp) {
$scope.response = resp.data;
//resp.data will contain the response of '$http.get(resp.data)'
})
you can use $resource instead of $http.get, see below
app.factory('call2', ['$q', '$resource', function ($q, $resource) {
var url = 'whatever url';
var defer = $q.defer();
$resource(url).get(function (resp) {
defer.resolve($resource(resp.url).get().$promise);
});
return defer.promise;
}]);
$http.get returns a promise, the simple thing to do is to resolve the promise in your controller... not in a factory. Meaning no .success() in your factory... only in the controller
If you need this in the service... it would be like so:
servicesModule.factory('ApiRef', function($resource, EnvVarApi){
var url = null;
// this is ASYNC, meaning it will got to the return statement below and wait until the promise is resolved to assign the url
EnvVarApi.getUrlApi('APIREF_KEY', function(data) {
if (data) {
url = data.valeur;
$resource(url, {'cle' : '#cle'}, { // url defined here, gets put correctly
put : {method : 'PUT'}
});
}
});
return $resource(url, {'cle' : '#cle'}, {
put : {method : 'PUT'}
});
});
I am using Jquerys Ajax method to talk to my web service. The code seems OK, but I just monitored HTTP traffic using HTTPFox firefox plugin and I noticed unexpected results. To begin with, I am setting the ContentType as application/json and my web service is also producing JSON data but HTTPFox indicates Content Type for my HTTP requests as application/vnd.sun.wadl+xml (NS_ERROR_DOM_BAD_URI).
The Request Method is GET as set in my Ajax request, but HTTPFox indicates my Request method as OPTIONS. And while the Request succeeds and data is returned, the onSuccess method of my Ajax request is not called. Instead, the onError method is called. HTTP Fox is able to capture the data from my web service as response. See the image for HTTP Fox.
Finally, all other request from other processes in my browser seem OK but my HTTP requests are flagged 'RED' by HTTP Fox. The request from other pages and processes seem OK.( GREEN or WHITE).
I have attached screenshot of HTTPFox highlighted on one of my Request. The flagged ones are also from my application.
Image:
I have also pasted the Ajax code I am using to make the HTTP Requests.
window.onload = function() {
var seq_no = getParameterByName("seq_no");
var mileage = getParameterByName("mileage");
document.getElementById("seq_no").value = seq_no;
document.getElementById("mileage").value = mileage;
var param = 'vehReg='+encodeURIComponent(document.getElementById('vehReg').value);
// alert(param);
loadVehicleInfo(param);
};
function loadVehicleInfo(params) {
$("#message").html('<p><font color="green">Loading...</font></p>');
$.ajax({
type: "GET",
url: "http://localhost:8080/stockcloud/rest/vehicles/info",
data: params,
contentType: "application/json; charset=utf-8",
dataType: "json",
success:
function(data,status) {
$("#message").empty();
$("#message").html('<p>'+getAsUriParameters(data)+'</p>');
},
error :
function(XMLHttpRequest, textStatus, errorThrown) {
$("#message").html("<p> <font color='red'>The following error occurred: " +textStatus+ ': '+errorThrown+ "</font>");
}
});
};
function getAsUriParameters (data) {
return Object.keys(data).map(function (k) {
if (_.isArray(data[k])) {
var keyE = encodeURIComponent(k + '[]');
return data[k].map(function (subData) {
return keyE + '=' + encodeURIComponent(subData);
}).join('&');
} else {
return encodeURIComponent(k) + '=' + encodeURIComponent(data[k]);
}
}).join('&');
};
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
Server side Code for the request:
#Path("/vehicles")
public class VehiclesService {
#GET
#Path("info")
#Produces("application/json")
public Response getVehicleInfo(#DefaultValue("__DEFAULT__") #QueryParam("vehReg") String vehReg) {
// Send SOAP Message to SOAP Server
ServerResponse resp = new ServerResponse();
if("__DEFAULT__".equals(vehReg)) {
resp.setError("Vehicle registration must be supplied as a query parameter: ?vehReg=<THE REG NO>");
resp.setResult(false);
Response.status(Response.Status.BAD_REQUEST).entity(resp).build();
}
try {
// actual code to return the car info and return XML string with the info.
connection.disconnect();
String xml = URLDecoder.decode(s.toString(),"UTF-8");
xml = xml.replace("<", "<").replace(">", ">").replace("<?xml version='1.0' standalone='yes' ?>", "");
System.out.println(xml);
resp.setVehicle(new VehicleParse().parse(xml));
resp.setResult(true);
} catch(Exception e) {
resp.setResult(false);
resp.setError(e.getMessage());
e.printStackTrace();
Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(resp).build();
}
return Response.status(Response.Status.OK).entity(resp).build();
}
}
Is there something I am not doing right?
Thanks.
After browsing thru SO, i found this piece of code everywhere, even I want to implement AutoComplete, I am using Solr to implement search, and wanted to use TermsComponent foe implementing Autocomplet
var cache = {};
$("#textbox").autocomplete({
source: function(request, response) {
if (request.term in cache) {
response($.map(cache[request.term].d, function(item) {
return { value: item.value, id: item.id }
}))
return;
}
$.ajax({
url: "/Services/AutoCompleteService.asmx/GetEmployees", /* I use a web service */
data: "{ 'term': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function(data) { return data; },
success: function(data) {
cache[request.term] = data;
response($.map(data.d, function(item) {
return {
value: item.value,
id: item.id
}
}))
},
error: HandleAjaxError // custom method
});
},
minLength: 3,
select: function(event, ui) {
if (ui.item) {
formatAutoComplete(ui.item); // custom method
}
}
});
Now my question is, How to configure the url source, wat it should be, the following url
http://localhost:8983/solr/terms?terms.fl=name&terms.prefix=at&wt=json&omitHeader=true
gives me perfect result, now pls tell me wat should be my url source, and if i want to customize add more parameters like terms.lower=py&terms.lower.incl=false&indent=true&wt=json etc ,should i better harcode them in url or in my java class like
List terms = query(q, Integer.parseInt(limit));
private List<TermsResponse.Term> query(String q, int limit) {
List<TermsResponse.Term> items = null;
SolrQuery query = new SolrQuery();
query.addTermsField("spell");
query.setTerms(true);
query.setTermsLimit(limit);
query.setTermsLower(q);
query.setTermsPrefix(q);
query.setQueryType("/terms");
try {
QueryResponse qr = server.query(query);
TermsResponse resp = qr.getTermsResponse();
items = resp.getTerms("name");
} catch (SolrServerException e) {
items = null;
}
return items;
}
Please help, um not so good in jquery, so wanted to confirm one more thing,for wat i need, i just need to modify the url over here or have to customize few more things
It's not very likely that you need to parameterize this client-side, so set those parameters server-side. Setting them with code instead of hardcoding them in the URL is generally better, it reveals the intention. Also remember that you can set parameters in the solr config.
Lastly, don't program by coincidence. Understand the jQuery snippet you're using, otherwise you will have problems sooner or later.
I am trying to access RESTful service, created on Java and deployed with help of Jersey using jQuery.
If I access it using browser I will get the result, but from jQuery, I am getting an error and can not see any results on the page.
Page with the script is hosting on local Apache server and the Service is running separately using Jersey/Grizzly on the same machine.
I can see that service is sending the response and it has 200 code, but I keep getting error from .ajax, without any details and
Any suggestions what is wrong?
Service:
#Path("/helloworld")
public class HelloWorldResource {
#GET
#Produces
public String test(){
System.out.println("Sending response");
return "test";
}
}
Main:
public static void main(String[] args) throws IOException {
final String baseUri = "http://localhost:9998/";
final Map<String, String> initParams = new HashMap<String, String>();
initParams.put("com.sun.jersey.config.property.packages",
"resources");
System.out.println("Starting grizly");
SelectorThread threadSelector = GrizzlyWebContainerFactory.create(baseUri, initParams);
System.out.println(String.format(
"Jersey app started with WADL available at %sapplication.wadl\n"
+ "Try out %shelloworld\nHit enter to stop it...", baseUri, baseUri));
System.in.read();
threadSelector.stopEndpoint();
System.exit(0);
}
JavaScript:
var serviceAddress = "http://192.168.1.2:9998/helloworld";
function loadDeviceData(){
$.ajax({
DataType: "text",
url: serviceAddress,
success: function (data) {
alert("Data loaded: " + data);
},
error: function (xhr) {
alert(xhr.responseText + ' ' + xhr.status + ' ' + xhr.statusText);
}
});
}
After a couple of days of research and experiments I discovered that the problem was in the headers of the response. To be able to use the response from the service, I added custom header field:
"Access-Control-Allow-Origin: *"
New service looks like this:
#Path("/helloworld")
public class HelloWorldResource {
#GET
#Produces
public Response test(){
return Response.ok("test").header("Access-Control-Allow-Origin", "*").build();
}
}
you have to set crossDomain to true to make cross domain requests
var serviceAddress = "http://192.168.1.2:9998/helloworld";
function loadDeviceData(){
$.ajax({
dataType:'html',
type:'GET',
crossDomain:true,
cache:false,
async:false,
url: serviceAddress,
success: function (data) {
alert("Data loaded: " + data);
},
error: function (xhr) {
alert(xhr.responseText + ' ' + xhr.status + ' ' + xhr.statusText);
}
});
}
UPDATE
if your service required the authentication may be you can do it like this
var serviceAddress = "http://192.168.1.2:9998/helloworld";
function loadDeviceData(){
$.ajax({
dataType:'html',
type:'GET',
crossDomain:true,
cache:false,
async:false,
xhrFields: {
withCredentials: true
},
username:'yourUsername', //not sure about the username and password options but you can try with or without them
password:'thePass',
url: serviceAddress,
success: function (data) {
alert("Data loaded: " + data);
},
error: function (xhr) {
alert(xhr.responseText + ' ' + xhr.status + ' ' + xhr.statusText);
}
});
}
also use jquery 1.5.1 or higher because the crossDomain and some other options are not available in the earlier versions. For reference see this link http://api.jquery.com/jQuery.ajax/
if you are using a javascript function to replace a typical form submission then pay attention to the fact that you should return false; at the end of your javascript function!
you can check a similar issue here http://forum.jquery.com/topic/jquery-newbie-3-9-2011
actually it is nota a matter of jersey but a matter of javascript