JavaNullPointerException on calling function - java

I get an error when I call a function in java.
The return type is void, and I just call it and display a string inside.
Here is the call of the bugging function :
#RequestMapping(method = RequestMethod.POST)
public String findDevicesByCriteria(#Valid #ModelAttribute Device device, BindingResult bindingResult, Model uiModel) {
if (isCriteriaEmpty(device)) {
uiModel.addAttribute("criteriaEmptyWarning", "error_search_criteria_empty");
return ViewConstants.DEVICE_SEARCH_VIEW;
}
identityService.searchDevices(device.getSerialNumber(), device.getOwner().getSiteName(), device.getIpAdress(), device.getInstallDate(), device.getEndDate()); // the error come from here
return ViewConstants.DEVICE_SEARCH_VIEW;
}
The prototype in the interface of the bugging function :
/**
* Search devices.
*
* #param sn the serial number of the device
* #param site the site of it
* #param ipAdress the ip adress of it
* #param installDt the install date of it
* #param endDt the end date of it
* #return the list of device
*/
void searchDevices(String sn, String site, String ipAdress, Date installDt, Date EndDt);
And finally the function that cause problem :
public void searchDevices(String sn, String site, String ipAdress, Date installDt, Date EndDt) {
System.out.println("toto");
}
Please advice
Regards

Check that none of the following objects is null.
identityService
device
device.getOwner()

Check whether the device is null or not before accessing the values
if(device != null)
{
identityService.searchDevices(device.getSerialNumber(), device.getOwner().getSiteName(), device.getIpAdress(), device.getInstallDate(), device.getEndDate());
}

Either of identityService or service has not been initialized and therefore is null. Then you get a NullPointerException when you try to use it.

