Unhandled exception type NoSuchFieldException (java reflection) - java

I am using Play Framework about 1 month and it is a great thing, but I had one big problem
.
I`ve try to run following code in secure controller:
MyModel myModel = MyModel.all().first();
Field idField = myModel.getClass().getField("id");
About line 2 Play says:
Compilation error
The file /app/controllers/Security.java could not be compiled. Error
raised is : Unhandled exception type NoSuchFieldException
Maybe it`s a core bug?
Thanks.

You should handle the exception that getField(String fieldName) can throw. In this case a NoSuchFieldException.
Try to write it as such:
Field idField = null;
try {
idField = myModel.getClass().getField("id");
} catch (NoSuchFieldException nsfe) {
throw new RuntimeException(nsfe);
}

If you use dp4j's #TestPrivates or #Reflect(catchExceptions =true) you don't need to write the catch statements yourself:
public class Security{
#Reflect(catchExceptions =true) //when false it will add the exceptions to the throws list.
public void aMethod(){
MyModel myModel = MyModel.all().first();
Field idField = myModel.getClass().getField("id");
//you might as well write:
// int id = myModel.id;
}

Related

Throwing a custom exception instead of other types of exceptions

I have a program in which I want to throw one of 4 exceptions that I define.
I get an HTTP response and according its error code I want to throw the exceptions:
Here is an example:
public List<Map<String, Object>> getData(String product) {
try {
Response<DataGeneralResponse> response = dataApi.dataGet(product).execute();
if (!response.isSuccessful()) {
log.error(String.format("Failed to get data for product [%s] error [%s]",
product,
Util.getErrorMsg(response)));
}
DataGeneralResponse body = response.body();
return body != null ? body.getData(): null;
} catch (Exception e) {
log.error(String.format("Failed to get data for product [%s] error[%s]",
product,
Util.getErrorMsg(response)));
}
return null;
}
So I need to to something like that in Util:
public void handleResponse(Response<DataGeneralResponse> response) throws CustomException {
switch (response.code()) {
case 500: throw new FirstCustomException(");
break;
case 404: throw new SecondCustomException(");
break;
default: throw new UnknownCustomException(");
}
}
But when I try to remove the catch clause I get unhandled IOException error on the execute method and on the getErrorMsg method.
Can someone help please?
I get unhandled IOException error on the execute method and on the getErrorMsg method.
This indicates that you have a method, which is trying to throw a checked exception, which is not surrounded by a try catch clause. By Java language standard all methods, which throw checked exceptions must do one of the two ..
Be surrounded by a try-catch block which catches the relevant exception
Declare that they throw the relevant exception by using the throws keyword
You can use one of the methods above to deal with error you are getting.
If this does not completely solve your problem, please add a comment below and I'll respond.

How would I access this variable from outside of this method?

I've been attempting to develop a Minecraft mod, but have hit a road block in which I have had no luck in surpassing. In my attempts to find a fix for this issue, I have sifted through multiple other questions and websites, but to no avail.
The closest I have gotten would be where I created the variable outside of the method and then set the value inside of the method. But, the issue with this is that it would always return with null.
Also, if it was not clear, I am talking about the "taskEntriesMethod" variable.
Here's my code:
public void getExecutingTaskEntries(Profiler profiler)
{
try
{
Class<?> AITasks = Class.forName("net.minecraft.entity.ai.EntityAITasks");
Field taskEntries = AITasks.getDeclaredField("executingTaskEntries");
taskEntries.setAccessible(true);
Object AITasksObj = taskEntries.get(new EntityAITasks(profiler));
Set<EntityAITasks.EntityAITaskEntry> taskEntriesMethod = (Set<EntityAITaskEntry>) AITasksObj;
}
catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException exception) { exception.printStackTrace(); }
}
private final Set<EntityAITasks.EntityAITaskEntry> executingTaskEntries = taskEntriesMethod; // <-- (this is what errors out)
You've created a get method but have declared it as a void. You probably want to change your code to something like this:
public Set<EntityAITasks.EntityAITaskEntry> getExecutingTaskEntries(Profiler profiler) {
//your code
return (Set<EntityAITaskEntry>) AITasksObj;
}
And then use it like so
Set<EntityAITasks.EntityAITaskEntry> executingTaskEntries = getExecutingTaskEntries(profiler)
Do you need executingTaskEntries to be final?
You could simply:
public void initExecutingTaskEntries(Profiler profiler) // changed name here, get suggested its going to return something
{
try
{
Class<?> AITasks = Class.forName("net.minecraft.entity.ai.EntityAITasks");
Field taskEntries = AITasks.getDeclaredField("executingTaskEntries");
taskEntries.setAccessible(true);
Object AITasksObj = taskEntries.get(new EntityAITasks(profiler));
executingTaskEntries = (Set<EntityAITaskEntry>) AITasksObj;
}
catch (ClassNotFoundException | NoSuchFieldException | IllegalAccessException exception) { exception.printStackTrace(); }
}
private Set<EntityAITasks.EntityAITaskEntry> executingTaskEntries;
if you need executingTaskEntries to be final then I would initialize it as empty Set and then just add entires to it within your method.

JUnit tests: How to check for errors with a try-catch block

So, I need to write a test for some (legacy) code I'm improving. In a method, I try to parse some string (which should be legal JSON). Then a possible JSONException is caught if the string doesn't represents valid JSON. Something like:
public void transformToJSON(String source) {
try {
JSONObject js = new JSONObject(new JSONTokener(item.getHtml()));
}
catch (JSONException e) {
log(e)
}
//than js is added to an Hashset and the method is done
}
So I want to write a test for good input (to see if I have generated a correct JSON-object). This is 'easy' by checking the object in the Set.
For wrong input however, I need to find out if the correct error has been thrown.
I know if an error was thrown in the code, I can check for it in the test.
By setting the rule public ExpectedException thrown=
ExpectedException.none(); and checking for it in test method.
By adding #Test(expected = JSONException.class) above the test
But both wont work for try..catch blocks.
How can I test if the proper exception is caught by catch block? I want to change as little of the source code as possible.
In the JUnit test class you can do is use fail("this should not have happened") in the try or catch block depending on what should and should not work (as in: try and catch in the JUnit class, not in your actual method!).
However, with a try/catch block within your method you cannot see whether an Exception occured or not, because it is handled within the method. So you would have to throw the exception in the method instead of catching it, i.e.,
public void transformToJSON(String source) throws JSONException { ... }
Then it will work to check whether an exception occured or not.
Alternatively you could return a boolean that states whether the transformation was successful or not. Then you can test whether the return value was true/false and if that was what you expected.
public boolean transformToJSON(String source) {
boolean success = true;
try {
JSONObject js = new JSONObject(new JSONTokener(item.getHtml()));
}
catch (JSONException e) {
log(e)
success = false;
}
//than js is added to an Hashset and the method is done
return success;
}
In your test class:
#Test
public void testTransformToJSON() {
assertTrue(transformToJSON("whatever"));
}
Based on the logging being used in the code, you can use Mockito to verify the message logged inside catch block.
Please go through the following link for more details on setting up the unit tests
http://bloodredsun.com/2010/12/09/checking-logging-in-unit-tests/
Your legacy code is swallowing the Exception. If it throws an exception, then your junit #Test ( expected = JSONException.class) would work.
I'd change the code slightly so it is
public void transformToJSON(String source) {
try {
JSONObject js = getJSON(item.getHtml()));
}
catch (JSONException e) {
log(e)
}
//than js is added to an Hashset and the method is done
}
public JSONObject getJSON(String source) throws JSONException {
return new JSONObject(new JSONTokener(source));
}
and then test against getJSON. This throws an exception and as other have said (and you) you can use the expectedException in the test class
use a bad formatted json string, and then do assertions or whatever in the catch block of ur test.
#Test
public void shouldCatchException(){
String source = "{ \"name\":\"John\", \"age\":30, \"car\":null ";
try {
jsonHelper.transformToJSON(source);
}catch (JSONException e){
Assert.assertThat(e, notNullValue());
assertTrue(StringUtils.isNotBlank(e.getMessage());
//whatever else u need to assert
}
}

Unable to catch exception for bad URL in JAVA class thrown by SCALA class

Im writing a program that should read data from an online XML file. The computation is done by classes written in Scala, should any exception be caught, it must be thrown to a Java class that will handle the exceptions. For some reason, i get an error with the exception type. What is the right exception that should be thrown when trying to access a bad URL or any similar issue (no internet connection?). Thanks!
The main class (Scala)
object test
{
def main(args:Array[String])
{
val x:A = new A()
}
}
The class that parses the XML file and tries to access the URL
import java.net.{URL, URLConnection}
import xml.{XML, Elem}
import java.lang.NullPointerException
import java.io.IOException
class XMLparser {
#throws(classOf[Exception])
private val connectionXMLURL = "http://www.boi.org.il/currency.xml1"
private var urlConnection:URLConnection = null
private var url:URL = null
private var doc:Elem = null
private val currencies = new java.util.LinkedHashMap[String,java.lang.Double]()
try
{
url = new URL(connectionXMLURL)
urlConnection = url.openConnection
doc = XML.load(urlConnection.getInputStream)
}
catch
{
case ex: org.xml.sax.SAXParseException => //is caught!!! and thrown!
{
throw ex
}
case e: IOException =>
{
throw e
//add error log!!
}
case e: NullPointerException =>
{
throw e
//add error log!!
}
case e: Exception =>
{
throw e
}
}
}
The class that should catch the exception (Java)
public class A
{
private XMLparser x;
public A()
{
try
{
x = new XMLparser();
}
catch(org.xml.sax.SAXParseException e) //Cannot catch it!!??
{
}
/* catch (Exception e)
{
e.printStackTrace();
} */
}
}
EDIT: this is the error message i get when trying to catch the exception:
scala: warning: [options] bootstrap class path not set in conjunction with -source 1.6
scala: C:\Users\home\Dropbox\Exchange Currency\src\il\hit\currencyExchange\CurrencyExchangeGUI.java:138: error: exception SAXParseException is never thrown in body of corresponding try statement
scala: catch (org.xml.sax.SAXParseException ex)
The problem is that you need to declare that your constructor method (the default one) throws a checked java exception. I saw that you already added the #throws(classOf[Exception]) annotation to your code, but it is slightly misplaced for your purposes. Check this link
https://issues.scala-lang.org/browse/SI-1420
It should look like
class XMLparser #throws(classOf[Exception]) {
private val connectionXMLURL = "http://www.boi.org.il/currency.xml1"
...
For an URLConnection, it can be SocketTimeoutException for both connection and input stream timeouts. It can also be an IOException for an unavailable website.
You can find this in the javadoc for URLConnection

Java - retrieving large amounts of data from a DB using iBatis

I need to extract data from a DB2 table, run some processing on each returned row and output to a flat file. I'm using iBatis but found that using the queryForList I started getting out of memory errors, I'll be looking at 100k+ rows of data increasing.
I've looked at using queryWithRowHandler instead but the iBatis RowHandler interface doesn't throw an exception from its handleRow function so if it gets an error I can't properly report it back and stop iterating the rest of the data. It looks like I can throw a RuntimeException but that doesn't strike me as a neat way of doing things.
I'd like to be able to stop processing while throwing a meaningful Exception indicating whether the error occurred on the data manipulation, the file access or whatever.
Has anyone had experience with this approach or have an alternative solution using iBatis. I know I could look to do this without iBatis, just using JDBC, but as iBatis is used for all other DB access in my app I'd like to avail of this architecture if possible.
1) Create your own RowHandler interface with checked Exceptions in signature:
public interface MySpecialRowHandler {
public void handleRow(Object row)
throws DataException, FileException, WhateverException;
}
2) Inherit (or even better, delegate ) from SqlMapDaoTemplate to add a new method that will manage your own handler with the same Exceptions in signature:
public class MySpecialTemplate extends SqlMapDaoTemplate {
...
public void queryWithRowHandler(String id,
final MySpecialRowHandler myRowHandler
) throws DataException, FileException, WhateverException {
// "holder" will hold the exception thrown by your special rowHandler
// both "holder" and "myRowHandler" need to be declared as "final"
final Set<Exception> holder = new HashSet<Exception>();
this.queryWithRowHandler(id,new RowHandler() {
public void handleRow(Object row) {
try {
// your own row handler is executed in IBatis row handler
myRowHandler.handleRow(row);
} catch (Exception e) {
holder.add(e);
}
}
});
// if an exception was thrown, rethrow it.
if (!holder.isEmpty()) {
Exception e = holder.iterator().next();
if (e instanceof DataException) throw (DataException)e;
if (e instanceof FileException) throw (FileException)e;
if (e instanceof WhateverException) throw (WhateverException)e;
// You'll need this, in case none of the above works
throw (RuntimeException)e;
}
}
}
3) Your business code will look like this:
// create your rowHandler
public class Db2RowHandler implements MySpecialRowHandler {
void handleRow(Object row) throws DataException, FileException, WhateverException {
// what you would have done in ibatis RowHandler, with your own exceptions
}
}
// use it.
MySpecialTemplate template = new MySpecialTemplate(daoManager);
try {
template.queryWithRowHandler("selectAllDb2", new Db2RowHandler());
} catch (DataException e) {
// ...
} catch (FileException e) {
...

Categories

Resources