why false if will execute? - java

Here is a code snippet from SAMLSSORelyingPartyObject in WSO2 org.wso2.carbon.hostobjects.sso package.
if (argLength != 1 || !(args[0] instanceof String)) {
String errorMsg = "Invalid argument. SAML response is missing.";
log.error(errorMsg);
throw new ScriptException(errorMsg);
}
when I was debugging this I saw even though this if expression evaluate to false, ScriptException will execute. anyone has explanation for that?
EDIT
The reason was I was debugging in wrong jar in eclipse IDE. server jar version is different was from the jar version I was debugging. even though IDE shows debug was on that line. actually debug was outside of if block

You must be misinterpreting what you saw in debug. If the complete logical expression in the if() evaluates to false, then the code inside the brackets shown will not execute. Perhaps the exception was thrown from elsewhere, or else the complete logical expression actually evaluated to true.

Related

Java - IF statement treats value as NULL even though it isn't when checking in debug

This is a strange one so any help would be appreciated.
I'm working on a Spring Batch job that sends transactions to a Kafka topic and when successful the status code is returned as a String: "C". There's a check for if this status code is null and if so it will give an appropriate error message as below to be outputted onto a table later on.
if (kafkaWriter.getKafkaStatusCode() == null)
{
messagingResultCode = CommonConstants.KAFKA_NULL_RESULT;
}
So what's happening is that for several transactions that are picked up by the job I get a Kafka null result error message because of the above code so I went into debug to see what was happening putting a breakpoint at where messagingResultCode is set.
But when I evaluated "kafkaWriter.getKafkaStatusCode() == null" it showed as "(boolean) false" in Spring Tools Suite. When looking at the KafkaStatusCode it shows as "C" so definitely not null, but it still went into the code anyway.
All getKafkaStatusCode() does is return a String:
public String getKafkaStatusCode() {
return kafkaStatusCode;
}
This only ever happens on the first job that's been run on the server (I'm using Liberty) and on all subsequent runs the code behaves as expected.
I've tried initialising the String messagingResultCode to null, "" and a default value but the same thing happens every time.
Thanks
".or: (time/) asynchronity is in place ;) (I.e. debugging influences the outcome;) – xerx593 3 hours ago"
#xerx593 You were right, the debugger wasn't showing me the correct value which I found after putting in some extra logging and running it in non-debug.
Turns out you can't trust the debugger all the time :)
Thanks

java File.createNewFile throws IOException before rest of program is executed occasionally

I have this project that I'm doing and for whatever reason, whenever I execute the program and put in the given arguments required for it (that I set and all) and occasionally an IOException is thrown before anything else is executed. It seems to be true because I got loggers everywhere and none of them are being fired. However, it seems that just the loggers are not being fired cause when I look in the json file I output to, it shows that it did do the first step of the execution, just no loggers. I'm new to log4j2 so it may be that but I'm not sure (with the loggers not being fired) but it seems weird that an IOException occurs when it shouldn't at all. Cause when I execute it again right after the crash, it runs just fine.
(Side note: this is in kotlin/jvm, but this is pertaining to the use of the JDK File class)
The exception is thrown here: https://github.com/AlexCouch/projauto/blob/master/src/main/java/thinkingcouch/projauto/Save.kt#L114
I'm on MacOSX High Sierra using Intellij IDEA 2017.3.
So what ended up happening was I had this function here for isolating a certain part of the given path to be appended to a new path and also saved to json for later use
fun Path.splitPathWithContext(context: String): File{
val presplit = this.normalize()
logger.info("presplit: $presplit")
logger.info("context: $context")
if(presplit.toString() == context){
logger.info("Path and context are the same.")
return presplit.toFile()
}
val reg = Pattern.compile("\\b$context\\b")
val ret = presplit.toString().split(reg)[1]
logger.info("ret: $ret")
return File(ret)
}
The solution was to do a strict pattern check against the context variable so that it doesn't cut at a word that contains that string but isn't that string exactly, and it needed to be exact. This solved my issue. No more problems, and no more broken paths, and I also fixed my loggers. I don't know exactly what was causing it to not do any logging, but I fixed it by setting the root level to "all" and then removing all my other logger elements since that's all I needed to do.

jsqlparser to evaluate a condition

