How to throw a parseException in a switch statement? - java

To increase my projects code coverage, I need to reach the branch ParseException in this method:
public String filterMessage(String actionIn, String messageIn) {
String message = null;
try{
switch (actionIn) {
//EDIT: this calls the other class causing parseexception
case "search":
message = (srvmt.SearchEngine(messageIn));
break;
default:
message = messageIn;
break;
}
}catch (ParseException e) {
System.out.println("Encountered parse exception");
e.printStackTrace();
}catch(IOException ioException){
ioException.printStackTrace();
}
return message;
}
Instincts are that we must put a String that is "illegal", that can't be parsed because it isn't actually a String, but how do you place something like that without causing a compile error (like putting an int to cause faulse parsing). Any ideas how to test this catch "branch"?
EDIT: This is the method the case above calls which uses a parse exception
public String SearchEngine(String removecommand)
{//INCOMING-SEARCH¿Email¿#gmail.com
JSONArray databaseupdated = read(pathdatabase);
ArrayList<String> matchlist = new ArrayList<String>();
JSONObject mainobj = new JSONObject();
JSONArray userinfo = new JSONArray();
JSONObject obj = new JSONObject();
for(int i = 0; i<databaseupdated.size(); i++)
{
String option = "";
String value = "";
try {
JSONObject json = (JSONObject) new JSONParser().parse(removecommand);
option = (String) json.get("option");
value = (String) json.get("value");
mainobj= (JSONObject) new JSONParser().parse(databaseupdated.get(i).toString());
userinfo =(JSONArray) new JSONParser().parse(mainobj.get(mainobj.keySet().toString().substring(1,mainobj.keySet().toString().length()-1)).toString());
obj = (JSONObject) new JSONParser().parse(userinfo.get(0).toString());
} //EDIT, there is a lot of code not explained, but here is the parse EXCEPTION
catch (ParseException e) {
return "false";
}
if(SearchEngineTRUEFALSE1(mainobj.keySet().toString().substring(1,mainobj.keySet().toString().length()-1),option,value))
{
matchlist.add(obj.get("Email").toString());
}
}
return matchlist.toString();
}

Try this :
throw new ParseException("Parse exception description you want");

you could throw an exception as Michaël told and if you are using Junit to test, you could do something like this using the expected annotation to catch it
#Test(expected= ParseException)
public void testFilterMessage() {
filterMessage(illformedString1, illformedString2);
}

Given your updated question:
You want to look into using a mocking framework.
Basically you have to enable your class under test so that you can provide a mocked srvmt object to it. And you configure that mock to simply throw that exception upon calls to the method it owns. Well, one of your test case configures the mock to throw that exception; other testcases would configure the mock to return other results.
In other words: search for terms like "dependency injection" and "mocking"; study and apply.

Related

Catch a list of specific exception subtypes instead for unchecked exceptions [duplicate]

