Hi I have this piece of code which is giving me trouble:
StmtIterator iter2 = model.listStatements(new SimpleSelector(null, FOAF.family_name, (RDFNode) null) {
public boolean selects(Statement s) {
// return the statements whose object equal to the required place
return s.getString().toLowerCase().equals(latin.toLowerCase());
}
});
if (iter2.hasNext()) {
while (iter2.hasNext()) {
Statement s = iter2.nextStatement();
// s.getSubject().addProperty(FOAF.family_name, maltese, "mt");
}
}
The commented line is the line throwing the exception. Any idea why this is happening?
This is the whole error output:
Exception in thread "main" java.util.ConcurrentModificationException
at com.hp.hpl.jena.mem.HashCommon$BasicKeyIterator.hasNext(HashCommon.java:354)
at com.hp.hpl.jena.util.iterator.NiceIterator$1.hasNext(NiceIterator.java:103)
at com.hp.hpl.jena.util.iterator.WrappedIterator.hasNext(WrappedIterator.java:90)
at com.hp.hpl.jena.util.iterator.Map1Iterator.hasNext(Map1Iterator.java:48)
at com.hp.hpl.jena.util.iterator.WrappedIterator.hasNext(WrappedIterator.java:90)
at com.hp.hpl.jena.util.iterator.WrappedIterator.hasNext(WrappedIterator.java:90)
at com.hp.hpl.jena.util.iterator.FilterIterator.hasNext(FilterIterator.java:54)
at com.hp.hpl.jena.util.iterator.WrappedIterator.hasNext(WrappedIterator.java:90)
at NotarialArchivesTurtle.main(NotarialArchivesTurtle.java:643)
The problem seems to be caused because I am adding a property the same as the one I was searching for ie: family_name
Related
In my use case, I am looping across a map and checking whether a particular key is present in a list. If it is present then I have to trow and exception otherwise continue with the execution.
Map<A,B> myMap = new HashMap<A,B>();
//code to populate values in myMap
...
...
List<A> myList = new ArrayList<A>();
//code to populate values in myList
...
...
for(Map.Entry<A,B> eachElementInMap:myMap.entrySet()){
if(myList.contains(eachElementInMap:myMap.getKey())){
//throwing exception
throw new MyCustomizedException("someString");
}
}
//code continues
...
....
In the above example, if there are 3 elements in the map(myMap) in which 1 key is present in the list(myList), I want to throw the exception for one and it should continue executing other lines of code for the rest two. Am I using a wrong design to achieve this? Any help or suggestion is appreciated! Thanks
Typically once you throw an exception, you are saying that the current line of execution should terminate, rather than continue. If you want to keep executing code, then maybe hold off on throwing an exception.
boolean fail = false;
for (Map.Entry<A,B> eachElementInMap:myMap.entrySet()) {
if (myList.contains(eachElementInMap:myMap.getKey())) {
// throw an exception later
fail = true;
}
}
if (fail) {
throw new MyCustomizedException("someString");
}
You can also create an exception object at a different location from where you throw it. This idiom will be useful in cases where the exception message is not just "someString", but needs to be constructed from data obtained from the object being iterated over.
Optional<MyCustomizedException> exception = Optional.empty();
for (Map.Entry<A, B> eachElementInMap:myMap.entrySet()) {
if (myList.contains(eachElementInMap.getKey())) {
// Create an exception object that describes e.g., the missing key(s)
// but do not throw it yet.
if( exception.isPresent() ) {
exception.get().addToDescription( /* Context-sensitive information */ );
}
else {
exception = Optional.of(
new MyCustomizedException( /* Context-sensitive information */));
}
}
}
if( exception.isPresent() ) {
throw exception.get();
}
If the only data stored in the exception is a string, an equivalent effect can be achieved by accumulating problem descriptions in a StringBuilder, but for cases where more interesting data needs to go into the exception object, building as you go might be an option worth considering.
You can split it into two lists,failList and successList. and do it.
This is clearer
failList = myMap.entrySet().stream().filter(p->myList.contains(p.getKey())).collect(Collectors.toList());
successList = myMap.entrySet().stream().filter(p->!myList.contains(p.getKey())).collect(Collectors.toList());
failList.forEach(p -> {
// fail code
});
successList .forEach(p -> {
// success code
});
why not use if...else instead of try catch ? error just means that's a mistake. if you afraid that makes some mistakes what you don't know. you can use throw error.
anyway, it should not be used when the program is running as you wish
Hi i am writing code for filtering specific data based on the input. if input not available in database it throwing nullpointer exception on the list since i am new in java i dont know how to solve this error
private String isCreditRatingValid(String isin) {
System.out.println(isin);
List<Credit_rating_details> result = Credit.stream()
.filter(i-> i.getIssuer_id()
.contains(isin)).collect(Collectors.toList()); \\throwing NullPointerException on this line\\
if(!result.isEmpty() ) {
validCreditRating = result.get(0).getCredit_rating();
return result.get(0).getCredit_rating();
}else {
return null;
}
As per your comment you are declaring it as
static ArrayList<Credit_rating_details> Credit = null;
which is causing the NPE as you are performing an operation on a null object. Change it to
static ArrayList<Credit_rating_details> Credit = new ArrayList<Credit_rating_details>();
I have the following code
boolean postojaoJePrijelaz = true;
epsilonStanja = sljedecaStanja;
while(postojaoJePrijelaz) {
for (String epsilonStanje : epsilonStanja) {
for (Prijelaz trenutniPrijelaz : prijelazi) {
postojaoJePrijelaz = false;
if (trenutniPrijelaz.postojiPrijelaz(epsilonStanje.trim(), "$")) {
sljedecaStanja.addAll(trenutniPrijelaz.getSkupIzlaznihStanja());
epsilonSljedecaStanja.addAll(trenutniPrijelaz.getSkupIzlaznihStanja());
postojaoJePrijelaz = true;
}
}
}
epsilonStanja = epsilonSljedecaStanja;
epsilonSljedecaStanja.clear();
}
And the compiler gives e ConcurrentModificationException even though i set epsilonStanje=epsilonSljedecaStanja after I already finished my foreach loop. I tried debuggng, but can't seem to fix this.
The program that I'm making is single-threaded
EDIT:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
at java.util.ArrayList$Itr.next(ArrayList.java:831)
at com.company.Main.main(Main.java:55)
epsilonStanja and epsilonStanja both are pointing to the same object as shown below.
epsilonStanja = sljedecaStanja;
for (String epsilonStanje : epsilonStanja) {
...
sljedecaStanja.addAll(trenutniPrijelaz.getSkupIzlaznihStanja());
...
}
you can't add data while iterating.
Solution: create a separate list and finally merge it as per your requirement or try below code:
epsilonStanja.addAll(sljedecaStanja);
you are assigning the reference of list sljedecaStanja to epsilonStanja. This is the issue.. Try
epsilonStanja = new ArrayList<String>(sljedecaStanja);
I have to write logic for detecting what line of code was exception thrown so we can go fix that issue later. The exception object's getStackTrace() gives us a list of stacktrace each with level. I am not interested in getting lowest place where exception was thrown but rather my class method which was responsible in passing parameters.
Here is an example of what i am asking
class Test {
void divide() {
try{
float i = 1/0
}
catch(Exception e){
def v = e.getStackTrace()[0]
println v.getClassName()
}
}
}
This would print class java.math.BigDecimal but i am interested in getting Test class so i can go to it's divide and fix this bug. Now, Test appears in some nth line which i cannot know in run time. One approach would be to iterate stacktrace list and try finding class which is custom developed but how to detect that? Or if there is some library function that already does that it would be great.
Try this:
println e.stackTrace.find {
it.className == 'Test' && it.methodName == 'divide'
}
Or, I guess you want to check all levels of stacktrace, then:
Throwable t = e
StackTraceElement found = null
while (!found && t) {
found = e.stackTrace.find {
it.className == 'Test' && it.methodName == 'divide'
}
t = e.cause
}
println found
I'm trying to build an application in Android using some codes from Objective-C (IPhone app).I'm trying to understand what exactly is doing a piece of code and translate it into Java code,but I think I need a little help here.So first, here is the Obj-C code :
(BOOL)processSqlInjectQueries:(NSArray *)injectQueries error:(NSError**)error {
//some code
for(NSDictionary * q in injectQueries)
{
if (![q isKindOfClass:[NSDictionary class]]) continue;
StPacketInjectQueryPackage qType = (StPacketInjectQueryPackage)[[q objectForKey:#"type"] intValue];
NSString * query = [q objectForKey:#"query"];
}
//some code
}
In Java, I'm trying to do something like this :
// in some other method :
JSONObject jsonData= new JSONObject();
String authHash = jsonData.getJSONObject("client_auth_hash").toString();
List<Map<String,String>> injectQueries= new ArrayList<Map<String,String>>();
injectQueries.add(new HashMap<String, String>());
//injectQueries.add(authHash);
public boolean processSqlInjectQueries(List<Map<String,String>> injectQueries, Exception error){
if(injectQueries==null || injectQueries.size()==0){
boolean injectsProcessed = this.processSqlInjectQueries(injectQueries,error);
if(!injectsProcessed){
return false;
}
}
Log.i("Info","Processing INJECT Queries...");
boolean res = true;
/*[_dbAdapter beginTransaction];
[_user.userDbAdapter beginTransaction];*/
for(Map<String,String> b : injectQueries){
if(b.getClass().getName()!=injectQueries.getClass().getName()){
continue;
}
//RPCPacketInjectQueryPackage qType = (RPCPacketInjectQueryPackage)
}
return true;
}
But my problem is that is that I get this error : Type mismatch: cannot convert from element type Object to ArrayList.
Any suggestion how to fix that error?
And second question : Can I use Exception error in declaraion of processSqlInjectQueries instead of NSError *error in Obj-C?
Iterating over the ArrayList
The error is being raised because your code needs to declare that b is an Object (since injectQueries contains objects of type Object, not objects of type ArrayList):
for(Object b : injectQueries){
...
}
Since the NSDictionary class in Objective-C closely resembles the Map class in Java, you can mimic the Objective-C code by casting b as a Map, or even better, you can use generics to specify that injectQueries contains Map objects. For example:
public boolean processSqlInjectQueries(List<Map<String,String> injectQueries, Exception error) {
// some code
for(Map<String,String> b : injectQueries) {
...
}
// some code
return true;
}
Exception Handling
As for your second question, methods in Java normally communicate error conditions by throwing Exception objects, so your method signature would resemble the following:
public boolean processSqlInjectQueries(List<Map<String,String> injectQueries) throws Exception
Note that it's always better to be specific with your exceptions (i.e. to throw objects that are subclasses of Exception) so that your method caller has some idea of what went wrong. See the following link for additional guidelines for handling exceptions in Java:
http://www.javapractices.com/home/HomeAction.do#Exceptions
The objective C code is passing through an NSArray containing NSDictionaries through to the method, so the following is probably closer to what you want to do...
public boolean processSqlInjectQueries(List<Map<String,String> injectQueries) {
for(Map<String,String> q : injectQueries) {
// do stuff with q
}
}
To handle the error code, you probably want to think about throwing an exception rather than trying to pass through an "Error" object, so something like the following:
public boolean processSqlInjectQueries(List<Map<String,String> injectQueries) throws Exception {
for(Map<String,String> q : injectQueries) {
// do stuff with q
}
if(errorConditionOccurs) {
throw new Exception();
}
}
You'll want to tailor the exact Exception that's thrown so it matches whatever your code is trying to do.
In response to comment: perhaps this is closer to what you're trying to do?
public boolean processSqlInjectQueries(JSONObject jsonObject) {
for(String key : jsonObject.keys()) {
Object value = jsonOnject.get(key);
// Do stuff with value
}
// Do more stuff
}
And you could call it with:
processSqlInjectQueries(jsonData.getJSONObject("client_auth_hash"));