The following String:
x=92 and y=29
Produces a valid output: x=92 AND y=29 and it works fine with CCJSqlParserUtil.parseCondExpression but shouldn't it throw an exception for the following?
x=92 lasd y=29
But the output is just: x=92
Furthermore which Expression I should use to implement my own visitor? i.e,
CCJSqlParser c= new CCJSqlParser(new StringReader(str));
Expression e = c.Expression(); // or SimpleExpression, etc..
So that when 'lasd' (anything other than not,or,and) is encountered I can throw an exception and not silently ignore the rest of the expression?
Recently a patch of JSqlParser (1.2-SNAPSHOT) was published to provide the needed behaviour:
CCJSqlParserUtil.parseExpression(String expression, boolean allowPartialParse)
and
CCJSqlParserUtil.parseCondExpression(String expression, boolean allowPartialParse)
Setting allowPartialParse to false will result in the mentioned Exception.
For on the fly interpreted stuff the already existing behaviour is still needed, e.g. to provide expressions from within an text. (Syntax coloring, Context help, ...)

IllegalArgumentException: Invalid conditional statement inside expectation block

I have a problem with an Expectations block I have written in my test case:
new Expectations() {
{
mFindHandlerMock.findAll((Model) any, (Set<Id>) any, false);
if (!pWithRealData) {
result = Collections.emptySet();
} else {
result = pAllData;
}
times = 1;
Deencapsulation.invoke(mDb, "readSqlQuery", withAny(String.class));
result = "select * from realdata";
times = 1;
}
};
the test case crashes with:
java.lang.IllegalArgumentException: Invalid conditional statement inside expectation block
exactly here:
if (!pWithRealData) {
it's just a simple boolean that is false in this case.
I have absolutly no clue why the exception happens.
I already searched with google but found nothing helpful.
Could you help me?
From the JMockit release notes for version 1.14:
Enhancement: Conditionals and loops will now trigger an exception when found inside an expectation recording block, to prevent API misuse and to encourage simpler tests. See issue #97.
The GitHub issues related to this:
https://github.com/jmockit/jmockit1/issues/97
https://github.com/jmockit/jmockit1/issues/123
In the one issue they state that:
Yes, and this is as intended, to avoid tests getting too complicated when recording expectations. A full test was not shown, but it looks to me that recording the specific expectations directly would be better in this case.
In the JMockit source you can see which other types of conditionals and loops will throw that exception.
In short, from JMockit 1.14 onwards you are not allowed to have conditionals (such as if statements) and loops in the Expectation block.

Why is the last line of this Java code unreachable

I've been writing a parse for a language and I am getting an unexpected problem in Java. Specifically, the Java compiler says that the return statement at the end of this code is unreachable.
StringBuffer buf = new StringBuffer();
Token tok2;
do {
tok2 = tokenizer.nextToken();
if (tok2 == null) throw new ParseException("Unexected end of file", tok2.endLine, tok2.endColumn);
switch (tok2.type) {
case Token.IDENTIFIER:
case Token.PACKAGE:
buf.append(tok2.token);
default:
throw new ParseException("Illegal character: expected identifier or .", tok.beginColumn, tok.beginLine);
}
} while (tok2.type != Token.SEMI_COLON);
return new PackageElement(buf.toString(), tok.beginLine, tok.beginColumn, tok2.endLine, tok2.endColumn);
tok2.type is an int, and the constants are ints, and the ParseException is a checked exception...
I understand what "unreachable" means and I have written many parses both from scratch and via tools like JavaCC, but I have been looking at this code for hours, and it seems correct to me...
Any help understanding why the return statement is unreachable would be much appreciated!
Your cases are missing breaks, which means each case falls through. That means that one of two things will happen:
if tok2 == null, an exception is thrown
otherwise, the switch block is triggered. Whether or not either case is hit, flow falls through to the default case, and an exception is thrown
In either case, the first run through the do block is guaranteed to throw an exception, and thus anything following it is unreachable.
Solution: add break statements, like this:
case Token.PACKAGE:
buf.append(tok2.token);
break; // <--- here
default:
// etc
Once you reach the semi colon token, the default case is hit and an exception thrown. This is the only exit from the loop.
You do not have a break statement anywhere, which means that the default statement is going to get executed - resulting in an Exception being thrown for certain no matter what. HEnce the return statement will never be hit.

Categories