I have a question about generic exceptions. How would we know which non-generic exception to use when you have a try that does multiple things.
For example:
#PostConstruct
protected void init() {
try {
HttpSession session = request.getSession();
String policyInfo = (String) session.getAttribute("policyInfo");
if(session.getAttribute("faxNumber") != null) {
faxNumber = (String) session.getAttribute("faxNumber");
}
policyNumber = (String) session.getAttribute("policyNumber");
JSONObject policyInfoObj = new JSONObject(policyInfo);
JSONArray policiesArr = policyInfoObj.getJSONArray("policies");
if (policiesArr.length() > 0) {
JSONObject policyObj = policiesArr.getJSONObject(0);
JSONArray insuredVehicle = policyObj.getJSONArray("insuredVehicle");
checkInsuredVechile(insuredVehicle);
termStartDate = policyObj.getString("effectiveDate");
JSONArray addressArray = policyObj.getJSONArray("address");
policySource = policyObj.getString("policySource");
checkAddressArry(addressArray);
}
policyNumber = policyNumber.substring(0,5)+"-"+policyNumber.substring(5,7)+"-"+policyNumber.substring(7);
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
}catch(Exception e) {
logger.error("Exception in getting policy details",e);
}
}
So for catch(Exception e) { it will need a non-generic exception, but I am having trouble to determine what it can be.
You should catch only specific exeption like:
catch(org.json.JsonException e)
and not the base class Exception, which means all possible checked and unchecked Exceptions

unreported exception ParseException; must be caught or declared to be thrown -- JAVA Error

I am building a Java app in JSF that makes a request to an API gets a JSON and fills a table with the JSON info...
This is the code:
#ManagedBean(name = "logic", eager = true)
#SessionScoped
public class Logic {
static JSONObject jsonObject = null;
static JSONObject jo = null;
static JSONArray cat = null;
public void connect() {
StringBuilder sb = new StringBuilder();
try {
URL url = new URL("xxx");
URLConnection yc = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;
while((inputLine = in.readLine())!= null){
System.out.println(inputLine);
sb.append(inputLine+"\n");
in.close();
}
}catch(Exception e) {System.out.println(e);}
try {
JSONParser parser = new JSONParser();
jsonObject = (JSONObject) parser.parse(sb.toString());
cat = (JSONArray) jsonObject.get("mesaje");
jo = (JSONObject) cat.get(0);
jo.get("cif");
System.out.println(jo.get("cif"));
}catch(Exception e){System.out.println(e);}
}
private String cif;
final static private ArrayList<Logic> logics = new ArrayList<Logic>(Arrays.asList(new Logic(jo.get("cif").toString())));
public ArrayList<Logic> getLogics() {
return logics;
}
public Logic() {
}
public Logic(String cif) throws ParseException {
this.cif = cif;
connect();
}
public String getCif() {
return cif;
}
public void setCif(String cif) {
this.cif = cif;
}
}
On line 67 -> final static private ArrayList<Logic> logics = new ArrayList<Logic>(Arrays.asList(new Logic(jo.get("cif").toString())));
it gives me this error in Netbeans: unreported exception ParseException; must be caught or declared to be thrown.
I tried surrounding it in try catch but it gives other errors in other parts of code...what can I do so I can run app ?
Thanks in advance
From what I understand, you tried something like
try {
final static private ArrayList<Logic> logics = new ArrayList<Logic>(Arrays.asList(new Logic(jo.get("cif").toString())));
} catch (Exception e) {
e.printStackTrace();
}
The problem is, that line is not inside a method, and you can't use try...catch there.
A quick way to solve this is to put that initialization in a static block
public class Logic {
final static private ArrayList<Logic> logics;
static {
try {
logics = new ArrayList<Logic>(Arrays.asList(new Logic(jo.get("cif").toString())));
} catch (Exception e) {
e.printStackTrace();
}
}
// rest of your class...
}
But honestly I have to wonder why you declared logics as static. It's not apparent from the rest of your code. Also, I see you have a non-static getLogics() method. So I'd say, if there's really no reason to declare it as static, just make it non-static and initialize it in the constructor, where you can use try...catch to your heart's content.

net.sf.json.JSONException: There is a cycle in the hierarchy

I want to write the value of list in JSON File. But it's giving an exception.
JSONArray objJsonArray = null;
FileWriter objJsonFileWriter = null;
try {
objJsonArray = (JSONArray) JSONSerializer.toJSON(objList); //<- This line is giving net.sf.json.JSONException: There is a cycle in the hierarchy
objJsonFileWriter = new FileWriter("D:\\MyJson.json");
objJsonFileWriter.write(objJsonArray.toString());
objJsonFileWriter.flush();
objJsonFileWriter.close();
} catch (JSONException jse) {
jse.printStackTrace();
}
Please make me know how to get rid of this exception. I am doing this work using core Java
Thanks #Kevin for your valuable suggestion.
JSONArray objJsonArray = null;
FileWriter objJsonFileWriter = null;
PlayerMasterJsonInfoBean objBean = null;
try {
objList.setFirst_name(getPlayerMaster.getFirst_name()); //<- Get the value from bean class then add to collection class
objList.setLast_name(getPlayerMaster.getLast_name()); //<- Get the value from bean class then add to collection class
objJsonArray = (JSONArray) JSONSerializer.toJSON(objList); //<- Then pass object here
objJsonFileWriter = new FileWriter("D:\\MyJson.json");
objJsonFileWriter.write(objJsonArray.toString());
objJsonFileWriter.flush();
objJsonFileWriter.close();
} catch (JSONException jse) {
jse.printStackTrace();
}

References in Java constructor

This is the first version of my code :
public class ListSchedule implements ListInterface {
private ArrayList<Schedule> list;
private String cookie;
public ListSchedule() {
this.list = new ArrayList<Schedule>();
}
public ArrayList<Schedule> getList() {
return list;
}
}
In another class, I made this call :
protected final ListSchedule parse(String jsonString)
throws CustomException {
ListSchedule list = new ListSchedule();
JSONArray schedulesArray;
try {
// Convert the response to a JSONObject
JSONObject json = new JSONObject(jsonString);
try {
int errorCode = json.getInt("error");
// Check if there is no error from FilBleu server
if (errorCode > 0) {
throw new CustomException(
CustomException.ERROR_FILBLEU,
"DataAccessObject", "Server error "
+ json.getInt("subError"));
}
try {
String cookie = json.getString("cookie");
list = new ListSchedule(cookie);
} catch (JSONException e) {
throw new CustomException(CustomException.JSON_FORMAT,
"DataAccessObject", "No cookie value");
}
schedulesArray = json.getJSONArray("schedules");
// NullPointerException with the line below
Log.d("DAO", list.getList().toString());
parseSchedulesArray(list, schedulesArray);
} catch (JSONException e) { // Unable to get the error code
throw new CustomException(CustomException.JSON_FORMAT,
"DataAccessObject", "Bad JSON format ("
+ e.getMessage() + ")");
}
} catch (JSONException e) { // Unable to convert response
throw new CustomException(CustomException.JSON_FORMAT,
"DataAccessObject", "Bad JSON format ("
+ e.getMessage() + ")");
}
return list;
}
then I had a NullPointerException from the line Log.d("DAO", list.getList().toString());. So I tried another solution. As you can see, the only difference is the initialization of the list property :
public class ListSchedule implements ListInterface {
private ArrayList<Schedule> list = new ArrayList<Schedule>();
private String cookie;
public ListSchedule() {
}
public ArrayList<Schedule> getList() {
return list;
}
}
and the NullPointerException was never thrown again...
I don't really understand the difference between the two ways of initializing the list property. Can somebody give me a hint please ?
I am speculating that the following constructor exists in your code base :
public ListSchedule(String cookie) {
this.cookie = cookie;
}
and what you need is the following:
public ListSchedule(String cookie) {
this.cookie = cookie;
this.list = new ArrayList<Schedule>();
}
This is further validated by the invocation of this line in your program:
list = new ListSchedule(cookie);
Notice how you don't initialize the list in the second constructor. Also you start by invoking the default constructor, but you later reassign the pointer to the object into what gets created from the String constructor of ListSchedule.
You code is calling this constructor:
list = new ListSchedule(cookie);
Which to me, does not call the one that initializes your ArrayList<Schedule> and that explains the NullReferenceException

IllegalArgumentException JSON

I am trying to put String[] in jsonObject and getting following error
java.lang.IllegalArgumentException: Invalid type of value. Type:
[[Ljava.lang.String;] with value: [[Ljava.lang.String;#189db56] at
com.ibm.json.java.JSONObject.put(JSONObject.java:241)
Please help me to resolve this.
Thanks
public JSONObject toJSONObject() {
JSONObject jsonObject = new JSONObject();
//Use reflection to get a list of all get methods
//and add there corresponding values to the JSON object
Class cl = dto.getClass();
logger.infoFormat("Converting {0} to JSON Object", cl.getName());
Method[] methods = cl.getDeclaredMethods();
for (Method method : methods) {
String methodName = method.getName();
if (methodName.startsWith("get")) {
logger.infoFormat("Processing method - {0}", methodName);
//Check for no parameters
if (method.getParameterTypes().length == 0) {
String tag = getLabel(method);
Object tagValue = new Object();
try {
tagValue = method.invoke(dto);
} catch (Exception e) {
logger.errorFormat("Error invoking method - {0}", method.getName());
}
if (method.getReturnType().isAssignableFrom(BaseDTO.class)) {
DTOSerializer serializer = new DTOSerializer((BaseDTO) tagValue);
jsonObject.put(tag, serializer.toJSONObject());
} else if (method.getReturnType().isAssignableFrom(List.class)) {
ListSerializer serializer = new ListSerializer((List<BaseDTO>) tagValue);
jsonObject.put(tag, serializer.toJSONArray());
} else {
if (tagValue != null) jsonObject.put(tag, tagValue);
}
}
}
}
return(jsonObject);
}
try
jsonObject.put("yourKey", Arrays.asList(yorStringArray));
As you should read the manual first http://www.json.org/javadoc/org/json/JSONObject.html there is no variation of it expects an Object[]
Maybe you should take a look at google-gson.
I like it very much to work with json in Java.

Categories