Call WS Rest Java with AngularJS - java

I've a problem with call WS Rest Java. I call the WS but the parameters isn't passed.
My java code:
#POST
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response setUser(#FormParam("name") String name, #FormParam("surname") String surname, #FormParam("email") String email,
#FormParam("phone") String phone, #FormParam("skype") String skype, #FormParam("password") String password){
try {
FileOutputStream fis = new FileOutputStream("/home/File.txt");
PrintStream ps = new PrintStream(fis);
String s = "name: "+name+"\nSurname: "+surname+"\nEmail: "+email+"\nPhone: "+phone+"\nSkype: "+skype+"\nPassword: "+password;
ps.println(s);
ps.close();
fis.close();
UserDAO userdao = new UserDAO(0,name,surname,email,phone,skype);
userdao.save();
...
return Response.status(200).entity(new ObjectMapper().writeValueAsString("OK!")).header("Access-Control-Allow-Origin", "*").build();
} catch (Exception e) {
e.printStackTrace();
return Response.status(500).entity("ERROR!").header("Access-Control-Allow-Origin", "*").build();
}
}
Angular call:
data = {
name: $scope.reg_name,
surname: $scope.reg_surname,
email: $scope.reg_email,
phone: $scope.reg_phone,
skype: $scope.reg_skype,
password: $scope.reg_password
}
$http.post(baseUrl+'user/',data,{
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
});
If i log data on angular data are set, the call working but i've an error when i create AccountDAO object because the parameters are null. To test the parameters values i create a file and put here the value, the content are this:
name: null
Surname: null
Email: null
Phone: null
Skype: null
Password: null
Any one have idea why not pass the parameters?
Thanks!
Solved:
data = "name=" + $scope.reg_name +
"&surname=" + $scope.reg_surname +
"&email=" + $scope.reg_email +
"&phone=" + $scope.reg_phone +
"&skype=" + $scope.reg_skype +
"&password=" + $scope.reg_password;
}
$http.post(baseUrl+'user/',data,{
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
})
Thanks grizzly!

You are sending data as JSON. Change it to form data string:
data = "name=" + $scope.reg_name +
"&surname=" + $scope.reg_surname +
"&email=" + $scope.reg_email +
"&phone=" + $scope.reg_phone +
"&skype=" + $scope.reg_skype +
"&password=" + $scope.reg_password;
}
$http.post(baseUrl+'user/',data,{
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}
})

Related

How to read JSON from file and replace objects with value?

