Test for null parameter in .properties file for MessageFormat - java

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?

Related

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.

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
}

Android Json and null values

How can I detect when a json value is null?
for example: [{"username":null},{"username":"null"}]
The first case represents an unexisting username and the second a user named "null". But if you try to retrieve them both values result in the string "null"
JSONObject json = new JSONObject("{\"hello\":null}");
json.put("bye", JSONObject.NULL);
Log.e("LOG", json.toString());
Log.e("LOG", "hello="+json.getString("hello") + " is null? "
+ (json.getString("hello") == null));
Log.e("LOG", "bye="+json.getString("bye") + " is null? "
+ (json.getString("bye") == null));
The log output is
{"hello":"null","bye":null}
hello=null is null? false
bye=null is null? false
Try with json.isNull( "field-name" ).
Reference: http://developer.android.com/reference/org/json/JSONObject.html#isNull%28java.lang.String%29
Because JSONObject#getString returns a value if the given key exists, it is not null by definition. This is the reason JSONObject.NULL exists: to represent a null JSON value.
json.getString("hello").equals(JSONObject.NULL); // should be false
json.getString("bye").equals(JSONObject.NULL); // should be true
For android it will raise an JSONException if no such mapping exists. So you can't call this method directly.
json.getString("bye")
if you data can be empty(may not exist the key), try
json.optString("bye","callback string");
or
json.optString("bye");
instead.
In your demo code, the
JSONObject json = new JSONObject("{\"hello\":null}");
json.getString("hello");
this you get is String "null" not null.
your shoud use
if(json.isNull("hello")) {
helloStr = null;
} else {
helloStr = json.getString("hello");
}
first check with isNull()....if cant work then try belows
and also you have JSONObject.NULL to check null value...
if ((resultObject.has("username")
&& null != resultObject.getString("username")
&& resultObject.getString("username").trim().length() != 0)
{
//not null
}
and in your case also check resultObject.getString("username").trim().eqauls("null")
If you must parse json first and handle object later, let try this
Parser
Object data = json.get("username");
Handler
if (data instanceof Integer || data instanceof Double || data instanceof Long) {
// handle number ;
} else if (data instanceof String) {
// hanle string;
} else if (data == JSONObject.NULL) {
// hanle null;
}
Here's a helper method I use so that I can get JSON strings with only one line of code:
public String getJsonString(JSONObject jso, String field) {
if(jso.isNull(field))
return null;
else
try {
return jso.getString(field);
}
catch(Exception ex) {
LogHelper.e("model", "Error parsing value");
return null;
}
}
and then something like this:
String mFirstName = getJsonString(jsonObject, "first_name");
would give you your string value or safely set your string variable to null. I use Gson whenever I can to avoid pitfalls like these. It handles null values much better in my opinion.

XML parsing with attributes that is empty (Android)

i have an xml file with attributes like this:
<folder name = 'somename' description = ''/>
i want to display the description attribute as 'null' but it force closes and throws a FATAL Exception main in the LogCat.
i have this code below at the startElement() method
if (localName.equalsIgnoreCase("folder")) {
/** Get attribute value */
if(attributes.getValue("description")== "null"){
parseList.setFolderdesc(null);
}else{
String desc = attributes.getValue("description");
parseList.setFolderdesc(desc);
}
i tried this code but no luck...
how will i solve this without changing my xml file?
try with the following code
String desc = null;
try{
desc = attributes.getValue("description");
if((desc == null) || (desc.length()<=0)){
desc = null;
}
}catch(Exception ex){
desc = null;
}
if(parseList != null){
parseList.setFolderdesc(desc);
}
This code doesn't do what you expect:
if (attributes.getValue("description") == "null") {
You are comparing the attribute value with the String "null" not with a java null. (And you are testing strings the unsafe way too! Strings should be tested for equality using String.equals() not the == operator.)
That test should be written as follows:
if (attributes.getValue("description") == null) {
or better still:
if (attributes.getValue("description") == null ||
attributes.getValue("description").isEmpty()) {
(I'm not sure whether this will fix you problem, because I don't understand your problem description.)

Using emf compare from code?

I have two emf models A and B where B only differs from A because it has an extra child node.
Now I would like to use emf compare from code to do:
1) Read model A and B and create model C which is a merged model from A and B. Basically this corresponds to A + the extra nodes from B.
I have looked at:
http://dev.eclipse.org/viewcvs/viewvc.cgi/org.eclipse.emf/org.eclipse.emf.compare/examples/org.eclipse.emf.compare.examples.standalone/src/org/eclipse/emf/compare/examples/standalone/ExampleLauncher.java?view=co&root=Modeling_Project
But I don't see how I can compute the final merged model using the code:
DiffModel diff = CompareUtils.compare(model1, model2, Collections.<String, Object> emptyMap());
CompareUtils.merge(diff);
Any examples that shows how to compute the merged model??
I have now tried:
private void bob() {
ResourceSet resourceSet = new ResourceSetImpl();
Map extensionMap = (Map) resourceSet.getResourceFactoryRegistry()
.getExtensionToFactoryMap().put("xmi", new XMIResourceFactoryImpl());
try {
Region region01 = StatemachineFactoryImpl.eINSTANCE.createRegion();
addResourceToModel(resourceSet, region01, "st1.xmi");
State state01 = StatemachineFactoryImpl.eINSTANCE.createState();
state01.setName("aaaa");
region01.getState().add(state01);
if (state01.eResource() == null) {
System.out.println("state01 NOT contained in resource!");
return;
}
Region region02 = StatemachineFactoryImpl.eINSTANCE.createRegion();
addResourceToModel(resourceSet, region02, "st2.xmi");
State state02 = StatemachineFactoryImpl.eINSTANCE.createState();
state02.setName("bbbb");
region02.getState().add(state02);
if (state02.eResource() == null) {
System.out.println("state02 NOT contained in resource!");
return;
}
final MatchModel match = MatchService.doMatch(region01, region02,
Collections.<String, Object> emptyMap());
final DiffModel diff = DiffService.doDiff(match, false);
final List<DiffElement> differences = new ArrayList<DiffElement>(
diff.getOwnedElements());
MergeService.merge(differences, true);
// Prints the results
addResourceToModel(resourceSet, match, "match.xmi");
addResourceToModel(resourceSet, diff, "diff.xmi");
if (match.eResource() != null)
System.out.println(ModelUtils.serialize(match)); // Throws an
// exception!
if (diff.eResource() != null)
System.out.println(ModelUtils.serialize(diff));
} catch (final InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void addResourceToModel(ResourceSet resourceSet, EObject obj,
String path) {
Resource res = resourceSet.createResource(URI.createURI(path));
res.getContents().add(obj);
}
But the line:
if (match.eResource() != null)
System.out.println(ModelUtils.serialize(match)); // Throws an
// exception!
even though match.eResource() != null
I get this error:
org.eclipse.emf.ecore.resource.Resource$IOWrappedException: The object 'statemachine.impl.StateImpl#11ce012 (name: bbbb)' is not contained in a resource.
at org.eclipse.emf.ecore.xmi.impl.XMLSaveImpl.endSave(XMLSaveImpl.java:306)
at org.eclipse.emf.ecore.xmi.impl.XMLSaveImpl.save(XMLSaveImpl.java:235)
at org.eclipse.emf.ecore.xmi.impl.XMLResourceImpl.doSave(XMLResourceImpl.java:254)
at org.eclipse.emf.ecore.xmi.impl.XMLResourceImpl.save(XMLResourceImpl.java:229)
at org.eclipse.emf.compare.util.ModelUtils.serialize(ModelUtils.java:429)
I have added Region to a resource based on the documentation here:
http://wiki.eclipse.org/index.php/EMF-FAQ#I_get_a_DanglingHREFException:e.g..2C.22org.eclipse.emf.ecore.xmi.DanglingHREFException:_The_object_.27com.example.Foo.402f5dda_.28.29.27_is_not_contained_in_a_resource..22_What_do_I_need_to_do.3F
and the State is contained in the Region so I don't understand why I get the exception...any ideas?
Tul,
The stack trace you get means that one of the 'merged' objects is not contained into a resource : when merging, we copy an object that references a statemachine (which name is 'bbbb'), we then need to reference this state machine from the copied object ... and that statemachine we reference (is it copied or directly referenced from your other model? You should debug to see this) isn't itself contained in any resource.
State state02 = StatemachineFactoryImpl.eINSTANCE.createState();
state02.setName("bbbb");
region02.getState().add(state02);
if (state02.eResource() == null) {
System.out.println("state02 NOT contained in resource!");
return;
}
This should ensures that "bbbb" is indeed contained in a resource.
After this line :
MergeService.merge(differences, true);
Could you try to check once more if "state02.eResource() == null" ? If it is, then that is your issue. Otherwise, you'll have to make sure that this doesn't return :
for (State state : region01.getState()) {
if (state.eResource() == null) {
System.err.println(state.getName() + " is not contained in a resource);
return;
}
}
What about this?
Model1 targetModel = EcoreUtil.copy(model1);
addResourceToModel(targetModel) // assign the copied model to a resource
MatchModel match = MatchService.doMatch(targetModel, model2,
Collections.<String, Object> emptyMap());
DiffModel diff = DiffService.doDiff(match, false);
EList<DiffElement> differences = diff.getDifferences();
for (DiffElement diffElement : differences) {
MergeService.merge(diffElement, true);
}
Your exception:" org.eclipse.emf.ecore.resource.Resource$IOWrappedException: The object 'statemachine.impl.StateImpl#11ce012 (name: bbbb)' is not contained in a resource.". The StateImpl#11ce012 (name: bbbb) is in one resource named st2.xmi,but the match elememt is in another resource named "match.xml". The two resources are different and they do not refer each other. So the match element can NOT refer StateImpl. To solve this problem, all elements(state01, state02, match, diff) must be saved in ONE resource. The code is:
res.getContents().add(stat01);
res.getContents().add(stat02);
res.getContents().add(match);
res.getContents().add(diff);
By the way, the condition "state02.eResource() == null" is not nessary.

Categories

Resources