Jackson Deserialize Integer Converting Error - java

I am trying to handle if required filed comes with a String value while I expect it as Integer. For example;
{
"transactionTimeMilliseconds": "asd"
}
but it defined as int in Java code.
private int transactionTimeMilliseconds;
#JsonCreator
public Channel(#JsonProperty("transactionTimeMilliseconds") int transactionTimeMilliseconds) {
this.transactionTimeMilliseconds = transactionTimeMilliseconds;
}
I have an exception informer class.
CLASS
#ControllerAdvice
public class ExceptionConfiguration extends ResponseEntityExceptionHandler {
#ExceptionHandler(MismatchedInputException.class) // Or whatever exception type you want to handle
public ResponseEntity<JsonException> handleMissingFieldError(MismatchedInputException exception) { // Or whatever exception type you want to handle
int code = 601;
String message = exception.getMessage().split("\n")[0] + exception.getMessage().split(";")[1].replace("]", "");
JsonException jsonException = new JsonException(code,message);
return ResponseEntity.status(jsonException.getCode()).body(jsonException);
}
#ExceptionHandler(UnrecognizedPropertyException.class) // Or whatever exception type you want to handle
public ResponseEntity<JsonException> handleUnrecognizedFieldError(UnrecognizedPropertyException exception) { // Or whatever exception type you want to handle
int code = 602;
String message = exception.getMessage().split(",")[0] + exception.getMessage().split(";")[1].replace("]", "");
JsonException jsonException = new JsonException(code,message);
return ResponseEntity.status(jsonException.getCode()).body(jsonException);
}
#ExceptionHandler(JsonParseException.class) // Or whatever exception type you want to handle
public ResponseEntity<JsonException> handleJsonParseError(JsonParseException exception) {
int code = 603;
String message = exception.getMessage().split(":")[0] + exception.getMessage().split(";")[1].replace("]", "");
JsonException jsonException = new JsonException(code,message);
return ResponseEntity.status(jsonException.getCode()).body(jsonException);
}
#ExceptionHandler(InvalidFormatException.class) // Or whatever exception type you want to handle
public ResponseEntity<JsonException> handleJsonInvalidFormatError(InvalidFormatException exception) {
int code = 604;
String message = exception.getMessage().split(":")[0] + exception.getMessage().split(";")[1].replace("]", "");
JsonException jsonException = new JsonException(code,message);
return ResponseEntity.status(jsonException.getCode()).body(jsonException);
}
#ExceptionHandler(JsonMappingException.class) // Or whatever exception type you want to handle
public ResponseEntity<JsonException> handleNullFieldError(JsonMappingException exception) {
int code = 605;
String message = exception.getMessage().split(":")[0] + exception.getMessage().split(";")[1].replace("]", "");
JsonException jsonException = new JsonException(code,message);
return ResponseEntity.status(jsonException.getCode()).body(jsonException);
}
}
I have to recognize that value, and if this field is wrong as written in above, set it default value as 0.
Should I write a custom deserializer to solve this problem? Thanks.

something like this worked for me :
class Val {
private int v;
public int getV() {
return v;
}
#JsonSetter // or #JsonProperty("v")
public void setV(String v) {
System.out.println("in setter");
try {
this.v = Integer.parseInt(v);
} catch (Exception e) {
this.v = 0;
}
}
}
Test:
#Test
public void test() throws IOException {
String json = " { \"v\" : 1 } ";
Val v = new ObjectMapper().readValue(json, Val.class);
System.out.println(v.getV()); // prints 1
json = " { \"v\" : \"asd\" } ";
v = new ObjectMapper().readValue(json, Val.class);
System.out.println(v.getV()); // prints 0
}
I tried something like this but couldn't get it to work so far.
class Val {
private int v;
#JsonCreator
public Val(#JsonProperty("v") String v) {
System.out.println("in setter");
try {
this.v = Integer.parseInt(v);
} catch (Exception e) {
this.v = 0;
}
}
public int getV() {
return v;
}
}

Related

TupleTag not found in DoFn

