Rest Search Parameters Validation - java

I have a rest end point that takes the urls with the following 3 parameters as valid:
regno, hostid, location
regno, domid, location
regno, provider
Anything other than these combinations are invalid.
I have a validator method that checks this
if (!StringUtils.isEmpty(criteria.getRegno())) {
if ((!StringUtils.isEmpty(criteria.getHostid()) || !StringUtils.isEmpty(criteria.getDomId())) && !StringUtils.isEmpty(criteria.getLocation())) {
criteria.setSearchType(GET_HOST_SEARCH_TYPE);
} else if (!StringUtils.isEmpty(criteria.getProvider()) && (StringUtils.isEmpty(criteria.getLocation()) && StringUtils.isEmpty(criteria.getHostid) && StringUtils.isEmpty(criteria.getDomId()))) {
criteria.setSearchType(GET_PROVIDER_SEARCH_TYPE);
} else {
throw new BadRequestException("Either Provider, Location, Hostid or domid is missing");
}
} else {
throw new BadRequestException("Regno is missing");
}
I dont like the fact that I am using a lot of if else statements. If there is a better readable way of doing this please feel free to help.

You may try the following approach, it will reduce the need of if else drastically..
public String detectSearchType(String url) throws BadRequestException{
final String condition1 = "(?=.*location)(?=.*(?:hostid|domid))";
final String condition2 = "(?=.*provider)(?!.*hostid)(?!.*domid)(?!.*location)";
if(!url.contains("regno="))
throw new BadRequestException("Regno is missing");
else if(Pattern.compile(condition1).matcher(url).find())
return "GET_HOST_SEARCH_TYPE";
else if(Pattern.compile(condition2).matcher(url).find())
return "GET_PROVIDER_SEARCH_TYPE";
else
throw new BadRequestException("Either Provider, Location, Hostid or domid is missing");
}
You need to pass the url strings to this method. such as the following:
detectSearchType("localhost/search?location=india&regno=12532&hostid=gdy-101");
detectSearchType("localhost/search?location=india&regno=12532&domid=gdy-101");
detectSearchType("localhost/search?regno=12532&provider=mrt");
detectSearchType("localhost/search?regno=12532&provider=mrt&host=abul");
detectSearchType("localhost/abc?regno=1&hostid=2");

Related

Best way to check specific result of 2 methods in Java

I have the following method
public Message JavaMethod(String id1, String id2)
In which I need to call a Dao class's method to verify that an user with the provided Id exist, and if it does not, create a message detailing the Id that couldn't be found on the database with the following method:
createMessage("Message string",Enum.TYPE,IdofMissingUser);
At first I thought of doing it like this:
public Message JavaMethod(String id1, String id2) {
if(Dao.findUser(id1) == null || Dao.findUser(id2) == null){
return createMessage("Error",Enum.Error,id1);
}else{
//do some other stuff
}
}
But obviously this way I won't know which of the ids has not been found.
So I went ahead and created an ugly if else cycle:
public Message JavaMethod(String id1, String id2) {
if (Dao.findUser(id1) == null) {
return createMessage("Error", Enum.Error, id1);
} else if (Dao.findUser(id2) == null) {
return createMessage("Error", Enum.Error, id2);
} else {
// Do stuff after veryfing users exists
return createMessage("All OK", Enum.OK, messageData);
}
}
But I'm not feeling really confident that this is the best solution for this basic issue.
What would you guys recommend in this case?
You could wrap the ids in a list and use a for loop:
public Message someMethod(String id1, String id2) {
for (String id: Arrays.asList(id1, id2)) {
if (Dao.findUser(id) == null) {
return createMessage("Error", Enum.Error, id);
}
}
// Do stuff after verifying users exists
return createMessage("All OK", Enum.OK, messageData);
}
If you're only ever going to have two IDs, you could deal with a shorthand boolean. Question is whether that makes it less readable though. E.g.
public Message JavaMethod(String id1, String id2) {
User user1 = Dao.findUser(id1);
User user2 = Dao.findUser(id2);
if(user1 == null || user2 == null){
return createMessage("Error",Enum.Error,user1 == null ? id1 : id2);
}else{
//do some other stuff
}
}
This also doesn't deal with if both of the IDs were null, for that you could extend it:
public Message JavaMethod(String id1, String id2) {
User user1 = Dao.findUser(id1);
User user2 = Dao.findUser(id2);
if(user1 == null || user2 == null){
return createMessage("Error",Enum.Error,user1 == null && user2 == null? both : user1 == null ? id1 : id2);
}else{
//do some other stuff
}
}
You'd need to define what you would return for the both variable
More details on the shorthand boolean annotation can be found here

