I have written this method
private string FindInnerExceptionMessage(Exception ex)
{
string exceptionMsg = string.Empty;
if (ex.InnerException == null)
{
exceptionMsg = ex.Message;
}
else
{
ex = ex.InnerException;
FindInnerExceptionMessage(ex);
}
return exceptionMsg;
}
However, after that FindInnerExceptionMessage it is stepping to return exceptionMsg and not logging the exact exception message
You don't actually assign the return value of your recursive call to anything. As a result, your first call will return String.Empty because the value of FindInnerExceptionMessage(ex.InnerException) is never assigned as the return value (unless the exception passed to the first call has no inner exception, in which case it will work). Try something like this:
private string FindInnerExceptionMessage(Exception ex)
{
string exceptionMsg = string.Empty;
if (ex.InnerException == null)
{
exceptionMsg = ex.Message;
}
else
{
exceptionMsg = FindInnerExceptionMessage(ex.InnerException);
}
return exceptionMsg;
}
Related
From time to time I'm in a situation where I need to convert String values to objects. And often I end up with a custom method.
Here's an example:
#Nullable
public static Object valueOf(Class pParamType, String pValue)
{
if (pValue == null) return null;
if ("null".equals(pValue)) return null;
if (String.class.equals(pParamType)) return pValue;
if (Number.class.equals(pParamType)) return Double.valueOf(pValue);
if (Long.class.equals(pParamType) || Long.TYPE.equals(pParamType)) return Long.valueOf(pValue);
if (Double.class.equals(pParamType) || Double.TYPE.equals(pParamType)) return Double.valueOf(pValue);
if (Integer.class.equals(pParamType) || Integer.TYPE.equals(pParamType)) return Integer.valueOf(pValue);
if (Byte.class.equals(pParamType) || Byte.TYPE.equals(pParamType)) return Byte.valueOf(pValue);
if (Short.class.equals(pParamType) || Short.TYPE.equals(pParamType)) return Short.valueOf(pValue);
if (Float.class.equals(pParamType) || Float.TYPE.equals(pParamType)) return Float.valueOf(pValue);
if (Date.class.equals(pParamType))
{
try
{
return Formatter.parse(pValue, DATE_PATTERN);
}
catch (Exception e)
{
throw new IllegalArgumentException("Illegal date format");
}
}
if (Boolean.class.equals(pParamType) || Boolean.TYPE.equals(pParamType))
{
return Boolean.valueOf(pValue);
}
throw new IllegalArgumentException("Parameters of type [" + pParamType.getName() + "] are not supported");
}
I do realize that it's impossible to convert to just any object. But most java.lang classes do have a valueOf method in place
But I hate to repeat myself, and I have the feeling that there should be something out there that does the same thing already, and probably even covers more.
My question is:
Does the jdk offer a similar utility class or method in the java framework ?
Alternatively what do other frameworks offer ? (e.g. apache commons, spring, guava, ...)
Using reflection you can try to find a constructor with String argument and invoke the constructor
public static void main(String[] args) throws Exception{
System.out.println(valueOf(String.class, ""));
System.out.println(valueOf(Long.class, "1"));
System.out.println(valueOf(Integer.class, "1"));
System.out.println(valueOf(Byte.class, "1"));
System.out.println(valueOf(Short.class, "1"));
System.out.println(valueOf(Double.class, "1.1"));
System.out.println(valueOf(Float.class, "1.1"));
System.out.println(valueOf(Boolean.class, "true"));
}
public static Object valueOf(Class pParamType, String pValue) throws Exception
{
if (pValue == null) return null;
if ("null".equals(pValue)) return null;
Constructor constructor = pParamType.getConstructor(String.class);
if (constructor!=null) {
return constructor.newInstance(pValue);
}
//... keep the logic for Date
throw new IllegalArgumentException("Parameters of type [" + pParamType.getName() + "] are not supported");
}
I have a method to unit test called addSong(song,userId) in service class. I am calling three methods inside it from Dao class. I am using Easy mock to mock dao class. In the setup I first mock all the methods I am calling in addSong(song,userId), and then calling the service.addsong(song,userId) method fot test.
But I am getting the following error:
Java.lang.IllegalStateException: missing behavior definition for the preceding method call:
MusicPlayerDao.addSong(song)
Usage is: expect(a.foo()).andXXX()
at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:42)
at org.easymock.internal.ObjectMethodsFilter.invoke(ObjectMethodsFilter.java:94)
at org.easymock.internal.ClassProxyFactory$MockMethodInterceptor.intercept(ClassProxyFactory.java:97)
at service.MusicPlayerDao$$EnhancerByCGLIB$$45bc3ca1.addSong(<generated>)
at service.MusicPlayerServiceImpl.addSong(MusicPlayerServiceImpl.java:43)
at AddSongTest.addSongs(AddSongTest.java:90)
Here is my code:
private void addSongSetup() throws SQLException{
this.album = new Album();
album.setAlbumName("album");
this.genre = new Genre();
genre.setGenreName("genre");
this.song = new Song("song",this.album,3,"artist","composer",this.genre);
EasyMock.expect(this.dao.addSong(song)).andReturn(1).anyTimes();
EasyMock.expect(this.dao.addGenre(genre, 1)).andReturn(1).anyTimes();
EasyMock.expect(this.dao.addAlbum(album, 1)).andReturn(1).anyTimes();
EasyMock.expect(this.dao.userIdSongsMapping(1,1)).andReturn(1).anyTimes();
}
#Test
public void addSongs(){
this.album = new Album();
album.setAlbumName("album");
this.genre = new Genre();
genre.setGenreName("genre");
this.song = new Song("song",this.album,3,"artist","composer",this.genre);
try {
System.out.println(this.dao.addSong(song));
boolean status = this.service.addSong(song, 1);
assertEquals(true,status);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
My addSong method in service class:
public boolean addSong(Song song, int userId) throws Exception {
MusicPlayerDaoInterface musicPlayerDao = MusicPlayerDao.getInstance();
boolean status = false;
int songId = 0;
TransactionManager transactionManager = TransactionManagerImpl
.getInstance();
try {
if (song != null) {
if (song.getTitle() != null) {
transactionManager.begin();
songId = musicPlayerDao.addSong(song);
song.setSongId(songId);
if (song.getGenre() != null
&& song.getGenre().getGenreName() != null) {
musicPlayerDao.addGenre(song.getGenre(),
song.getSongId());
}
if (song.getAlbum() != null
&& song.getAlbum().getAlbumName() != null) {
musicPlayerDao.addAlbum(song.getAlbum(),
song.getSongId());
}
if (userId != 0 && songId != 0) {
musicPlayerDao.userIdSongsMapping(userId,
song.getSongId());
}
transactionManager.commit();
status = true;
}
}
} catch (SQLException | RollbackException | HeuristicMixedException
| HeuristicRollbackException e) {
transactionManager.rollback();
status = false;
throw e;
}
return status;
}
I don't know were I am going wrong. Please help.
I think you are missing a EasyMock.replay statement after you record the expected behaviour. Something like
EasyMock.replay(this.dao);
From the EasyMock guide:
To get a Mock Object, we need to
create a Mock Object for the interface we would like to simulate
record the expected behavior
switch the Mock Object to replay state
try removing the following lines from the addSongs test case:
this.album = new Album();
album.setAlbumName("album");
this.genre = new Genre();
genre.setGenreName("genre");
this.song = new Song("song",this.album,3,"artist","composer",this.genre);
I assume that addSongSetup is invoked before addSongs (e.g.; #Before). You are reassigning values to your variables album, genre and song in addSong, which, I suppose, EasyMock cannot match to your mock setup in addSongSetup as (depending on how EasyMock implemented this)
you forgot to implement hashcode or equals in Song, Album, Genre or,
EasyMock uses Object identity (i.e., reference comparison)
I guess it's 1.
I'm developing an Android App which uses JSON for the server communication and I've got a weird problem when I'm trying to parse my json file.
This is my json from the server
{
"street2": null,
"province": null,
"street1": null,
"postalCode": null,
"country": null,
"city": null
}
I'm getting the value for City by calling String city = address.optString("city", "") on my address Json-object. For this situation I'm expecting cityto be empty (that's what optString is here for isn't it?) but in fact it contains the String "null". So further null- or isEmpty-checks will return false as the String contains text. If I call address.isNull("city") it returns true which is correct. Only optString fails.
I couldn't find anything on Google or Stackoverflow for this problem. I don't really understand how it can happen as I thought optString would do exactly what I expected. Anybody knows what's going wrong here?
You're not alone in running into this problem and scratching your head, thinking "Could they really have meant this?" According to an AOSP issue, the Google engineers did consider this a bug, but they had to be compatible with the org.json implementation, even bug-compatible.
If you think about it, it makes sense, because if the same code which uses the same libraries run in other Java environments behaves differently in Android, there would be major compatibility problems when using 3rd party libraries. Even if the intentions were good and it truly fixed bugs, it would open up a whole new can of worms.
According to the AOSP issue:
The behavior is intentional; we went out of our way to be bug-compatible with org.json. Now that that's fixed, it's unclear whether we should fix our code as well. Applications may have come to rely on this buggy behavior.
If this is causing you grief, I recommend you workaround by using a different mechanism to test for null, such as json.isNull().
Here's a simple method to help you out:
/** Return the value mapped by the given key, or {#code null} if not present or null. */
public static String optString(JSONObject json, String key)
{
// http://code.google.com/p/android/issues/detail?id=13830
if (json.isNull(key))
return null;
else
return json.optString(key, null);
}
You basically have 2 choices:
1) Send a JSON payload with null values
{
"street2": "s2",
"province": "p1",
"street1": null,
"postalCode": null,
"country": null,
"city": null
}
You will have to check for null values and parse them accordingly:
private String optString_1(final JSONObject json, final String key) {
return json.isNull(key) ? null : json.optString(key);
}
2) Do not send the keys with null values and use optString(key, null) directly (should save you bandwidth).
{
"street2": "s2",
"province": "p1"
}
Got rid off this situation by simply replacing "null" with "".
String city = address.optString("city").replace("null", "");
Using Matt Quigley's answer as a basis, here is the code if you desire to mimic the full functionality of optString, including the fallback portion, written in Kotlin and Java.
Kotlin:
fun optString(json: JSONObject, key: String, fallback: String?): String? {
var stringToReturn = fallback
if (!json.isNull(key)) {
stringToReturn = json.optString(key, null)
}
return stringToReturn
}
Java:
public static String optString(JSONObject json, String key, String fallback) {
String stringToReturn = fallback;
if (!json.isNull(key)) {
stringToReturn = json.optString(key, null);
}
return stringToReturn;
}
Simply pass in null for the fallback parameter if you don't need the fallback.
I ended up creating a utility class for this purpose:
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.json.JSONException;
import org.json.JSONObject;
final public class JsonUtil {
#Nullable
public static String optString(
#NonNull JSONObject object,
#NonNull String key
) throws JSONException {
if (object.has(key) && !object.isNull(key)) {
return object.getString(key);
}
return null;
}
}
I do like this...
String value;
if(jsonObject.get("name").toString().equals("null")) {
value = "";
}else {
value = jsonObject.getString("name");
}
if (json != null && json.getString(KEY_SUCCESS) != null){
// PARSE RESULT
}else{
// SHOW NOTIFICIATION: URL/SERVER NOT REACHABLE
}
that is for checking json null with there key word.
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;
}
My Josn parser was long and had to create a new class to fix that,
then just had to add 1 extra line in each method and rename current JSONObject property name, so all other calls were referencing to my new class instead to JSONObject.
public static ArrayList<PieceOfNews> readNews(String json) {
if (json != null) {
ArrayList<PieceOfNews> res = new ArrayList<>();
try {
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
//before JSONObject jo = jsonArray.getJSONObject(i);
JSONObject joClassic = jsonArray.getJSONObject(i);
//facade
FixJsonObject jo = new FixJsonObject(joClassic);
PieceOfNews pn = new PieceOfNews();
pn.setId(jo.getInt("id"));
pn.setImageUrl(jo.getString("imageURL"));
pn.setText(jo.getString("text"));
pn.setTitle(jo.getString("title"));
pn.setDate(jo.getLong("mills"));
res.add(pn);
}
return res;
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
Here is my class with the methods I needed, you can add more
public class FixJsonObject {
private JSONObject jsonObject;
public FixJsonObject(JSONObject jsonObject) {
this.jsonObject = jsonObject;
}
public String optString(String key, String defaultValue) {
if (jsonObject.isNull(key)) {
return null;
} else {
return jsonObject.optString(key, defaultValue);
}
}
public String optString(String key) {
return optString(key, null);
}
public int optInt(String key) {
if (jsonObject.isNull(key)) {
return 0;
} else {
return jsonObject.optInt(key, 0);
}
}
public double optDouble(String key) {
return optDouble(key, 0);
}
public double optDouble(String key, double defaultValue) {
if (jsonObject.isNull(key)) {
return 0;
} else {
return jsonObject.optDouble(key, defaultValue);
}
}
public boolean optBoolean(String key, boolean defaultValue) {
if (jsonObject.isNull(key)) {
return false;
} else {
return jsonObject.optBoolean(key, defaultValue);
}
}
public long optLong(String key) {
if (jsonObject.isNull(key)) {
return 0;
} else {
return jsonObject.optLong(key, 0);
}
}
public long getLong(String key) {
return optLong(key);
}
public String getString(String key) {
return optString(key);
}
public int getInt(String key) {
return optInt(key);
}
public double getDouble(String key) {
return optDouble(key);
}
public JSONArray getJSONArray(String key) {
if (jsonObject.isNull(key)) {
return null;
} else {
return jsonObject.optJSONArray(key);
}
}
}
If values for key is null like below
{
"status": 200,
"message": "",
"data": {
"totalFare": null,
},
}
check with "isNull" , for Eg:
String strTotalFare;
if (objResponse.isNull("totalFare"))
{
strTotalFare = "0";
} else {
strTotalFare = objResponse.getString("totalFare");
}
if value is "null" for key "totalFare", above function will enter in if and assign value zero else it will get actual value from key.
private Object artikanID(String string) {
try {
DAOTerjemah dao = new DAOTerjemah(ConnectionDB.getConnection()) {};
List<Kata> terjemahan1 = new ArrayList<Kata>();
List<Kata> terjemahan2 = new ArrayList<Kata>();
List<Kata> terjemahan3 = new ArrayList<Kata>();
terjemahan1 = dao.getByIndo(string);
terjemahan2 = dao.getByIndo(string.substring(0,string.length()-1));
terjemahan3 = dao.getByIndo(string.substring(0,string.length()-2));
if (terjemahan1 == null) {
return terjemahan1.get(0).getDayak();
}
else {
return terjemahan2.get(0).getDayak();
}
}catch(Exception e){
return string ;
}
}
there are 3 conditions(terjemahan1,terjemahan2 & terjemahan 3),
how to create the conditions to be executed terjemahan3 ?
With an else, but I'm not entirely sure I understand your logic.
if (terjemahan1 == null) {
return terjemahan1.get(0).getDayak();
}
else if (terjemahan2 == null) {
return terjemahan2.get(0).getDayak();
}
else {
return terjemahan3.get(0).getDayak();
}
I think you probably want the opposite though, so you only call this on variables that are not null. In this case you have to decide which one you want to call in preference if they are all not null. Also you have to decide what to do if all of them are null.
if (terjemahan1 != null) {
return terjemahan1.get(0).getDayak();
}
else if (terjemahan2 != null) {
return terjemahan2.get(0).getDayak();
}
else if (terjemahan3 != null) {
return terjemahan3.get(0).getDayak();
}
else
{
// decide what to do in this condition
}
Hello
I am not able to get the correct validation.I think there is some error in this code so can anyone please help me solving this problem.
public static boolean validateFee(String value) {
boolean isvalid = true;
try {
int fee = 0;
if (value != null && !value.isEmpty()) {
fee = Integer.parseInt(value);
}
} catch (NumberFormatException ne) {
// ne.printStackTrace();
isvalid = false;
return isvalid;
}
return isvalid;
}
}
I am actaully using this code for validation of fee in which i m using a regex as [0-9]+.
This code i m using it in a common function.Actually validation call is done in the servlet as follows:
private Boolean validateFee(HttpSession session, PropertiesHandler props, String number) {
Boolean isvalid = true;
HashMap hashMap = new LinkedHashMap();
number = ApplicationConstants.FEE_PATTERN;
if (!Validation.validateFee(number)) {
isvalid = false;
hashMap.put("time", props.getText("error.fee.invalid.type"));
}
session.setAttribute("errorMessage", hashMap);
System.out.println("Map size " + hashMap.size());
logger.info("Exit validateTIme"); return isvalid;
}
I think there is no error in that but i have a doubt in this function.I am facing a problem like if i give number to the fee also its taking validation.please help me out
Currently it allows value of null or "" to count as being valid - is that deliberate?
Note that your current code can be rewritten more simply:
public static boolean validateFee(String value) {
try {
if (value != null && !value.isEmpty()) {
Integer.parseInt(value);
}
return true;
} catch (NumberFormatException ne) {
return false;
}
}
Now if you want null/empty to count as invalid, I'd rewrite it as:
public static boolean validateFee(String value) {
if (value == null || value.isEmpty()) {
return false;
}
try {
Integer.parseInt(value);
return true;
} catch (NumberFormatException ne) {
return false;
}
}
trim your string and then pass it to.
StringUtils.isNumeric(StringUtils.trimToNull(fees));
You can directly use StringUtils.isNumeric()
I recommend you use commons-lang StringUtils class, your validate method is re-written
public static boolean validateFee(String value) {
return StringUtils.isNumeric(StringUtils.trimToNull(value));
}
And you remove ApplicationConstants.FEE_PATTERN completely. The problem you are currently facing is that your servlet overwrites its input value with ApplicationConstants.FEE_PATTERN. Your servlet method is re-written
private Boolean validateFee(HttpSession session, PropertiesHandler props, String number) {
final Boolean valid = Validation.validateFee(number);
if (!valid) {
final HashMap hashMap = new LinkedHashMap();
hashMap.put("time", props.getText("error.fee.invalid.type"));
session.setAttribute("errorMessage", hashMap);
}
}