I have a DoFn that is supposed to split input into two separate PCollections. The pipeline builds and runs up until it is time to output in the DoFn, and then I get the following exception:
"java.lang.IllegalArgumentException: Unknown output tag Tag<edu.mayo.mcc.cdh.pipeline.PubsubToAvro$PubsubMessageToArchiveDoFn$2.<init>:219#2587af97b4865538>
at org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions.checkArgument(Preconditions.java:216)...
If I declare the TupleTags I'm using in the ParDo, I get that error, but if I declare them outside of the ParDo I get a syntax error saying the OutputReceiver can't find the tags. Below is the apply and the ParDo/DoFn:
PCollectionTuple results = (messages.apply("Map to Archive", ParDo.of(new PubsubMessageToArchiveDoFn()).withOutputTags(noTag, TupleTagList.of(medaPcollection))));
PCollection<AvroPubsubMessageRecord> medaPcollectionTransformed = results.get(medaPcollection);
PCollection<AvroPubsubMessageRecord> noTagPcollectionTransformed = results.get(noTag);
static class PubsubMessageToArchiveDoFn extends DoFn<PubsubMessage, AvroPubsubMessageRecord> {
final TupleTag<AvroPubsubMessageRecord> medaPcollection = new TupleTag<AvroPubsubMessageRecord>(){};
final TupleTag<AvroPubsubMessageRecord> noTag = new TupleTag<AvroPubsubMessageRecord>(){};
#ProcessElement
public void processElement(ProcessContext context, MultiOutputReceiver out) {
String appCode;
PubsubMessage message = context.element();
String msgStr = new String(message.getPayload(), StandardCharsets.UTF_8);
try {
JSONObject jsonObject = new JSONObject(msgStr);
LOGGER.info("json: {}", jsonObject);
appCode = jsonObject.getString("app_code");
LOGGER.info(appCode);
if(appCode == "MEDA"){
LOGGER.info("Made it to MEDA tag");
out.get(medaPcollection).output(new AvroPubsubMessageRecord(
message.getPayload(), message.getAttributeMap(), context.timestamp().getMillis()));
} else {
LOGGER.info("Made it to default tag");
out.get(noTag).output(new AvroPubsubMessageRecord(
message.getPayload(), message.getAttributeMap(), context.timestamp().getMillis()));
}
} catch (Exception e) {
LOGGER.info("Error Processing Message: {}\n{}", msgStr, e);
}
}
}
Can you try without MultiOutputReceiver out parameter in the processElement method ?
Outputs are then returned with context.output with passing element and corresponding TupleTag.
Your example only with context :
static class PubsubMessageToArchiveDoFn extends DoFn<PubsubMessage, AvroPubsubMessageRecord> {
final TupleTag<AvroPubsubMessageRecord> medaPcollection = new TupleTag<AvroPubsubMessageRecord>(){};
final TupleTag<AvroPubsubMessageRecord> noTag = new TupleTag<AvroPubsubMessageRecord>(){};
#ProcessElement
public void processElement(ProcessContext context) {
String appCode;
PubsubMessage message = context.element();
String msgStr = new String(message.getPayload(), StandardCharsets.UTF_8);
try {
JSONObject jsonObject = new JSONObject(msgStr);
LOGGER.info("json: {}", jsonObject);
appCode = jsonObject.getString("app_code");
LOGGER.info(appCode);
if(appCode == "MEDA"){
LOGGER.info("Made it to MEDA tag");
context.output(medaPcollection, new AvroPubsubMessageRecord(
message.getPayload(), message.getAttributeMap(), context.timestamp().getMillis()));
} else {
LOGGER.info("Made it to default tag");
context.output(noTag, new AvroPubsubMessageRecord(
message.getPayload(), message.getAttributeMap(), context.timestamp().getMillis()));
}
} catch (Exception e) {
LOGGER.info("Error Processing Message: {}\n{}", msgStr, e);
}
}
I also show you an example that works for me :
public class WordCountFn extends DoFn<String, Integer> {
private final TupleTag<Integer> outputTag = new TupleTag<Integer>() {};
private final TupleTag<Failure> failuresTag = new TupleTag<Failure>() {};
#ProcessElement
public void processElement(ProcessContext ctx) {
try {
// Could throw ArithmeticException.
final String word = ctx.element();
ctx.output(1 / word.length());
} catch (Throwable throwable) {
final Failure failure = Failure.from("step", ctx.element(), throwable);
ctx.output(failuresTag, failure);
}
}
public TupleTag<Integer> getOutputTag() {
return outputTag;
}
public TupleTag<Failure> getFailuresTag() {
return failuresTag;
}
}
In my first output (good case), no need to pass the TupleTag ctx.output(1 / word.length());
For my second output (failure case), I pass the Failure tag with the corresponding element.
I was able to get around this by making my ParDo an anonymous function instead of a class. I put the whole function inline and had no problem finding the output tags after I did that. Thanks for the suggestions!

Unable to change the value of variable name?

Can i change the value inside the compare method? Error - variable need to be declared final, but final wont allow me to change.
I want to compare some other variables the JSONarray(like total_transit_time, total_walking_time). i cant think of another solution to do that. could someone teach me an easier way to do it?
public JSONArray findShortest(JSONObject json_object) throws JSONException {
JSONArray sortedJsonArray = new JSONArray();
List<JSONObject> jsonList = new ArrayList<JSONObject>();
for (int i = 0; i < json_object.length(); i++) {
int name = i;
JSONObject json_array = json_object.optJSONObject(""+name);
jsonList.add(json_array);
}
System.out.println("jsonList = " + jsonList.toString());
Collections.sort(jsonList, new Comparator<JSONObject>() {
public int compare(JSONObject a, JSONObject b) {
String valA = new String();
String valB = new String();
try {
valA = String.valueOf(a.get("total_duration"));
valB = String.valueOf(b.get("total_duration"));
} catch (JSONException e) {
//do something
}
return valA.compareTo(valB);
}
});
to this
public JSONArray findShortest(JSONObject json_object, String sortByThisElement) throws JSONException {
......
......
try {
valA = String.valueOf(a.get(sortByThisElement));
valB = String.valueOf(b.get(sortByThisElement));
} catch (JSONException e) {
//do something
}
......
}
});
You can declare your sortByThisElement to be final,then you can use it directly:
public JSONArray findShortest(JSONObject json_object, final String sortByThisElement) throws JSONException {
......
......
try {
valA = String.valueOf(a.get(sortByThisElement));
valB = String.valueOf(b.get(sortByThisElement));
} catch (JSONException e) {
//do something
}
......
}
});
the other way is,create a final variable in your method,then visit it in your compare method:
public JSONArray findShortest(JSONObject json_object, String sortByThisElement) throws JSONException {
......
......
System.out.println("jsonList = " + jsonList.toString());
final String sortByThis = sortByThisElement;//note this should be add before Collections.sort
........
try {
valA = String.valueOf(a.get(sortByThis));
valB = String.valueOf(b.get(sortByThis));
} catch (JSONException e) {
//do something
}
......
}
});