sign-up form validations in java

i have a signup page connected to sql database.now i want to have validations in signup page like firstname,lastname,username etc can not be empty using java how can i do that
My code is
String fname=Fname.getText();
String lname=Lname.getText();
String uname=Uname.getText();
String emailid=Emailid.getText();
String contact=Contact.getText();
String pass=String.valueOf(Pass.getPassword());
Connection conn=null;
PreparedStatement pstmt=null;
try
{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/zeeshan","root","sHaNi97426");
pstmt=conn.prepareStatement("Insert into signup1 values(?,?,?,?,?,?)");
pstmt.setString(1,fname);
pstmt.setString(2,lname);
pstmt.setString(3,uname);
pstmt.setString(4,emailid);
pstmt.setString(5,contact);
pstmt.setString(6,pass);
int i=pstmt.executeUpdate();
if(i>0)
{
JOptionPane.showMessageDialog(null,"Successfully Registered");
}
else
{
JOptionPane.showMessageDialog(null,"Error");
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
First your question is not direct. Validation occurs before database query. You should not proceed to database Connetction or making any query.
What should you do:
public static boolean nullOrEmpty(String value) {
return value == null || value.trim().equals("") ? true : false;
}
public void yourMethod(){
try{
//YourCode Here
String fname=Fname.getText();
if(nullOrEmpty(fname)){
new throw ValidationException("First name should not be null.");
}
//YourCode Here
}catch(ValidationException e){
System.err.println("Exception:"+e.getMessage());
}
}
Check for every string to validate.
that should not be hard, you can do it with simple if and else like below
if(fname != null && fname.isEmpty()){
throw new Exception(fname+" cannot be empty");
}else if(lname != null && lname.isEmpty()){
throw new Exception(fname+" cannot be empty");
}
.....
as a recommendation you should abstract validation and database access objects . see example of MVC here
You may do it just by downloading a jar named org.apache.commons.lang
Stringutils Class Reference
Sample Code
StringUtils.isBlank(null) = true
StringUtils.isBlank("") = true
StringUtils.isBlank(" ") = true
StringUtils.isBlank("bob") = false
StringUtils.isBlank(" bob ") = false
or
StringUtils.isEmpty(obj_String); // Another method to check either null or "";
To check if a String is empty you can use the method .isEmpty(). You'll probably want to use .trim() first, as this removes all the whitespaces at the beginning and ending of the String. For more options check out the full documentation here.

null string test is always true

I already saw a lot of similar posts, but none seems to be the same as this. I am testing if a string is null in my Java Android (2.2) app and whatever the string is, it is always true. Here is the code :
public static String getLocalBluetoothName(){
String name;
if(mBluetoothAdapter == null){
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}
try{
name = mBluetoothAdapter.getName();
if(name == null){
System.out.println("Name is null!");
name = mBluetoothAdapter.getAddress();
}
return name;
}
catch (Exception e){
return "";
}
}
The if(name == null) is always true even if my string has a value. By the way, I also tried mBluetoothAdapter.getName() == null and it is always true too. I saw somewhere that you can do something like that:
if(name.equals("null")){
}
But if the string is null, wouldn't that create an exception because I should not be able to use a method if the object is null? Also, testing "null" is somewhat strange to me...
Try this simplified version :
public static String getLocalBluetoothName(){
String name = null;
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
if (adapter == null) {
//System.out.println("Can't get adapter");
Log.d(TAG, "Can't get adapter");
return name;
}
if ((name = adapter.getName()) == null) {
//System.out.println("Name is null!");
Log.d(TAG, "Name is null!");
name = adapter.getAddress();
}
return name;
}
and don't forget to include android.permission.BLUETOOTH permission in your app's manifest.
Also, note that sometimes your debugger may trick you by showing executing specific branches that are not in fact run (happened to me debugging in Eclipse before). So, make sure that you ACTUALLY have Name is null output in logcat, otherwise your name may be not null.
name = mBluetoothAdapter.getName();
Since name is null, your Bluetooth adapter probably doesn't have a name.
According to me, mBluetoothAdapter.getName() is always returning null, that is why the if condition is always returning true. Your method of comparing if(name == null) is absolutely correct, no doubt in this.

How to test if a JSONObject is null or doesn't exist

I have a set of JSONObject values which i receive from a server and operate on. Most times I get a JSONObject with a value (let's say statistics) and sometimes, it returns an Error object with a code and a description of the error.
How do I structure my code so that it doesn't break if it returns the error. I thought I could do this, but doesn't work.
public void processResult(JSONObject result) {
try {
if(result.getJSONObject(ERROR) != null ){
JSONObject error = result.getJSONObject(ERROR);
String error_detail = error.getString(DESCRIPTION);
if(!error_detail.equals(null)) {
//show error login here
}
finish();
}
else {
JSONObject info = result.getJSONObject(STATISTICS);
String stats = info.getString("production Stats"));
}
}
}
Use .has(String) and .isNull(String)
A conservative usage could be;
if (record.has("my_object_name") && !record.isNull("my_object_name")) {
// Do something with object.
}
It might be little late(it is for sure) but posting it for future readers
You can use JSONObject optJSONObject (String name) which will not throw any exception and
Returns the value mapped by name if it exists and is a JSONObject, or null otherwise.
so you can do
JSONObject obj = null;
if( (obj = result.optJSONObject("ERROR"))!=null ){
// it's an error , now you can fetch the error object values from obj
}
or if you just want to test nullity without fetching the value then
if( result.optJSONObject("ERROR")!=null ){
// error object found
}
There is whole family of opt functions which either return null or you can also use the overloaded version to make them return any pre-defined values.
e.g
String optString (String name, String fallback)
Returns the value mapped by name if it exists, coercing it if
necessary, or fallback if no such mapping exists.
where coercing mean, it will try to convert the value into String type
A modified version of the #TheMonkeyMan answer to eliminate redundant look-ups
public void processResult(JSONObject result) {
JSONObject obj = null;
if( (obj = result.optJSONObject("ERROR"))!=null ){
//^^^^ either assign null or jsonobject to obj
// if not null then found error object , execute if body
String error_detail = obj.optString("DESCRIPTION","Something went wrong");
//either show error message from server or default string as "Something went wrong"
finish(); // kill the current activity
}
else if( (obj = result.optJSONObject("STATISTICS"))!=null ){
String stats = obj.optString("Production Stats");
//Do something
}
else
{
throw new Exception("Could not parse JSON Object!");
}
}
In JSONObject there is a 'Has' method that you can do to Determaine the key.
I have no idea if this will work but it looks Credible.
public void processResult(JSONObject result) {
if(result.has("ERROR"))
{
JSONObject error = result.getJSONObject("ERROR")
String error_detail = error.getString("DESCRIPTION");
if(error_detail != null)
{
//Show Error Login
finish();
}
}
else if(result.has("STATISTICS"))
{
JSONObject info = result.getJSONObject("STATISTICS");
String stats = info.getString("Production Stats");
//Do something
}
else
{
throw new Exception("Could not parse JSON Object!");
}
}
It is sometimes more convenient and less ambiguous to have a NULL object than to use Java's null value.
JSONObject.NULL.equals(null) returns true.
JSONObject.NULL.toString()returns "null".
Example:
System.out.println(test.get("address").equals(null)); // Preferred way
System.out.println(test.getString("address").equals("null"));
source -- JSONObject oracle docs
Just a note:
With EE8 json specs, I can do an exception-safe get:
result.asJsonObject().getString("ERROR", null);
if, however, I want to do a check I can do it with:
result.asJsonObject().get("ERROR").equals(JsonValue.NULL)
If at any point in your code, org.json.JSONObject json_object becomes null and you wish to avoid NullPointerException (java.lang.NullPointerException), then do check it as below:
if(json_object == null) {
System.out.println("json_object is found as null");
}
else {
System.out.println("json_object is found as not null");
}
If in any case, your jsonobject is null.
Then use this statement for checking jsonobject is null or not.
if (!obj.get("data").isJsonNull()){
//Not Null
}else{
//Null
}
And for checking jsonobject is exist or not, use .has:
if (!obj.has("data")){
//Not Exist
}else{
//Exist
}

Test for null parameter in .properties file for MessageFormat

Is it possible, with resource bundles and MessageFormat to have the following result?
when I call getBundle("message.07", "test") to get "Group test"
when I call getBundle("message.07", null) to get "No group selected"
Every example I found on the Internet is with planets, with files on the disk and so on.
I only need to check if one parameter is null (or doesn't exist) in the resource bundle's properties file. I hope to find a special format for the null parameter something like {0,choice,null#No group selected|notnull#Group {0}}.
The method I use to get the bundles is:
public String getBundle(String key, Object... params) {
try {
String message = resourceBundle.getString(key);
if (params.length == 0) {
return message;
} else {
return MessageFormat.format(message, params);
}
} catch (Exception e) {
return "???";
}
}
I also call this method for other bundles, like
getBundle("message.08", 1, 2) => "Page 1 of 2" (always parameters, no need to check for null)
getBundle("message.09") => "Open file" (no parameters, no need to check for null)
What should I write in my .properties file for message.07 to have the result described?
What I have now is:
message.07=Group {0}
message.08=Page {0} of {1} # message with parameters where I always send them
message.09=Open file # message without parameters
I'll recommend not trying to change the bundle functionality (even if you have a getBundle method encapsulating it).
Simply do in your code:
getBundle(param == null? "message.07.null": "message.07", param)
Or make another method:
getBundleOrNull("message.07", param, "message.07.null")
that does
public String getBundleOrNull(String key, value, nullKey) {
return getBundle(value == null? nullKey: key: value);
}
Your .properties file,
message.07=Group {0}
message.08=Page {0} of {1}
message.09=Open file
message.null = No group selected
And then you need to change your code to put an explicit check params for null. And if null then you can do something like resourceBundle.getString(NULL_MSG). Where NULL_MSG will be this,
private static final String NULL_MSG = "message.null";
So, now your original method would become something like this.
public String getBundle(String key, Object... params) {
String message = null;
try {
if (params == null) {
message = resourceBundle.getString(NULL_MSG);
} else {
message = MessageFormat.format(resourceBundle.getString(key), params);
}
} catch (Exception e) {
e.printStackTrace();
}
return message;
}
Calling my method like below,
getBundle("message.07", "test") // returning 'Group test'
getBundle("message.07", null) // returning 'No group selected'
getBundle("message.08", 1, 2) // returning 'Page 1 of 2'
getBundle("message.08", null) // returning 'No group selected'
getBundle("message.09", new Object[0]) // returning 'Open file'
getBundle("message.09", null) // returning 'No group selected'
Now tell me where is the problem?

Categories

Resources