Getting null values in REST web service PUT command - web-services

I am writing a PUT request REST web service. I have a POJO User.java having String name. Below is my POJO:
#XmlRootElement(name = "User")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private String Name;
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public User() {
}
public User(String Name) {
this.Name = Name;
}
}
My Web service is as below:
#Path("/user")
public class UserService {
#Path("/xml")
#PUT
#Produces({MediaType.APPLICATION_XML})
#Consumes({MediaType.APPLICATION_XML})
public User putUsers(User user){
System.out.println("***** Received User XML *****");
System.out.println("Name :: "+user.getName());
return user;
}
}
From Postman, i am sending below in Request body:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><User>
<Name>abcd</Name></User>
and PUT URL executed:
http://localhost:8080/rest/users/xml
But i am getting null as output:
***** Received User XML *****
Name :: null
Why am i not getting abcd as output?

Ok.. i found the answer..
1) I just added #XmlElement(name = "Name") above the getter getName().
2) Changed it to small n in the variable declaration Name as 'name'.
This fixed it.

Related

How get token from headers to test my controller by mocking the service class

public class AdditionDto
{
public int HttpCode {get; set:}
public string UserName {get; set:}
public int Total {get; set:}
}
public interface IAddtionService
{
AdditionDto AddingTwoNumbers(int input1, int input2, string userName);
}
public class AdditionService : IAdditionService
{
public AdditionDto AddingTwoNumbers(int input1, int input2, string userName)
{
AdditionDto addDto = new AdditionDto()
{
httpCode = 200,
UserName = userName,
Total = input1 + input2
}
return addDto;
}
}
With a controller like this:
public class AdditionController : ControllerBase
{
private readonly IAddtionService _additionService;
public AdditionController(IAddtionService additionService)
{
_additionService = additionService;
}
[HttpGet]
[Authorize(Roles = "Admin")]
[Route("AddtionOfTwoNumbers")]
public IActionResult AddTwoNumbers(int input1, int input2)
{
if (ModelState.IsValid)
{
var token = HttpContext.Request.Headers["Authorization"].ToString();
var tokenbearer = token.Split(' ');
var handler = new JwtSecurityTokenHandler();
var decodedtoken = handler.ReadJwtToken(tokenbearer[1]);
string user = decodedtoken.Claims.Where(x => x.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name").FirstOrDefault().ToString();
var usr = user.Split(":");
string userName = usr[2].Trim();
var result = _additionService.AddingTwoNumbers(input1, input2,userName);
if (result.Httpcode == 200)
return Ok(result);
else
return StatusCode(500, result);
}
else
return BadRequest();
}
}
When i am trying to conduct xunit test on this api I am getting null at header level.
also I need to mock service method that is also not happening. mostly it is showing null exception even I have passed token in the headers also then I am facing mocking issue at the service method level. could you please help me to mock my service method to test that api through xunit framework....

Retrieve data of type Date from the DB with Postman

I don't receive the value that I entered in my DB, when I get a response back from Postman. I make and POST Request with Postman and when I verify in my DB it's OK.
When I make a GET Request with Postman, the result of my request is an empty array and I don't know why.
Please need help!
Thank you.
/************* Model *************/
#Entity
#EntityListeners(AuditingEntityListener.class)
#Table
public class RDV implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long idRDV;
#Column(nullable = false)
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm")
#NotNull
private Date dateRDV;
private String nomRDV;
Getters and setters { ... }
/************** Controller ************/
#GetMapping(path="/rdv/getbydate/{dateRDV}")
public List<RDV> getEventsByDate(#PathVariable("dateRDV")
#DateTimeFormat(pattern="yyyy-MM-dd") Date dateRDV)
{
return rdvService.FindByDateRDV(dateRDV);
}
/*************** Service **************/
public interface RDVService {
List<RDV> getRDVs();
RDV saveRDV(RDV rdv);
RDV updateRDV(RDV rdv);
void deleteRDV (Long id);
List<RDV> FindByNomRDV(String nomRDV);
List<RDV> FindByDateRDV(Date dateRDV);
}
/************ Service Implementation **********/
#Override
public List<RDV> FindByDateRDV(Date dateRDV) {
return rdvRepository.findByDateRDV(dateRDV);
}
/*********** Repository ***************/
#Repository
public interface RDVRepository extends JpaRepository<RDV, Long> {
List<RDV> findByNomRDV(String nomRDV);
List<RDV> findByDateRDV(Date dateRDV); }
What I'm expecting is the result of this request :
SELECT daterdv, nomrdv FROM RDV where daterdv LIKE '2018-06-20'

how can i resolve this "Etat HTTP 500 - java.lang.NullPointerException"?

i'm developping a restful web service that extract data (messages) from my database and return all messages!
every single message is a MsgBean ( with an id, contenu, from, numexp,... )
the web service couldn't return a table so i created a new object that contain a table (msgTable) of MsgBean !
while running my web service on the rest console, i got this error :
Etat HTTP 500 - java.lang.NullPointerException
type Rapport d''exception
message java.lang.NullPointerException
description Le serveur a rencontré une erreur interne qui l''a empêché de satisfaire la requête.
Click to see the rest of error
my MsgBean is :
#XmlRootElement
public class MsgBean implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String frommm;
private String contenu;
private String DateEnvoi;
private String NumExp;
private int idu;
public MsgBean(){};
#XmlElement
public int getIdu() {
return idu;
}
public void setIdu(int idu) {
this.idu = idu;
}
#XmlElement
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#XmlElement
public String getFrommm() {
return frommm;
}
public void setFrommm(String frommm) {
this.frommm = frommm;
}
#XmlElement
public String getContenu() {
return contenu;
}
public void setContenu(String contenu) {
this.contenu = contenu;
}
#XmlElement
public String getDateEnvoi() {
return DateEnvoi;
}
public void setDateEnvoi(String DateEnvoi) {
this.DateEnvoi = DateEnvoi;
}
#XmlElement
public String getNumExp() {
return NumExp;
}
public void setNumExp(String NameExp) {
this.NumExp = NameExp;
}
}
my msgTabl is :
#XmlRootElement
public class msgTabl implements Serializable {
String test;
MsgBean[] m = new MsgBean[100];
public msgTabl(){};
#XmlElement
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
#XmlElement
public MsgBean getM(int i) {
return m[i];
}
public void setM(int i, MsgBean mb) {
this.m[i].setId(mb.getId());
this.m[i].setIdu(mb.getIdu());
this.m[i].setFrommm(mb.getFrommm());
this.m[i].setNumExp(mb.getNumExp());
this.m[i].setDateEnvoi(mb.getDateEnvoi());
this.m[i].setContenu(mb.getContenu());
}
}
and here is the web service that i did test with :
#GET
#Path("/historiquemethod")
#Produces("application/json")
//#Produces("text/plain")
public msgTabl historique(
#QueryParam("pseudo") String pseudo,
#QueryParam("motDePasse") String motDePasse
) {
msgTabl tab = new msgTabl();
MsgBean ms = new MsgBean();
// set information into our msg to test
ms.setContenu("contenu");
ms.setFrommm("8080");
ms.setNumExp("2584126");
ms.setId(1);
ms.setIdu(2);
ms.setDateEnvoi("date");
// set the message into the first table case
tab.setM(0, ms);
tab.setTest("ok");
return tab;
}
In setM method do this in first line :
this.m[i] = new MsgBean();
Problem is that you have instantiated your array but the objects are null inside that array. So you need to first instantiate the object at required index and then use it.
UPDATE FOR COMMENT
Make a getter method for your m like this getM() and annotate it with XmlElement(Remove the annotation from your current overloaded getM(int i) method). The method getM(int i) cannot be used by JAXB, since jaxb needs simple getter and setter for your properties.

Webservice with different datatype?

I'm writing one of my very first web-service, as far as now it was more than ok, but when I'm trying to create sperate class:
public class Workers {
private String name;
private String surname;
private boolean type;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public boolean isType() {
return type;
}
public void setType(boolean type) {
this.type = type;
}
public Workers(String name, String surname, boolean type) {
this.name = name;
this.surname = surname;
this.type = type;
}
}
and than to use it in webservice like this:
#WebMethod(operationName = "SelectWorker")
public Pracownicy SelectWorker(#WebParam(name = "username") String username, #WebParam(name = "password") String password) {
ResultSet rs = null;
String name = null;
String surname = null;
boolean type = false;
PreparedStatement st = null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("db_address", "login", "password");
System.out.println("connection status: " +con);
st = con.prepareStatement("select name, surname from clients where login = ? and passwd= ?");
st.setString(1, username);
st.setString(2, password);
rs = st.executeQuery();
if (rs.next()) {
name = rs.getString(2);
surname=rs.getString(3);
type = rs.getBoolean(5);
Workers pr = new Workers(name, surname, type);
return pr;
}
} catch (Exception e) {
System.out.println("error: " + e.toString());
}
return null;
}
the body of method can be empty or filled with code, it doesn't matter - I'm getting the same error:
Error occurred during deployment: Exception while loading the app
:java.lang.IllegalStateException: ContainerBase.addChild: start:
org.apache.catalina.LifecycleException: java.lang.RuntimeException: Servlet web
service endpoint '' failure.
Are the int, string, boolean etc only allowed as return type?
there is by no means enough information given in your post... How are you creating the web service (I guess with an #WebService), your're telling it does not matter if method SelectWorker (which btw should be called selectWorker by proper naming conventions) is empty or not, but with an empty body your source would not even compile...
what I can tell you: int, String, boolean are not the only allowed return types. You can of course also return instances of your classes from a web service.
For future googlers :
I've had the same error, and checked the server log and got the error :
Two classes have the same XML type name
Which I found wierd but adding this :
#XmlType(namespace="someName")
To my class I was trying to return ( I chose the same name of the class) fixed the problem.
I had this problem, the glassfish was on Linux environment. check your $JAVA_HOME
it should be set in to jdk
export JAVA_HOME=/usr/java/jdk1.7.0_55
/opt/glassfish4/glassfish/bin # echo $JAVA_HOME
/usr/java/jdk1.7.0_55
then problem was solved..

How to fake a validation error in a MonoRail controller unit-test?

I am running on Castle's trunk, and trying to unit-test a controller-action where validation of my DTO is set up. The controller inherits from SmartDispatcherController. The action and DTO look like:
[AccessibleThrough(Verb.Post)]
public void Register([DataBind(KeyReg, Validate = true)] UserRegisterDto dto)
{
CancelView();
if (HasValidationError(dto))
{
Flash[KeyReg] = dto;
Errors = GetErrorSummary(dto);
RedirectToAction(KeyIndex);
}
else
{
var user = new User { Email = dto.Email };
// TODO: Need to associate User with an Owning Account
membership.AddUser(user, dto.Password);
RedirectToAction(KeyIndex);
}
}
public class UserRegisterDto
{
[ValidateNonEmpty]
[ValidateLength(1, 100)]
[ValidateEmail]
public string Email { get; set; }
[ValidateSameAs("Email")]
public string EmailConfirm { get; set; }
[ValidateNonEmpty]
public string Password { get; set; }
[ValidateSameAs("Password")]
public string PasswordConfirm { get; set; }
// TODO: validate is not empty Guid
[ValidateNonEmpty]
public string OwningAccountIdString { get; set; }
public Guid OwningAccountId
{
get { return new Guid(OwningAccountIdString); }
}
[ValidateLength(0, 40)]
public string FirstName { get; set; }
[ValidateLength(0, 60)]
public string LastName { get; set; }
}
The unit test looks like:
[Fact]
public void Register_ShouldPreventInValidRequest()
{
PrepareController(home, ThorController.KeyPublic, ThorController.KeyHome, HomeController.KeyRegister);
var dto = new UserRegisterDto { Email = "ff" };
home.Register(dto);
Assert.True(Response.WasRedirected);
Assert.Contains("/public/home/index", Response.RedirectedTo);
Assert.NotNull(home.Errors);
}
("home" is my HomeController instance in the test; home.Errors holds a reference to an ErrorSummary which should be put into the Flash when there's a validation error).
I am seeing the debugger think that dto has no validation error; it clearly should have several failures, the way the test runs.
I have read Joey's blog post on this, but it looks like the Castle trunk has moved on since this was written. Can someone shed some light, please?
http://www.candland.net/blog/2008/07/09/WhatsNeededForCastleValidationToWork.aspx would appear to contain an answer.