I need to read JSON from file and replace few objects.
For example, I have class User.java
public class User {
String username;
String email;
String city;
String code;
}
and JSON:
{
"variables":
{
"user":
{
"value":
{
"username": "$USERNAME",
"email": "$EMAIL",
"city": "$CITY"
}
}
}
}
I have two questions:
How can I read JSON from file? Read JSON will be send by WebClient POST API.
How can I replace $USERNAME, $EMAIL and $CITY? I won't hardcode it.
I have register form. When someone complete form, it will be replaced for $...
Firsty, I got hardcode JSON to string but I need read it from file
class JSONClass {
static String toFormat(User user) {
String jsonUserRegister = "{\n" +
" \"variables\":\n" +
" {\n" +
" \"user\": \n" +
" {\n" +
" \"value\":\n" +
" {\n" +
" \"username\": \"" + user.getUsername() + "\",\n" +
" \"email\": \"" + user.getEmail() + "\",\n" +
" \"city\": \"" + user.getCity() + "\",\n" +
" \"code\": \"" + user.getCode() + "\"\n" +
" } }\n" +
" }\n" +
"}";
return jsonUserRegister;
This can be achieved using Spring Boot to set up the backend to receive client calls. So to get Task 1a working, we need below
#RestController
public class JsonReaderController {
#Autowired
private ResourceLoader resourceLoader;
#PostMapping(value = "/read-json")
public String fileContent() throws IOException {
return new String(Files.readAllBytes(
resourceLoader.getResource("classpath:data/json- sample.json").getFile().toPath()));
}
}
Above code simply reads file content and returns as String. Note default response is Json.
Now that we have the backend done, we need Task 1b - Sending the POST request.
private String readJsonFile() throws IOException {
final OkHttpClient client = new OkHttpClient();
final String requestUrl = "http://localhost:8080/read-json";
Request request = new Request.Builder()
.url(requestUrl)
.post(RequestBody.create(JSON, ""))
.build();
try (Response response = client.newCall(request).execute()) {
//we know its not empty given scenario
return response.body().string();
}
}
readJsonFile method makes a POST request - using OkHttp to our backend bit (done in Task 1a) and returns the content of the file as json.
And for Task 2 - replacing $USERNAME, $EMAIL and $CITY with appropriate values. For this, we will use the Apache commons-text library.
public static void main(String[] args) throws IOException {
String fileContent = new ReadJsonFromFile().readJsonFile();
User user = new User("alpha", "alpha#tesrt.com", "Bristol", "alpha");
Map<String, String> substitutes = new HashMap<>();
substitutes.put("$USERNAME", user.getUsername());
substitutes.put("$EMAIL", user.getEmail());
substitutes.put("$CITY", user.getCity());
substitutes.put("$CODE", user.getCode());
StringSubstitutor stringSubstitutor = new StringSubstitutor(substitutes);
//include double quote prefix and suffix as its json wrapped
stringSubstitutor.setVariablePrefix("\"");
stringSubstitutor.setVariableSuffix("\"");
String updatedContent = stringSubstitutor.replace(fileContent);
System.out.println(updatedContent);
}
Hope this helps.

Retrofit PUT doesn't work

I am developing an Android application using "Discord API".
First, if I call the same API in Postman, it works fine.
But in my android application, it doesn't work.
The API what I want to use is this: "https://discordapp.com/developers/docs/resources/guild#add-guild-member"
And I want to do the same thing in my Android application using "Retrofit Library".
Below is the interface.
#PUT("guilds/{guildId}/members/{userId}")
Call<RespUser> joinGuild(#Path("guildId") String guildId, #Path("userId") String userId, #Header("Authorization") String token, #Header("Content-Type") String contentType, #Body String body);
And below is implement:
#Override
public void joinGuild(DUser dUser, String authorization) {
Log.d(TAG, "[CHICKEN] joinGuild: " + dUser + ", " + authorization);
Gson gson = new Gson();
String body = gson.toJson(new DJoinBody(authorization, dUser.getUsername()));
Log.d(TAG, "[CHICKEN] joinGuild - body: " + body);
Call<RespUser> guildCall = mDiscordService.joinGuild(BuildConfig.DISCORD_GROUP_ID, dUser.getId(), BuildConfig.DISCORD_BOT_TOKEN, "application/json", body);
Log.d(TAG, "[CHICKEN] joinGuild - request method: " + guildCall.request().method());
Log.d(TAG, "[CHICKEN] joinGuild - request headers: " + guildCall.request().headers().toString());
Log.d(TAG, "[CHICKEN] joinGuild - request body.contentType: " + guildCall.request().body().contentType().toString());
Log.d(TAG, "[CHICKEN] joinGuild - request body.: " + guildCall.request().body().toString());
Log.d(TAG, "[CHICKEN] joinGuild - request: " + guildCall.request().toString());
guildCall.enqueue(new Callback<RespUser>() {
#Override
public void onResponse(Call<RespUser> call, Response<RespUser> response) {
if (response.isSuccessful()) {
RespUser result = response.body();
Log.d(TAG, "[CHICKEN] joinGuild - result: " + result);
} else {
try {
Log.e(TAG, "[CHICKEN] joinGuild - failed: " + response.code() + ": " + response.errorBody().string());
Log.d(TAG, "[CHICKEN] joinGuild - failed: " + response.raw().toString());
Log.d(TAG, "[CHICKEN] joinGuild - failed: " + response.headers().toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onFailure(Call<RespUser> call, Throwable t) {
}
});
}
And the error is:
{"_misc": ["Only dictionaries may be used in a DictType"]}
Could you tell me what I do mistake, please?
I found the solution.
I changed the "Body" parameter's type from "String" to "Object".
Before code:
#PUT("guilds/{guildId}/members/{userId}")
Call<RespUser> joinGuild(#Path("guildId") String guildId,
#Path("userId") String userId,
#Header("Authorization") String token,
#Header("Content-Type") String contentType,
#Body String body);
After code:
#Headers({"Content-Type: application/json"})
#PUT("guilds/{guildId}/members/{userId}")
Call<RespUser> joinGuild(#Path("guildId") String guildId,
#Path("userId") String userId,
#Header("Authorization") String token,
#Body DJoinBody joinBody);

Display exception's message from Controller MVC in the jsp page

StudentController - here is my controller class that returns exceptions and i want to handle and display these in jsp
#RequestMapping(value = RequestURL.ADD_STUDENT, method = RequestMethod.POST)
#ResponseBody
public void addStudent(#RequestBody AddStudentRequest addStudentRequest) throws StudentGroupNumberNotFoundException, SpecializationNotFoundException {
User user = new User(addStudentRequest.getUsername(),
addStudentRequest.getPassword(), Role.ROLE_STUDENT);
userService.add(user);
user = userService.findByUsername(addStudentRequest.getUsername());
int userId = user.getId();
try {
int groupId = studentGroupService
.getIdByGroupNumber(addStudentRequest.getGroup());
int specializationId = specializationService
.getIdByName(addStudentRequest.getSpecialization());
Student student = new Student(userId, specializationId,
addStudentRequest.getName(),
addStudentRequest.getRegistrationNumber(), groupId,
addStudentRequest.getYear());
studentService.add(student);
} catch (StudentGroupNumberNotFoundException e) {
throw new StudentGroupNumberNotFoundException(e.getMessage());
} catch (SpecializationNotFoundException e) {
throw new SpecializationNotFoundException (e.getMessage());
}
}
student.jsp - jsp page for student
function addStudent() {
var username = $('#modalStudentUsername').val();
var password = $('#modalStudentPassword').val();
var name = $('#modalStudentName').val();
var registrationNumber = $('#modalStudentRegistrationNumber').val();
var group = $('#modalStudentGroup').val();
var year = $('#modalStudentYear').val();
var specialization = $('#modalStudentSpecializationId').val();
var data = '{ "username" : "' + username + '", "password": "'
+ password + '", "name":"' + name
+ '","registrationNumber": "' + registrationNumber + '" , "specialization": "' + specialization
+ '","group": "' + group+'", "year": " ' + year + '" }';
var token = $('#csrfToken').val();
var header = $('#csrfHeader').val();
$.ajax({
type : "POST",
url : "student/add",
contentType : 'application/json',
data : data,
beforeSend : function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader(header, token);
},
success : function(data, status, xhr) {
alert("Success!");
},
error : function(xhr, status, errorThrown) {
alert("Error!");
},
});
}
I want to display in the alert from ajax the exception's message from controller. Could anyone help me? Thanks!
Change the method return type from void to String & give a call to xhr.responseText in alert() just like below:-
Change In Controller:
#ResponseBody
public void addStudent(#RequestBody AddStudentRequest addStudentRequest) throws StudentGroupNumberNotFoundException, SpecializationNotFoundException {
// business logic
}
to
#ResponseBody
public String addStudent(#RequestBody AddStudentRequest addStudentRequest) throws StudentGroupNumberNotFoundException, SpecializationNotFoundException {
// business logic
}
Change In JavaScript:
function addStudent() {
// ...
$.ajax({
type : "POST",
url : "student/add",
contentType : 'application/json',
data : data,
beforeSend : function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader(header, token);
},
success : function(data, status, xhr) {
alert(xhr.responseText);
},
error : function(xhr, status, errorThrown) {
alert(xhr.responseText);
},
});
}

Unit-testing methods secured with Securesocial annotation

I'm trying to make some functional tests for my webapplication that is using Play 2.1.4 and Socialsecure. Before using securesocial the tests where pretty straight forward but now im having troubles figuering out how i can make tests on the secured actions.
#Test
public void createNewNote() {
Result result;
// Should return bad request if no data is given
result = callAction(
controllers.routes.ref.Notes.newNote(),
fakeRequest().withFormUrlEncodedBody(
ImmutableMap.of("title", "", "text",
"")));
assertThat(status(result)).isEqualTo(BAD_REQUEST);
result = callAction(
controllers.routes.ref.Notes.newNote(),
fakeRequest().withFormUrlEncodedBody(
ImmutableMap.of("title", "My note title", "text",
"My note content")));
// Should return redirect status if successful
assertThat(status(result)).isEqualTo(SEE_OTHER);
assertThat(redirectLocation(result)).isEqualTo("/notes");
Note newNote = Note.find.where().eq("title", "My note title")
.findUnique();
// Should be saved to DB
assertNotNull(newNote);
assertEquals("My note title", newNote.title);
assertEquals("My note content", newNote.text);
}
As of right now i got a user in the test yml file:
- !!models.User
id: 1234567890
username: Pingu
provider: Twitter
firstName: Pingu
lastName: Pingusson
email: pingu#note.com
password: password
My user is pretty straight forward...:
#Table(
uniqueConstraints=
#UniqueConstraint(columnNames={"username"}))
#Entity
public class User extends Model {
private static final long serialVersionUID = 1L;
#Id
public String id;
public String provider;
public String firstName;
public String lastName;
public String email;
public String password;
#MinLength(5)
#MaxLength(20)
public String username;
public static Finder<String, User> find = new Finder<String, User>(
String.class, User.class);
public static User findById(String id) {
return find.where().eq("id", id).findUnique();
}
public static User findByEmail(String email) {
return find.where().eq("email", email).findUnique();
}
#Override
public String toString() {
return this.id + " - " + this.firstName;
}
}
and the UserService:
public class UserService extends BaseUserService {
public UserService(Application application) {
super(application);
}
#Override
public void doDeleteExpiredTokens() {
if (Logger.isDebugEnabled()) {
Logger.debug("deleteExpiredTokens...");
}
List<LocalToken> list = LocalToken.find.where().lt("expireAt", new DateTime().toString()).findList();
for(LocalToken localToken : list) {
localToken.delete();
}
}
#Override
public void doDeleteToken(String uuid) {
if (Logger.isDebugEnabled()) {
Logger.debug("deleteToken...");
Logger.debug(String.format("uuid = %s", uuid));
}
LocalToken localToken = LocalToken.find.byId(uuid);
if(localToken != null) {
localToken.delete();
}
}
#Override
//public Identity doFind(UserId userId) {
public Identity doFind(IdentityId identityId){
if (Logger.isDebugEnabled()) {
Logger.debug(String.format("finding by Id = %s", identityId.userId()));
}
User localUser = User.find.byId(identityId.userId());
Logger.debug(String.format("localUser = " + localUser));
if(localUser == null) return null;
SocialUser socialUser = new SocialUser(new IdentityId(localUser.id, localUser.provider),
localUser.firstName,
localUser.lastName,
String.format("%s %s", localUser.firstName, localUser.lastName),
Option.apply(localUser.email),
null,
new AuthenticationMethod("userPassword"),
null,
null,
Some.apply(new PasswordInfo("bcrypt", localUser.password, null))
);
if (Logger.isDebugEnabled()) {
Logger.debug(String.format("socialUser = %s", socialUser));
}
return socialUser;
}
#Override
public Identity doFindByEmailAndProvider(String email, String providerId) {
List<User> list = User.find.where().eq("email", email).eq("provider", providerId).findList();
if(list.size() != 1){
Logger.debug("found a null in findByEmailAndProvider...");
return null;
}
User localUser = list.get(0);
SocialUser socialUser =
new SocialUser(new IdentityId(localUser.email, localUser.provider),
localUser.firstName,
localUser.lastName,
String.format("%s %s", localUser.firstName, localUser.lastName),
Option.apply(localUser.email),
null,
new AuthenticationMethod("userPassword"),
null,
null,
Some.apply(new PasswordInfo("bcrypt", localUser.password, null))
);
return socialUser;
}
#Override
public Token doFindToken(String token) {
if (Logger.isDebugEnabled()) {
Logger.debug("findToken...");
Logger.debug(String.format("token = %s", token));
}
LocalToken localToken = LocalToken.find.byId(token);
if(localToken == null) return null;
Token result = new Token();
result.uuid = localToken.uuid;
result.creationTime = new DateTime(localToken.createdAt);
result.email = localToken.email;
result.expirationTime = new DateTime(localToken.expireAt);
result.isSignUp = localToken.isSignUp;
if (Logger.isDebugEnabled()) {
Logger.debug(String.format("foundToken = %s", result));
}
return result;
}
#Override
public Identity doSave(Identity user) {
if (Logger.isDebugEnabled()) {
Logger.debug("save...!_!");
Logger.debug(String.format("user = %s", user));
}
User localUser = null;
localUser = User.find.byId(user.identityId().userId());
Logger.debug("id = " + user.identityId().userId());
Logger.debug("provider = " + user.identityId().providerId());
Logger.debug("firstName = " + user.firstName());
Logger.debug("lastName = " + user.lastName());
Logger.debug(user.fullName() + "");
Logger.debug("email = " + user.email());
Logger.debug(user.email().getClass() + "");
if (localUser == null) {
Logger.debug("adding new...");
localUser = new User();
localUser.id = user.identityId().userId();
localUser.provider = user.identityId().providerId();
localUser.firstName = user.firstName();
localUser.lastName = user.lastName();
//Temporary solution for twitter which does not have email in OAuth answer
if(!(user.email().toString()).equals("None")){
localUser.email = user.email().get();
}
if(!(user.passwordInfo() + "").equals("None")){
localUser.password = user.passwordInfo().get().password();
}
localUser.save();
} else {
Logger.debug("existing one...");
localUser.id = user.identityId().userId();
localUser.provider = user.identityId().providerId();
localUser.firstName = user.firstName();
localUser.lastName = user.lastName();
//Temporary solution for twitter which does not have email in OAuth answer
if(!(user.email().toString()).equals("None")){
localUser.email = user.email().get();
}
if(!(user.passwordInfo() + "").equals("None")){
localUser.password = user.passwordInfo().get().password();
}
localUser.update();
}
return user;
}
#Override
public void doSave(Token token) {
LocalToken localToken = new LocalToken();
localToken.uuid = token.uuid;
localToken.email = token.email;
try {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
localToken.createdAt = df.parse(token.creationTime.toString("yyyy-MM-dd HH:mm:ss"));
localToken.expireAt = df.parse(token.expirationTime.toString("yyyy-MM-dd HH:mm:ss"));
} catch (ParseException e) {
Logger.error("UserService.doSave(): ", e);
}
localToken.isSignUp = token.isSignUp;
localToken.save();
}
}
As of my understanding i should in someway set the session so the user is logged in by using the .withsession method on the fakerequest and maybe also set some value on the serverside.
Tried searching the web for examples using securesocial and play but found no tests at all.
How can i login in my user so i can preform the tests?
Best regards
Rawa
Thanks to David Weinbergs comment i was able to solve this after some trail and error. (:
I started out my LocalUser implementation from this reply:
https://stackoverflow.com/a/18589402/1724097
This is how i solved it:
To make unit tests i created a local user in the database, using the test-data.yml file:
- !!models.LocalUser
id: 1234567890
username: Username
provider: userpass
firstName: firstName
lastName: lastName
email: user#example.com
#hash for "password"
password: $2a$10$.VE.rwJFMblRv2HIqhZM5.CiqzYOhhJyLYrKpMmwXar6Vp58U7flW
Then i made a test utils class that create my fakeCookie.
import models.LocalUser;
import play.Logger;
import securesocial.core.Authenticator;
import securesocial.core.IdentityId;
import securesocial.core.SocialUser;
import securesocial.core.PasswordInfo;
import scala.Some;
import securesocial.core.AuthenticationMethod;
import scala.Option;
import scala.util.Right;
import scala.util.Either;
import play.mvc.Http.Cookie;
public class Utils {
public static Cookie fakeCookie(String user){
LocalUser localUser = LocalUser.findByEmail(user);
Logger.debug("Username: " + localUser.username +" - ID: " + localUser.id);
SocialUser socialUser = new SocialUser(new IdentityId(localUser.id, localUser.provider),
localUser.firstName,
localUser.lastName,
String.format("%s %s", localUser.firstName, localUser.lastName),
Option.apply(localUser.email),
null,
new AuthenticationMethod("userPassword"),
null,
null,
Some.apply(new PasswordInfo("bcrypt", localUser.password, null))
);
Either either = Authenticator.create(socialUser);
Authenticator auth = (Authenticator) either.right().get();
play.api.mvc.Cookie scalaCookie = auth.toCookie();
//debug loggig
Logger.debug("Cookie data:");
Logger.debug("Name: " + "Value: " + auth.cookieName() + " | Class: " + auth.cookieName().getClass() + " | Should be type: " + "java.lang.String");
Logger.debug("Value: " + "Value: " + scalaCookie.value() + " | Class: " + scalaCookie.value().getClass() + " | Should be type: " + "java.lang.String");
Logger.debug("MaxAge: " + "Value: " + scalaCookie.maxAge() + " | Class: " + scalaCookie.maxAge().getClass() + " | Should be type: " + "int");
Logger.debug("Path: " + "Value: " + scalaCookie.path() + " | Class: " + scalaCookie.path().getClass() + " | Should be type: " + "java.lang.String");
Logger.debug("Domain: " + "Value: " + scalaCookie.domain() + " | Class: " + auth.cookieDomain().getClass() + " | Should be type: " + "java.lang.String");
Logger.debug("Secure: " + "Value: " + auth.cookieSecure() + " | Class: " + "Boolean" + " | Should be type: " + "boolean");
Logger.debug("HttpOnly: " + "Value: " + auth.cookieHttpOnly() + " | Class: " + "Boolean" + " | Should be type: " + "boolean");
// secureSocial doesnt seem to set a maxAge or Domain so i set them myself.
Cookie fakeCookie = new Cookie(auth.cookieName(), scalaCookie.value(), 120, scalaCookie.path(), "None", auth.cookieSecure(), auth.cookieHttpOnly());
return fakeCookie;
}
}
And then i simply use my cookie to in the fakeRequest so im logged in:
Cookie cookie = Utils.fakeCookie("user#example.com");
Result result = callAction(
controllers.routes.ref.yourSampleClass.yourSecuredFucntion(),
fakeRequest().withFormUrlEncodedBody(
ImmutableMap.of("Value", "Some input value")).withCookies(cookie));
// Should return redirect status if successful
assertThat(status(result)).isEqualTo(SEE_OTHER);
assertThat(redirectLocation(result)).isEqualTo("/yourWantedResult");
Hope this helps others!

POST on JAVA Restful WebService URL from JavaScript

I have implemented a RESTful web Service in java which inserts data into MySQL db, I have tested this using POSTER in mozila firefox and also in google chrome. My Web Service takes a String with the POST request, now I am unable to utilize WEB SERVICE using JS: the code making POST request on WEB SERVICE URL is as follows:
$.ajax({
url: 'http://localhost:8080/AgentWS/webresources/Items',
type: 'POST',
contentType: 'application/xml',
dataType: 'xml',
data: 'content='+content,
success: function (data) {
alert(content);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + errorThrown);
}
});
The alert in success function is also not displayed plus the dialog error is showing a dialog with : Error: on it'
Server Side code is:
#POST
#Consumes("application/xml")
#Produces("application/xml")
public String postXml(String content) {
//TODO
// return Response.created(context.getAbsolutePath()).build();
StringTokenizer sp = new StringTokenizer(content, "&");
String agentName = sp.nextToken();
String agentId = sp.nextToken();
String agentState = sp.nextToken();
String agentExtension = sp.nextToken();
String agentDeviceState = sp.nextToken();
String agentDeviceStateChangeTime = sp.nextToken();
DBConection conn = new DBConection();
conn.insertAgentActivityInfo(agentName, agentId, agentState, agentExtension, agentDeviceState, agentDeviceStateChangeTime);
return agentName + " " + agentId + " " + agentState + " " + agentExtension + " " + agentDeviceState + " " + agentDeviceStateChangeTime;
}
I think the problem is with the data you are sending,
data: 'content='+content should be replaced with a name for the parameter like
data: {content:'content='+content}
and check what you are doing on the server side
My guess is that data: 'content='+content, is posting invalid XML to the server and you are getting 500 Internal Server Error. Can you try setting the data to just the XML content? like
...
data: content,
....
EDIT
If all you want is a simple post
Java
#POST
public String postXml(String content) {
//TODO
// return Response.created(context.getAbsolutePath()).build();
StringTokenizer sp = new StringTokenizer(content, "&");
String agentName = sp.nextToken();
...
return agentName + " " + agentId + " " + agentState + " " + agentExtension + " " + agentDeviceState + " " + agentDeviceStateChangeTime;
}
Javascript
$.ajax({
url: '/AgentWS/webresources/Items',
type: 'POST',
data: 'content=1&2&3&4&5&5',
success: function (data) {
alert(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + errorThrown);
}
});
Here's what i think, you should write a model class Agent in server side like this :
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Agent
{
private String agentName;
private String agentId;
private String agentState;
private String agentExtension;
private String agentDeviceState;
private String agentDeviceStateChangeTime;
public String getAgentName() {
return agentName;
}
public void setAgentName(String agentName) {
this.agentName = agentName;
}
public String getAgentId() {
return agentId;
}
public void setAgentId(String agentId) {
this.agentId = agentId;
}
public String getAgentState() {
return agentState;
}
public void setAgentState(String agentState) {
this.agentState = agentState;
}
public String getAgentExtension() {
return agentExtension;
}
public void setAgentExtension(String agentExtension) {
this.agentExtension = agentExtension;
}
public String getAgentDeviceState() {
return agentDeviceState;
}
public void setAgentDeviceState(String agentDeviceState) {
this.agentDeviceState = agentDeviceState;
}
public String getAgentDeviceStateChangeTime() {
return agentDeviceStateChangeTime;
}
public void setAgentDeviceStateChangeTime(String agentDeviceStateChangeTime) {
this.agentDeviceStateChangeTime = agentDeviceStateChangeTime;
}
}
And the server rest service that you have should be changed little bit :
#POST
#Consumes("application/xml")
#Produces("application/xml")
public String postXml(Agent agent) {}
Inside this method you can use "agent" object, that is passed, to retrieve all the values sent by the client like agent.getAgentName()
Now the payload(or request body) that should contain something like this:
<Agent>
<agentName></agentName>
<agentId></agentId>
<agentState></agentState>
<agentExtension></agentExtension>
<agentDeviceState></agentDeviceState>
<agentDeviceStateChangeTime></agentDeviceStateChangeTime>
</Agent>
I hope it is of some assistance.
Hard to guess without the error code and message but:
change
data: 'content='+content
to
data: { content : content } // format as json
And in your java resource:
#POST
#Consumes(MediaType.APPLICATION_JSON)
public String postXml(String content)
// read content as json

Categories

Resources