Not a JSON Object Exception

I'm trying to get the JSON values from Distance24 JSON output via Google GSON.
But I can't figure out what and where the Exception comes from (I'm using Google AppEngine with Java).
Here's the class from which i send and get the request and response.
package de.tum.in.eist.distance;
import java.io.IOException;
import javax.inject.Inject;
import java.net.URL;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.gson.JsonObject;
import de.tum.in.eist.JsonHelper;
import de.tum.in.eist.URLFetchServiceHelper;
public class Distance24Client {
private final URLFetchService service;
#Inject
public Distance24Client(URLFetchService service) {
this.service = service;
}
public Distance24 getDistanceAPI(String source, String destination) throws IOException {
URL url = new URL("http://www.distance24.org/route.json?stops=" + source + "|" + destination);
HTTPResponse response = service.fetch(url);
String jsonString = URLFetchServiceHelper.toString(response);
try {
JsonObject json = JsonHelper.parse(jsonString);
return toDistance24(json);
} catch (Exception e) {
throw new IOException("Error ocurred in getDistanceAPI(): " + e.getMessage());
}
}
private Distance24 toDistance24(JsonObject response) {
if (!(response.get("stops").getAsJsonObject().getAsJsonArray().size() != 0)) {
throw new IllegalArgumentException("No Status set from Distance24 API");
} else {
JsonObject distances = response.get("distances").getAsJsonObject();
return new Distance24(distances);
}
}
}
And here's the Distance24 Object:
package de.tum.in.eist.distance;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
public class Distance24 {
private int[] distances;
private int totalDistance;
private Double sourceLat;
private Double sourceLon;
private Double destLat;
private Double destLong;
public Distance24(JsonObject distances) {
this.setDistances(getIntArray(distances));
this.setTotalDistance(getSum(this.distances));
this.setSourceLat(distances.get("stops").getAsJsonObject().getAsJsonArray().get(0).getAsJsonObject().get("latitude").getAsDouble());
this.setSourceLon(distances.get("stops").getAsJsonObject().getAsJsonArray().get(0).getAsJsonObject().get("longitude").getAsDouble());
this.setDestLat(distances.get("stops").getAsJsonObject().getAsJsonArray().get(1).getAsJsonObject().get("latitude").getAsDouble());
this.setDestLong(distances.get("stops").getAsJsonObject().getAsJsonArray().get(1).getAsJsonObject().get("longitude").getAsDouble());
}
private int[] getIntArray(JsonObject array) {
JsonArray distances = array.getAsJsonArray();
int[] result = new int[distances.size()];
for(int i = 0; i < distances.size(); i++) {
result[i] = distances.get(i).getAsInt();
}
return result;
}
private int getSum(int[] array) {
int sum = 0;
for(int element : array) {
sum += element;
}
return sum;
}
private void setDistances(int[] distances) {
this.distances = distances;
}
public int getTotalDistance() {
return totalDistance;
}
public void setTotalDistance(int totalDistance) {
this.totalDistance = totalDistance;
}
public Double getSourceLat() {
return sourceLat;
}
public void setSourceLat(Double sourceLat) {
this.sourceLat = sourceLat;
}
public Double getSourceLon() {
return sourceLon;
}
public void setSourceLon(Double sourceLon) {
this.sourceLon = sourceLon;
}
public Double getDestLat() {
return destLat;
}
public void setDestLat(Double destLat) {
this.destLat = destLat;
}
public Double getDestLong() {
return destLong;
}
public void setDestLong(Double destLong) {
this.destLong = destLong;
}
}
As a result, I get the whole JSON Object as a String output for e.getMessage(). So I guess the information retrieving works, even though it's on the wrong part of the code.
Plus in the same try-catch-block of the code (Distance24Client, method "toDistance24") it says, the error ocurred in line 30, which is the return statement of the "toDistance24" method.
(clickable)
Running http://www.distance24.org/route.json?stops=detroit|dublin from my browser gives me
{"stops":[{"region":"Michigan ...
"distances":[5581]}
So distances is an array and not an object.
So your line:
JsonObject distances = response.get("distances").getAsJsonObject();
is wrong. Read distances as a JsonArray.
Create a method to handle array or no-array
public static JsonElement toJsonElement(String jsonString) {
JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse(jsonString);
JsonElement result = null;
if (jsonElement instanceof JsonObject) {
result = jsonElement.getAsJsonObject();
} else if (jsonElement instanceof JsonArray) {
result = jsonElement.getAsJsonArray();
} else {
throw new IllegalArgumentException(jsonString + " is not valid JSON stirng");
}
return result;
}

ADF Faces: It's possible to Customize Error Handling without ADF BC

Is there away to customize Error Handling in ADF Faces without ADF BC?
This is my approach.
Class MyErrorHandler extends DCErrorHandlerImpl
public class MyErrorHandler extends DCErrorHandlerImpl {
private static final ADFLogger logger = ADFLogger.createADFLogger(MyErrorHandler.class);
private static ResourceBundle rb =
ResourceBundle.getBundle("error.handling.messages.ErrorMessages_de_DE");
public MyErrorHandler() {
super(true);
}
public MyErrorHandler(boolean setToThrow) {
super(setToThrow);
}
public void reportException(DCBindingContainer bc, java.lang.Exception ex) {
disableAppendCodes(ex);
logger.info("entering reportException() method");
BindingContext ctx = bc.getBindingContext();
if (ex instanceof NullPointerException) {
logger.severe(ex);
JboException e = new JboException(rb.getString("STANDARD_ERROR_MESSAGE"));
super.reportException(bc, e);
} else if (ex instanceof RowValException) {
Object[] exceptions = ((RowValException) ex).getDetails();
if (exceptions != null) {
for (int i = 0; i < exceptions.length; i++) {
if (exceptions[i] instanceof RowValException) {
this.reportException(bc, (Exception) exceptions[i]);
} else if (exceptions[i] instanceof AttrValException) {
super.reportException(bc, (Exception) exceptions[i]);
}
}
} else {
this.reportException(bc, ex);
}
} else if (ex instanceof TxnValException) {
Object[] exceptions = ((TxnValException) ex).getDetails();
if (exceptions != null) {
for (int i = 0; i < exceptions.length; i++) {
if (exceptions[i] instanceof RowValException) {
this.reportException(bc, (Exception) exceptions[i]);
} else {
super.reportException(bc, (Exception) exceptions[i]);
}
}
} else {
super.reportException(bc, ex);
}
}
else if (ex instanceof oracle.jbo.DMLException) {
JboException e = new JboException(rb.getString("STANDARD_ERROR_MESSAGE"));
super.reportException(bc, e);
} else if (ex instanceof javax.xml.ws.WebServiceException) {
JboException e = new JboException(rb.getString("WEB_SERVICE_EXCEPTION"));
super.reportException(bc, e);
}
else if (ex instanceof JboException) {
super.reportException(bc, ex);
}
}
public static FacesMessage getMessageFromBundle(String key, FacesMessage.Severity severity) {
ResourceBundle bundle =
ResourceBundle.getBundle("sahaj.apps.vleadministration.view.resources.VLEAdministrationUIBundle");
String summary = JSFUtils.getStringSafely(bundle, key, null);
String detail = JSFUtils.getStringSafely(bundle, key + "_detail", summary);
FacesMessage message = new FacesMessage(summary, detail);
message.setSeverity(severity);
return message;
}
private void disableAppendCodes(Exception ex) {
if (ex instanceof JboException) {
JboException jboEx = (JboException) ex;
jboEx.setAppendCodes(false);
Object[] detailExceptions = jboEx.getDetails();
if ((detailExceptions != null) && (detailExceptions.length > 0)) {
for (int z = 0, numEx = detailExceptions.length; z < numEx; z++) {
System.err.println("Detailed Exception : "+ detailExceptions[z].toString());
disableAppendCodes((Exception) detailExceptions[z]);
}
}
}
}
#Override
protected boolean skipException(Exception ex) {
if (ex instanceof JboException) {
return false;
} else if (ex instanceof SQLIntegrityConstraintViolationException) {
return true;
}
return super.skipException(ex);
}
private String handleApplicationError(String errorMessageRaw) {
String errorMessageCode = getErrorCode(errorMessageRaw);
// application error code
String errorMessage = null;
for (String key : errorPrefixes) {
if (errorMessageCode.startsWith(key)) {
try {
errorMessage = rb.getString(errorMessageCode);
} catch (MissingResourceException mre) {
// application error code not found in the bundle,
// use original message
return errorMessageRaw;
}
break;
}
}
// return the formated application error message
return errorMessage;
}
private String getErrorCode(String errorMessageRaw) {
// check for null/empty error message
if (errorMessageRaw == null || errorMessageRaw.isEmpty()) {
return errorMessageRaw;
}
int start = 0;
String currentErrorCodePrefix = null;
int count = 0;
// check for error message
for (String errorCode : errorPrefixes) {
count += 1;
start = errorMessageRaw.indexOf(errorCode);
if (start >= 0) {
currentErrorCodePrefix = errorCode;
start += currentErrorCodePrefix.length();
break;
}
if (count == errorPrefixes.size())
return errorMessageRaw;
}
int endIndex = start + 5;
// get the CURRENT error code
return currentErrorCodePrefix + errorMessageRaw.substring(start, endIndex);
}
#Override
public String getDisplayMessage(BindingContext bindingContext, Exception exception) {
String data=super.getDisplayMessage(bindingContext, exception);
System.err.println("Exception DATA : "+ data);
String msg= handleApplicationError(data);
System.err.println("Exception MSG : "+ msg);
return msg;
}
#Override
public DCErrorMessage getDetailedDisplayMessage(BindingContext bindingContext, RegionBinding regionBinding,
Exception exception) {
return super.getDetailedDisplayMessage(bindingContext, regionBinding, exception);
}
private static Set<String> errorPrefixes = new HashSet<String>();
static {
errorPrefixes.add("JBO-");
errorPrefixes.add("ORA-");
errorPrefixes.add("DCA-");
}
}
In my DataBinding.cpx
<Application xmlns="http://xmlns.oracle.com/adfm/application" version="12.1.2.66.68" id="DataBindings"
SeparateXMLFiles="false" Package="de.nkk.oasis.ui.web" ClientType="Generic"
ErrorHandlerClass="MyErrorHandler">
After that i generate Data Controller from Myclass.
//MyClass
/**
* method throwing a Nullpointer exception
*/
public void throwNPE() {
Object o = null;
String s = o.toString();
//bang occurs in the line above, no need for any more code
//...
}
/**
* Method that throws a single JboException
*/
public void throwJboException(){
throw new JboException("This is a JboException thrown in ADF BC");
}
and bind the two methods to JSF
<af:button actionListener="#{bindings.throwNPE.execute}" text="throwNPE"
disabled="#{!bindings.throwNPE.enabled}" id="b2"/>
<af:button actionListener="#{bindings.throwJboException.execute}" text="throwJboException"
disabled="#{!bindings.throwJboException.enabled}" id="b3"/>
NOW COMES MY PROBLEM:
Whenever i click one the Button i get
DCA-29000 unexcepted Exception
Try remove
disabled="#{!bindings.throwNPE.enabled}"
and
disabled="#{!bindings.throwJboException.enabled}"

I'm getting a Null pointer exception in my code because of the hashmap not being filled or maybe not

I was given this exercise:
Implement the following class that loads and prints a set of data values.
import java.util.Iterator;
public class MyLoader {
public void loadAndPrintValues(Iterator<String> keysToLoad, Data data, Printer printer) {
// Load data values like this:
// String value = data.loadValue(key);
// Print loaded data value like this:
// printer.printEntry(key, value);
}
}
However when I did the exercise I got a NullPointerException, probably from the while (keysToLoad.hasNext()) or from the key = keysToLoad.next();. I assume I got the exception because "data" was not getting filled but I can't figure out how to do it. Here is my code and error message
public interface Data{
//I made this method
public void makeEntry(String key, String value);
//given
public String loadValue(String key);
}
public interface Printer {
public void displayEntry(String key, String value);
}
import java.util.Iterator;
import java.util.HashMap;
public class MyLoader implements Data, Printer {
Data data; // = new MyLoader();
Printer printer; // = new MyLoader();
Iterator<String> iter; // = new MyLoader();
String key = "";
String value = "";
HashMap<String, String> ht = new HashMap<String, String>();
public MyLoader(){
// this.database = null;
// this.key = null;
// this.value = null;
// this.ht = null;
// this.iter = null;
System.out.println("now in the constructor");
}
public MyLoader(Iterator<String> iter, Data data, Printer printer){
this.data = data;
this.printer = printer;
this.iter = iter;
}
public void loadAndPrintValues(Iterator<String> keysToLoad, Data data, Printer printer) {
try {
if (ht.isEmpty()){
System.out.println("ht is empty");
throw new NullPointerException("Database is empty.");
}else {
this.data = data;
}
while (keysToLoad.hasNext()){
// Load data values like this:
key = keysToLoad.next();
value = data.loadValue(key);
// Print loaded data value like this:
printer.printEntry(key, value);
}
}catch (NullPointerException npe){
System.out.println("caught null pointer ");
System.out.println(npe.getMessage());
}
}
#Override
public void makeEntry(String key, String value){
ht.put(key, value);
}
#Override
public void printEntry(String key, String value) {
System.out.println("[" + key + " : " + value + "]");
}
#Override
public String loadValue(String key) {
System.out.println("loadValue:" + key);
if(this.ht.containsKey(key))
return this.ht.get(key);
else {
System.out.println("No key in database.");
throw new NullPointerException("No key in data.");
}
}
}
public class test {
public static void main(String[] args) {
try {
MyLoader mdbl = new MyLoader();
mdbl.makeEntry("0", "zero");
mdbl.makeEntry("1", "One");
mdbl.makeEntry("2", "Two");
mdbl.makeEntry("3", "Three");
mdbl.loadAndPrintValues(mdbl.iter, mdbl.data, mdbl.printer);
}
catch(NullPointerException e){
System.out.println(e.getMessage());
}
}
}
mdbl.iter is never assigned a value, i.e. is null (by default, since you are using the MyLoader constructor without arguments in which iter is not assigned). So when you pass it to a method that tries to do operations on it, you naturally get a NullPointerException (not an error).
You should not have
try{ /* ... */ } catch (NullPointerException npe){ /* ... */ }
blocks because any decent IDE will allow you to get to the line where the exception was thrown with one click, which is not the case if you catch the exception and simply print a message to System.out.
You are passing null values for Iterator, Data and Printer parameter of the method loadAndPrintValues() which will result in NullPointerException.
in this line
mdbl.loadAndPrintValues(mdbl.iter, mdbl.data, mdbl.printer);
you didn't initialize the mdbl.data and mdbl.printer
Never ever catch a NullPointerException. Remove the catch block with NullPointerException, run it and then post the stack trace.

Categories

Resources