1.Plz. Confirm whether you have declared and defined the bean for identity service. (Most probably it would be #Autowired in your controller and defined as bean in your SpringBean context file) and correct the discrepancies found if any.
Whether Object device is null or not. If it is, then check your request headers and body (which leads to creation of Device object referenced by you).
It would be far more easy to pin point the issue if you could share whole your controller file(from where the function is called and debug point on line from where null pointer is thrown).

Related

User creating multiple objects from one class during runtime -Java

So I have been looking around and reading up a lot of forums and the java documentation but I can't seem to get a solid solution for what I am trying to do.
Essentially I have a Module class as shown below:
/**
* MODULE CLASS
* This class will be the base for every Module inputed into the system
* #author George
*/
public class Module {
// -=VARIABLE DECLARATIONS=-
private String moduleName; /* String variable to store the name of the module */
private String moduleLeader; /* String variable to store the name of the module leader */
// -=GETTERS=-
public String getModuleName() {return this.moduleName;} /* Will return the name of the module */
public String getModuleLeader() {return this.moduleLeader;} /* Will return the name of the module leader */
// -=SETTERS=-
public void setModuleLeader(String l) {this.moduleLeader = l;} /* Sets the name of the module leader to the inputed name */
public void setModuleName(String n) {this.moduleName = n;} //THIS NEEDS TO BE ADDED TO DESIGN DIAGRAMS
// -=CONSTRUCTOR=-
/**
* Constructor to make a new object for the module
* #param n (NAME) - String input to set the name of the module
* #param l (LEADER) - String input to set the name of the module leader
*/
public Module(String n, String l) {
this.moduleName = n;
this.moduleLeader = l;
}
}
On my GUI, each module is represented as its own button which upon clicking will take you to the module's page using CardLayout. I also have a button where the user can add a module, this is where my issue comes into place. Obviously a Module object would be defined as:
Module newModule = new Module("name", "leader");
But how would this allow more than one object to be created. The name of the module would come from user input so there is no way I can put the name of the object in the source code and from what I have read you cannot set the object name using a variable.
Lets say for example, during runtime, the user would want to create two modules. One with the name of "Java" and one with the name of "Python". How would I go about doing this? Obviously the first object would be created just fine using the initialization above, but the name of the object would be stuck as newModule. But then it would not be able to create the second object as it cannot have two objects with the same name. I have spent some time trying to understand HashMaps to see if that could be of any use to me but quite frankly I find it quite confusing and again, I can't tell if that is the correct solution.
I hope I have worded this correctly and you can understand my problem. Any help with this would be greatly appreciated.
Thanks in advance.

Angular HTTP POST request to spring boot resulting in null value

I was having some problem when trying to execute POST request with multiple parameters. Here is my service.ts class written in typescript:
retrieve(packageId: any[], date: any) {
console.log(packageId);
console.log(date);
let packgeIdStr: string = JSON.stringify(packageId);
const data = { stringArrDo: packgeIdStr, date: date };
const url = this.serviceAPI + '/...../retrieve';
return this.http.post<SRFDO[]>(
url,
{ params: data }
);
}
When I print out in my console, I managed to get the data here.
However, when I pass the data to my controller written in Java, the parameters became null:
#PostMapping("/retrieve")
public DO[] retrieve(#RequestBody String stringArrDo, java.sql.Date date)
throws RemoteException, JaMClientRemoteException, JaMException {
System.out.println(stringArrDo);
System.out.println("date :"+ date);
// removed code
}
I not sure why the data is printed out at service.ts but when passing it to the controller then became null. Any ideas?
Thanks!
You can open up your Chrome dev tools, go to the Network tab, and inspect your POST to see if angular is actually passing the right stuff to the right endpoint. That will tell you if your problem is client-side vs server-side.
Edit:
It looks like your server may be expecting an array of strings, but you're sending an object. In javascript, when you do {var1, var2}, that's just shorthand for {var1: var1Value, var2: var2Value}
Edit 2: I looked up spring, and it looks like you're using #RequestBody incorrectly. It looks like you're supposed to pass it a class that it can deserialize the JSON into, like
public class RequestData {
private String[] packageIds;
private Date date;
// ...
}
You've also put your data under the top-level variable params, so you'd want to remove that and put all your stuff at the top level of your object.
Try reading through this tutorial for more info: https://www.baeldung.com/spring-request-response-body
The attributes name on two classes may be different.
class A{
// class in springboot
private String name;
}
class A {
//class in angular
data: String;
}
In this case, attribute name is main cause for null pointer exception in server side.

JAutodoc: getter comment template is merged with default comment behavior

I am trying to configure JAutodoc such that getter comments are generated containing only the #returns tag, like so:
/**
* #returns The non-null {#linkplain Foo foo} of this {#link IBar}.
*/
public Foo getFoo();
I have configured my getter template to produce this:
However, something must be wrong with my general JAutodoc settings, because what I get instead is a hybrid of my template and a comment parsed from the method name:
/**
* Get foo.
* #returns The non-null {#linkplain Foo foo} of this {#link IBar}.
*/
public Foo getFoo();
These are my settings:
I have removed the 'get' replacement from the replacements list, as well as unchecked the 'etter from field comment' setting as advised in this discussion, but it has not made a noticeable difference. I have also attempted to uncheck the 'Create comment from element name' setting, despite my example getter being part of an interface (in which case there is no element to get the comment from), but JAutodoc doesn't seem to care about that.
I have also tried restarting Eclipse after making each of these changes, in case that mattered. So far, nothing is working. It almost appears as if the comment behavior of getters is hard-coded. Can someone please shed some light on this?
TL;DR
JAutodoc, in its current form, can not do what you want it to do. This is because you are asking for incomplete Javadocs.
Details
(This was fun, and I hope you appreciate the effort :-)
This is a case where you are asking JAutodoc to create incomplete Javadocs. i.e. you are asking for no documentation in the Javadoc. (I personally find the repetitiveness on simple getter annoying too BTW).
The steps that JAutodoc are going through internally is:
Applying your template, so the comment looks exactly as you want - for a moment in time.
This is the bit of code that applies the template. Using your example, the member parameter below is your getFoo method and, as there is no existing comment in your code when you first apply the auto-comment, so the jdi parameter is empty (jdi.isEmpty() == true).
When the template is applied, text looks exactly as you want it too. text gets parsed just as any Javadoc comment would and returned.
From net.sf.jautodoc.source.JavadocCreator:
public JavadocInfo applyTemplate(final IMember member, final JavadocInfo jdi) throws Exception {
final JavadocInfo templateJdi = new JavadocInfo();
final String text = JAutodocPlugin.getContext().getTemplateManager().applyTemplate(member,
config.getProperties());
if (text != null && text.length() > 0) {
templateJdi.parseJavadoc(text);
}
return jdi.isEmpty() ? templateJdi : jdi.merge(templateJdi);
}
Now the JavadocInfo that was returned from applyTemplate is passed to createJavadoc. In createJavadoc the code checks if there is a comment (excluding the #params, #return, etc). As there is not any, it tries to insert some automatically from the information available. Simplistically, it just un-camel-cases the name of the method and makes that the comment.
From net.sf.jautodoc.source.JavadocCreator
public String createJavadoc(final IMethod method, final String indent, final String lineSeparator,
final JavadocInfo jdi) throws JavaModelException {
final List<String> text = jdi.getComment();
if (text.isEmpty()) {
if (config.isCreateDummyComment()) {
if (method.isConstructor()) {
text.add(Constants.JDOC_CONSTRUCTOR);
}
else if (method.isMainMethod()) {
text.add(Constants.JDOC_MAIN);
}
else {
String comment = CommentManager.createComment(config, method.getElementName(),
CommentManager.METHOD, true, true, CommentManager.FIRST_TO_UPPER);
text.add(comment + Constants.DOT);
}
}
else {
text.add("");
}
}
else {
checkForDot(text);
}
Now the code that calls the above two methods is this:
From net.sf.jautodoc.source.SourceManipulator.addJavadoc(IMember):
if (config.isCreateDummyComment()) {
jdi = javadocCreator.applyTemplate(member, jdi);
}
newJavadoc = javadocCreator.createJavadoc((IMethod) member, indent, lineDelimiter, jdi);
As you can see from these code snippets, both applying your template and creating the comment part (that you don't want!) is controlled by the same if statement config.isCreateDummyComment(). That if statement connects to the Create comment from element name option.
Examples
This issue is not happening because the method is a getter, but applies everywhere. Assume you have this bit of code:
/**
* #param myFirstParam this is important and I documented it
*/
public int doThisAndThat(int myFirstParam, int anotherParamHere) {
return 0;
}
And you apply JAutodoc to it (with Complete existing Javadoc) then you get:
With Create comment from element name unset:
/**
*
*
* #param myFirstParam this is important and I documented it
* #param anotherParamHere
* #return
*/
public int doThisAndThat(int myFirstParam, int anotherParamHere) {
return 0;
}
With Create comment from element name set:
/**
* Do this and that.
*
* #param myFirstParam this is important and I documented it
* #param anotherParamHere the another param here
* #return the int
*/
public int doThisAndThat(int myFirstParam, int anotherParamHere) {
return 0;
}
Getting the source
I couldn't find the source on any of the usual suspects (github, etc), but it is available for download here: http://sourceforge.net/projects/jautodoc/files/jautodoc/1.13.0/
So you could, if you desired, edit the source and rebuild your plug-ins. Or file a feature request with the dev.
In Conclusion
JAutodoc, in its current form, can not do what you ask it to do. However, this is essentially by design, because if you say you want to Create comment from element name automatically (internally called Create Dummy Comment) then you want fully complete Javadoc to be created for you.
Finally, keep in mind if there is no comment, then nothing appears in the method summary table and your generated Javadocs simply look incomplete.

Play framework merge POST with model

I am trying to learn the Play framework however i hit a roadblock and the documentation did not cover my issue (google resulted in nothing). What i am trying to do is making a multi page form that updates every time to the database.
Lets say the form is made in 5 steps and they cant be on the same page. What i've got working is that the first page works like intended (this also has the required data, the rest is optional)
ERROR executing DML bindLog[] error[Invalid value "null" for parameter "SQL"
After some searching i found that this had to do with the fact that the second page does not have the required data and thus sets those values to null. Meaning when i want to save the object it cant because all the other values are null.
Now my current saving code is pretty straightforward:
User userUpdate = Form.form(User.class).bindFromRequest().get();
userUpdate.update(id);
(the id value is from the action)
i've also tried the following:
User userUpdate = Form.form(User.class).fill(User.find.byId(id)).bindFromRequest().get();
userUpdate.update(id);
And in both cases my program crashes because of the null values.
So what i need is a push in the right direction to merge the current model with the form data so that i can save it. If someone has an good example on how to do it that would be really helpful!
P.s. this is my current model:
#Entity
public class User extends Model{
#Id
public Long id;
public String username;
public String firstname;
public String lastname;
public static Finder<Long,User> find = new Finder<Long,User>(Long.class, User.class);
public Form getUserFormByID(Long id){
Form<User> userForm = Form.form(User.class);
if(id > 0){
userForm = userForm.fill(
this.find.byId(id)
);
}
return userForm;
}
}

Convert empty string to null using javax.validation annotations

I have the following variable annotated for data validation:
#Size(min=8, max=16, message="the size of the parameter must be between 8 and 16")
private String param;
However, the param can be null. It is required that it be 8-16 chars long only if it is not null. The problem I face is if the client app (JSON API) supplies an empty string, I want to treat it as though it were not supplied at all, i.e. is null. I was wondering if there is an elegant way to do this using the javax.validation annotations, i.e. convert an empty string to null, as opposed to the plain Java way the way I'm doing it right now:
public void setParameter(String _param) {
if(_param != null && !_param.trim().isEmpty()){
this.param = _param;
} else {
this.param = null;
}
}
I would like to have a very simple setter:
public void setParameter(String _param) {
this.param = _param;
}
and have the is-empty-string boilerplate done by an annotation. Is there a way to do it?
You could can implement your own custom constraint validator.
see here. I've used this many times and works like a charm.
https://docs.jboss.org/hibernate/validator/5.0/reference/en-US/html/validator-customconstraints.html
You would just need to set this condition (if null return "" or vice-versa) in the isValid method.

Categories

Resources