Error on Spring REST webservice call - web-services

I have following webservice call
#RequestMapping(value = "modifyUser/{userDn}", method = RequestMethod.POST, headers="Accept=application/json")
public #ResponseBody
JSONObject modifyUser(#PathVariable String userDn, #RequestBody DirectoryUser directoryUser) {
// Modify User
boolean modifiedUser = this.authenticationService.modifyUser(userDn, directoryUser.getPassword(), directoryUser);
// Build JSONObject
JSONObject jsonObject = new JSONObject();
jsonObject.put("modifyUser", modifiedUser);
return jsonObject;
}
I am using following client method to access above REST webservice.
String url = "http://www.local.com:8080/CommonAuth-1.0-SNAPSHOT/api/authentication/modifyUser/";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url + "user6.external")
JSONObject ob = new JSONObject();
ob.put("description", "updated");
System.out.println(ob.toString());
StringEntity entity = new StringEntity(ob.toString());
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
I always get "The server refused this request because the request entity is in a format not supported by the requested resource for the requested method" error. What is wrong in my code. I am able to access other webservice calls without using #RequestBody and using simple path variables. The issue is with #RequestBody and how i am using HttpPost.
public class DirectoryUser {
private String displayName;
private String fullName;
private String userName;
private String firstName;
private String lastName;
private String description;
private String country;
private String company;
private String phone;
private String emailAddress;
private String password;
private boolean expirePassword = true;
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isExpirePassword() {
return expirePassword;
}
public void setExpirePassword(boolean expirePassword) {
this.expirePassword = expirePassword;
}
}
JSON string i am posting is {"description":"updated"}

try {
/* your code */
if (httpResponse != null) {
InputStream in = httpResponse.getEntity().getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n > 0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n > 0)
out.append(new String(b, 0, n));
}
System.out.println(out.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
Can you check what the status code says? Also, please check if it is HTTPS.

By default Spring try to use Jackson for json marshall/unmarshall:
private static final boolean jackson2Present =
ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", WebMvcConfigurationSupport.class.getClassLoader()) &&
ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", WebMvcConfigurationSupport.class.getClassLoader());
you need to add Jackson libs to your project.

Related

How to process "data" part of GCP PubSub message into a HashMap?

I'm getting pubsub message as below :
{
"data": {
"systemId": "system-1",
"userId": "userId-1",
"departmentId": "090",
"enrolmentDateTime": "2022-08-19T15:44:29.080Z",
"event_type": "REGISTRATION"
}
}
I want to further process this message in my springboot application based on the "event_type".
How can I just fetch "event_type" from this message and use it for comparison?
Any suggestions?
For eg I want to have processing like this :
if(event_type.equals("REGISTRATION")) { registrationHandler.handle(message); else { }
I have tried converting a PubSubMessage into string and then further map it to HashMap using ObjectMapper, but that gives me "data" as key and rest of the json part as a value.
public void process(final PubsubMessage message) throws ConsumerException {
String data = message.getData().toStringUtf8();
try {
ObjectMapper mapper = new ObjectMapper();
HashMap<String, String> dataMap = mapper.readValue(data, HashMap.class);
} ....
Instead of using a Map, you can use a typed object, example :
PubSubData.java file :
public class PubSubData {
private String systemId;
private String userId;
private String departmentId;
private String enrolmentDateTime;
private String event_type;
public PubSubData() {
}
public String getSystemId() {
return systemId;
}
public void setSystemId(String systemId) {
this.systemId = systemId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getDepartmentId() {
return departmentId;
}
public void setDepartmentId(String departmentId) {
this.departmentId = departmentId;
}
public String getEnrolmentDateTime() {
return enrolmentDateTime;
}
public void setEnrolmentDateTime(String enrolmentDateTime) {
this.enrolmentDateTime = enrolmentDateTime;
}
public String getEvent_type() {
return event_type;
}
public void setEvent_type(String event_type) {
this.event_type = event_type;
}
}
PubSubResult.java file :
public class PubSubResult {
private PubSubData data;
public PubSubResult() {
}
public PubSubData getData() {
return data;
}
public void setData(PubSubData data) {
this.data = data;
}
}
Example of an unit test that deserializes data from PubsubMessage to the PubSubResult object :
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.google.protobuf.ByteString;
import com.google.pubsub.v1.PubsubMessage;
import org.junit.Test;
public class MyTest {
private static final ObjectMapper OBJECT_MAPPER;
static {
final ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE, false);
OBJECT_MAPPER = mapper;
}
#Test
public void testDeserializePubSubData() {
final String data = "{\n" +
" \"data\": {\n" +
" \"systemId\": \"system-1\",\n" +
" \"userId\": \"userId-1\",\n" +
" \"departmentId\": \"090\",\n" +
" \"enrolmentDateTime\": \"2022-08-19T15:44:29.080Z\",\n" +
" \"event_type\": \"REGISTRATION\"\n" +
" }\n" +
"}";
final PubsubMessage message = PubsubMessage.newBuilder()
.setData(ByteString.copyFrom(data.getBytes()))
.build();
final String dataResult = message.getData().toStringUtf8();
final PubSubResult resultData = deserialize(dataResult);
// Access to the event type.
final String eventType = resultData.getData().getEvent_type();
}
private PubSubResult deserialize(final String value) {
try {
return OBJECT_MAPPER.readValue(value, PubSubResult.class);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Error !!", e);
}
}
}

Having a composition relationship in ASP .NET?

I have a Car composed by a Driver. I have problems showing either informations on the gridview. It's only shows Car's info. on the gridview, and I wanna display like: Car: Lancia Driver: Sandro, something like that.
Here's the code:
Car:
[Serializable]
public class Car
{
public String Brand { get; set; }
public String Model { get; set; }
public int Year { get; set; }
public Driver Driver { get; set; }
public Car(String Brand, String Model, int Year, Driver Driver)
{
Brand = Brand;
Model = Model;
Year = Year;
Driver = Driver;
}
public Car()
{
Init();
}
public void Init()
{
Brand = string.Empty;
Model = string.Empty;
Year = 0;
Driver = new Driver();
}
Driver:
[Serializable]
public class Driver
{
public String Name { get; set; }
public int Age { get; set; }
public String Nationality { get; set; }
public Driver(String Name, int Age, String Nationality)
{
Name = Name;
Age = Age;
Nationality = Nationality;
}
public Driver()
{
Init();
}
public void Init()
{
Name = string.Empty;
Age = 0;
Nationality = string.Empty;
}
}
aspx.cs:
public partial class WebForm1 : System.Web.UI.Page
{
//private ArrayList garageList;
private List<Car> garageList;
private static int counterPost = 0;
private static int counterLoad = 0;
public void Page_Load(object sender, EventArgs e)
{
TextBox masterTextLoad = (TextBox) Master.FindControl("txtLoad");
masterTextLoad.Text = Convert.ToString(counterLoad++);
if (IsPostBack)
{
TextBox masterTextPost = (TextBox) Master.FindControl("txtPost");
masterTextPost.Text = Convert.ToString(counterPost++);
garageList = (List<Car>)ViewState["Cars"];
//garageList = (ArrayList) ViewState["Cars"];
if (garageList == null)
{
//garageList = new ArrayList();
garageList = new List<Car>();
}
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
//Driver
Driver driver = new Driver();
TextBox driverName = (TextBox) Master.FindControl("txtName");
driver.Name = driverName.Text;
TextBox driverAge = (TextBox) Master.FindControl("txtAge");
driver.Age = Convert.ToInt32(driverAge.Text);
TextBox driverNationality = (TextBox)Master.FindControl("txtNationality");
driver.Nationality = driverNationality.Text;
//Car
Car car = new Car();
car.Brand = txtBrand.Text;
car.Model = txtModel.Text;
car.Year = Int32.Parse(txtYear.Text);
garageList.Add(car);
//ViewState["Cars"] = garageList;
ViewState["garageList"] = garageList;
cleanControls();
}
private void cleanControls()
{
//Cleaning driver controls
TextBox masterTextPost = (TextBox)Master.FindControl("txtPost");
masterTextPost.Text = string.Empty;
TextBox driverName = (TextBox)Master.FindControl("txtName");
driverName.Text = string.Empty;
TextBox driverAge = (TextBox)Master.FindControl("txtAge");
driverAge.Text= string.Empty;
TextBox driverNationality = (TextBox)Master.FindControl("txtNationality");
driverNationality.Text = string.Empty;
//Cleaning Car controls
txtBrand.Text = String.Empty;
txtModel.Text = String.Empty;
txtYear.Text = String.Empty;
}
protected void btnShow_Click1(object sender, EventArgs e)
{
grvShow.AutoGenerateColumns = true;
grvShow.DataSource = garageList;
grvShow.DataBind();
//grvShow.Visible = true;
}
}

Unable to view the jaxrs restful webservice

I am new to jaxrs , i followed this http://www.youtube.com/watch?v=-Aec0KEDdzE tutorial for creating and deploying a restful web application and i also created a entity class and created a restful web service from a entity class and the when i deployed it from the server and when typed the path of the service i get page not found error from server and the web application is working contents from the web application can be viewed on the web page but unable to view the restful web service
package com.example.example;
import java.io.Serializable;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.xml.bind.annotation.XmlRootElement;
#javax.persistence.Entity
#XmlRootElement
public class Entity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Entity)) {
return false;
}
Entity other = (Entity) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
private String firstName;
/**
* Get the value of firstName
*
* #return the value of firstName
*/
public String getFirstName() {
return firstName;
}
/**
* Set the value of firstName
*
* #param firstName new value of firstName
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
private String lastName;
/**
* Get the value of lastName
*
* #return the value of lastName
*/
public String getLastName() {
return lastName;
}
/**
* Set the value of lastName
*
* #param lastName new value of lastName
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Override
public String toString() {
return "com.example.example.Entity[ id=" + id + " ]";
}
}

Powermock - how to mock a specific method and leave the rest of the object as-is

I have a Person class with get set for FirstName, LastName
A TestClass to execute TestCase1
Can we just only mock a specific method (getLastName) and leave every thing else (other internal fields, functions ... as-is)?
public class Person {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
import static org.powermock.api.easymock.PowerMock.*;
import static org.easymock.EasyMock.expect;
#RunWith(PowerMockRunner.class)
#PrepareForTest ( {Person.class} )
public class TestClass {
#Test
public void TestCase1() {
Person person = createNiceMock(Person.class);
person.setFirstName = "First name";
expect(person.getLastName()).andReturn("Fixed value").anyTimes();
replayAll();
String ln = person.getLastName(); //will return "Fixed value";
String fn = person.getFirstName();
// Currently it returns null because of createNiceMock
// but I want it to return "First name" (value has been set to mock object)
// Is it possible?
verifyAll();
}
}
You can use spy to mock individual (including private) methods:
Person classUnderTest = PowerMockito.spy(new Person());
// use PowerMockito to set up your expectation
PowerMockito.doReturn("Fixed value").when(classUnderTest, "getLastName");

Hibernate querying issue

I have the following code on the webservice that uses Hibernate
Session session = ICDBHibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
User user = (User) session.load(User.class, userid);
userId is a paramter sent from the client.
User class
package com.icdb.data;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
public class User implements java.io.Serializable {
private Integer userid;
private String username;
private String email;
private String password;
private String firstname;
private String lastname;
// private String streetaddress;
// private String city;
// private String phone;
private String state;
private String country;
private Date birthdate;
// private String zipcode;
private Set usersesForFavoriteuser = new HashSet(0);
private Set recipetipses = new HashSet(0);
private Set recipeses = new HashSet(0);
private Set recipepictureses = new HashSet(0);
private Set onlineuserses = new HashSet(0);
private Set generaltipses = new HashSet(0);
private Set usersesForFollowinguser = new HashSet(0);
private Set recipereviewses = new HashSet(0);
public User() {
}
public User( String username,
String password,
String email,
String firstname,
String lastname,
// String streetaddress,
// String city,
// String phone,
String state,
String country,
Date birthdate )
// String zipcode )
{
this.username = username;
this.password = password;
this.email = email;
this.firstname = firstname;
this.lastname = lastname;
// this.streetaddress = streetaddress;
// this.city = city;
// this.phone = phone;
this.state = state;
this.country = country;
this.birthdate = birthdate;
// this.zipcode = zipcode;
}
public User( String username,
String password,
String email,
String firstname,
String lastname,
// String streetaddress,
// String city,
String phone,
// String state,
// String country,
// String email,
Date birthdate,
// String zipcode,
Set usersesForFavoriteuser,
Set recipetipses,
Set recipeses,
Set recipepictureses,
Set onlineuserses,
Set generaltipses,
Set usersesForFollowinguser,
Set recipereviewses )
{
this.username = username;
this.password = password;
this.email = email;
this.firstname = firstname;
this.lastname = lastname;
// this.streetaddress = streetaddress;
// this.city = city;
// this.phone = phone;
this.state = state;
this.country = country;
this.birthdate = birthdate;
// this.zipcode = zipcode;
this.usersesForFavoriteuser = usersesForFavoriteuser;
this.recipetipses = recipetipses;
this.recipeses = recipeses;
this.recipepictureses = recipepictureses;
this.onlineuserses = onlineuserses;
this.generaltipses = generaltipses;
this.usersesForFollowinguser = usersesForFollowinguser;
this.recipereviewses = recipereviewses;
}
public Integer getUserid() {
return this.userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstname() {
return this.firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return this.lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
// public String getStreetaddress() {
// return this.streetaddress;
// }
// public void setStreetaddress(String streetaddress) {
// this.streetaddress = streetaddress;
// }
// public String getCity() {
// return this.city;
// }
// public void setCity(String city) {
// this.city = city;
// }
// public String getPhone() {
// return this.phone;
// }
// public void setPhone(String phone) {
// this.phone = phone;
// }
public String getState() {
return this.state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return this.country;
}
public void setCountry(String country) {
this.country = country;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getBirthdate() {
return this.birthdate;
}
public void setBirthdate(Date birthdate) {
this.birthdate = birthdate;
}
// public String getZipcode() {
// return this.zipcode;
// }
// public void setZipcode(String zipcode) {
// this.zipcode = zipcode;
// }
public Set getUsersesForFavoriteuser() {
return this.usersesForFavoriteuser;
}
public void setUsersesForFavoriteuser(Set usersesForFavoriteuser) {
this.usersesForFavoriteuser = usersesForFavoriteuser;
}
public Set getRecipetipses() {
return this.recipetipses;
}
public void setRecipetipses(Set recipetipses) {
this.recipetipses = recipetipses;
}
public Set getRecipeses() {
return this.recipeses;
}
public void setRecipeses(Set recipeses) {
this.recipeses = recipeses;
}
public Set getRecipepictureses() {
return this.recipepictureses;
}
public void setRecipepictureses(Set recipepictureses) {
this.recipepictureses = recipepictureses;
}
public Set getOnlineuserses() {
return this.onlineuserses;
}
public void setOnlineuserses(Set onlineuserses) {
this.onlineuserses = onlineuserses;
}
public Set getGeneraltipses() {
return this.generaltipses;
}
public void setGeneraltipses(Set generaltipses) {
this.generaltipses = generaltipses;
}
public Set getUsersesForFollowinguser() {
return this.usersesForFollowinguser;
}
public void setUsersesForFollowinguser(Set usersesForFollowinguser) {
this.usersesForFollowinguser = usersesForFollowinguser;
}
public Set getRecipereviewses() {
return this.recipereviewses;
}
public void setRecipereviewses(Set recipereviewses) {
this.recipereviewses = recipereviewses;
}
}
also userId defined in the .hbm.xml as
<id name="userid" type="java.lang.Integer">
<column name="userid"/>
<generator class="identity"/>
</id>
So we have a table of users and another tables that its FK is userId.
I need to update the code to handle the request with a username - and then retrieve the userId instead of the mentioned code of the webservice.
Please help :)
Yoav
// I assume username is unique
// username is a parameter
// to get the full user object by name
String queryString = "from User where username = :username";
Query query = session.createQuery(queryString);
query.setString(":username", username);
User user = (User) query.uniqueResult();
// to get just the id
String queryString = "userid from User where username = :username";
Query query = session.createQuery(queryString);
query.setString(":username", username);
Integer userid = (Integer) query.uniqueResult();