Java object declaration following return;? - java

I came across some unfamiliar Java syntax while looking at some code from jstl 1.1.2. It occurs to me the code I'm looking at was reverse compiled by Beyond Compare (or a plug-in thereof), so that might have something to do with it.
The code at the end of the method looks like this:
...
p.parse(page.getInputStream(), h);
if(failed)
return vmFromString("taglib " + prefix + " (" + uri + ") allows only the " +
"following taglibs to be imported: " + permittedTaglibs);
return null;
SaxException ex;
ex;
return vmFromString(ex.toString());
ex;
return vmFromString(ex.toString());
ex;
return vmFromString(ex.toString());
}
In jstl 1.1, before they refactored the PermittedTaglibsHandler, it looks like this:
...
saxparser.parse(pagedata.getInputStream(), permittedtaglibshandler);
if(failed)
return vmFromString("taglib " + s+ " (" + s1+ ") allows only the " +
"following taglibs to be imported: " + permittedTaglibs);
return null;
Object obj;
obj;
return vmFromString(((SaxException) (obj)).toString());
obj;
return vmFromString(((ParserConfigurationException) (obj)).toString());
obj;
return vmFromString(((IOException) (obj)).toString());
}
Is this odd syntax just an artifact of the reverse compile, or is there such a thing as meaningful code that follows a return statement?
Thanks,
Rebeccah

The code is just the exception handler loop customized to handle multiple exceptions - thus the multiple return statements. Its obviously not been translated correctly into Java.

Related

How can I write this expression more compactly in Java 8?

How can I write that if more compact using java 8?
Optional.ofNullable(city).ifPresent(c -> {
if (!city.equalsIgnoreCase(district)) {
address.setCity(district + ", " + c);
}
});
As Eran commented, you can avoid the spurious detour over Optional by just directly checking for null:
if (city != null && !district.equalsIgnoreCase(city)) {
address.setCity(district + ", " + city);
}

Ternary operator for Bigdecimal null validation

Why am I getting null pointer exception in this code?
BigDecimal test = null;
String data = "";
try {
System.out.println(test==null?"":test.toString());
data = test==null?"":test.toString();
System.out.println(data);
data = data + " " + test==null?"":test.toString(); // catching null pointer in this line
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
It's evaluating the expressions as:
data = (data + " " + test==null)?"":test.toString();
so, since data + " " + test is not null, it attempts to call test.toString() even when test is null.
Change
data = data + " " + test==null?"":test.toString();
to
data = data + " " + (test==null?"":test.toString());
Since Java 8 there is also an alternative way to deal with potential null references: Optional
To prevent an NPE while converting a BigDecimal to a String you can use an Optional like that:
String data = Optional.ofNullable(test).map(BigDecimal::toString).orElse("");
This way you don't need to check test several times if it is null. Having test once wrapped in an Optional you could work on being safe, that any conversion (map) will be performed only if test is not referencing null.

Including function code snippet form a groovy file in JMeter groovy script

I have a big Groovy script in JMeter and I want few methods to be re-used in different places of my script. Below is what I tried.
This is a groovy script where I have written a function that I want to call from Jmeter.
Tools.groovy
public void AssertValuesF(float Expected, float Actual, String PassMessage, String FailureMessage){
if(Expected==Actual){
log.info("****Assertion Successful****");
log.info("Actual: "+Actual+" Expected: "+Expected +"\n");
log.info(PassMessage);
}
else{
vars.put("AssertionFailure","true");
AssertionResult.setFailure(true);
vars.put("FailureMsg",vars.get("FailureMsg") + "\n****ASSERTION FAILURE****** \n"+FailureMessage + " || EXPECTED: "+ Expected + " || ACTUAL: "+Actual + "\n");
log.info("****ASSERTION FAILURE******");
// AssertionResult.setFailureMessage("****Assertion Failure****** "+FailureMessage + " Expected: "+ Expected + " Actual: "+Actual+"\n");
log.info(FailureMessage);
log.info("Actual: "+Actual+"Expected: "+Expected);
}
}
Below is my JMeter Groovy code where I am calling the function.
File sourceFile = new File("D://TestScript//Tools.groovy");
Class groovyClass = new GroovyClassLoader(getClass().getClassLoader()).parseClass(sourceFile);
GroovyObject myObject = (GroovyObject) groovyClass.newInstance();
myObject.AssertValues("s","s","asdf","asdf");
The output gives this error, javax.script.ScriptException: groovy.lang.MissingPropertyException: No such property: log for class: Tools
This is probably because of 'log' object not available from Groovy. How can I solve this issue?
log shorthand is available only for JSR223 Elements, in order to be able to use it you need to define it manually like it's done in JSR223TestElement class
So amend your code to look like:
import org.slf4j.Logger
import org.slf4j.LoggerFactory
public void AssertValuesF(float Expected, float Actual, String PassMessage, String FailureMessage) {
final Logger log = LoggerFactory.getLogger(getClass());
if (Expected == Actual) {
log.info("****Assertion Successful****");
log.info("Actual: " + Actual + " Expected: " + Expected + "\n");
log.info(PassMessage);
} else {
vars.put("AssertionFailure", "true");
AssertionResult.setFailure(true);
vars.put("FailureMsg", vars.get("FailureMsg") + "\n****ASSERTION FAILURE****** \n" + FailureMessage + " || EXPECTED: " + Expected + " || ACTUAL: " + Actual + "\n");
log.info("****ASSERTION FAILURE******");
// AssertionResult.setFailureMessage("****Assertion Failure****** "+FailureMessage + " Expected: "+ Expected + " Actual: "+Actual+"\n");
log.info(FailureMessage);
log.info("Actual: " + Actual + "Expected: " + Expected);
}
}
And you will be able to use it from Groovy scripts your way:
Also be aware that there is groovy.utilities property which can be used to re-use your custom scripts in __groovy() function, you will need either add the next line to user.properties file:
groovy.utilities=D:/TestScript/Tools.groovy
or pass it via -J command-line argument like:
jmeter -Jgroovy.utilities=D:/TestScript/Tools.groovy -n -t test.jmx -l result.jtl
References:
Configuring JMeter
Overriding Properties Via The Command Line
Apache JMeter Properties Customization Guide

Building Hibernate query depending of parameters that can be nulls

so i am working on a project right now
1st time using Hibernate
in this projet i am using Swing too
i have a form with multiple jTextFields
public List<Object[]> getoperations(String a,String c,String n,String e,String d) {
SessionDao s=new SessionDao();
session=s.getSession();
Query q;
q=session.createQuery("select idTiers,beneficiaire,emetteur,montant,numcompte,t_param_nature_operation.libelleNature,dateValidite,dateCreation where");
if (a != null && !a.isEmpty()) { q+= " and codeBanque='" + a + "'"; }
if (c != null && !c.isEmpty()) { q += " and numCompte='" + c + "'"; }
if (n != null && !n.isEmpty()) { q += " and t_param_nature_operation_.libelleNature='" + n + "'"; }
if (e != null && !e.isEmpty()) { q += " and decision='" + e + "'"; }
if (d != null && !d.isEmpty()) { q += " and dateCreation='" + d + "'"; }
q+= " order by idTiers" ;
return q.list();
}
As you see I am making a test on the values to add them in the query.
My question is there a way to add those values?
since query +="" isn't working.
Personally, I would add Guava utils to my project and use isNotBlank()
function. Anyway, you can write your own static function that would
return true if not null and not empty and false otherwise, and later
use it. It'll make your code much clearer.
The above was my comment and I decided to show you this little piece of code.
public static boolean isBlank(String s) {
if (s == null)
return true;
if (s.isEmpty())
return true;
return false;
}
Now you can simply write:
//static import your isBlank() method
//import static package.classInWhichIsBlankIsDeclared;
if (!isBlank(a) { q+= " and codeBanque='" + a + "'"; }
if (!isBlank(b) { q+= " and codeBanque='" + b + "'"; }
if (!isBlank(c) { q+= " and codeBanque='" + c + "'"; }
if (!isBlank(d) { q+= " and codeBanque='" + d + "'"; }
It's much more readable so it'll be much easier to debug in case of errors in the future.
Please, have a look at DRY principle and follow it. If your issue require checking same condition 4 or 5 times (2 times should be enough to use DRY) consider writing a function. call it the way that it'll be human-friendly instead of combination of different logical statements.
DRY. Don't Repeat Yourself.
"Every piece of knowledge must have a single, unambiguous, authoritative representation within a system"
Wikipedia article about DRY
you should consider using Criteria. it's more clean when dealing with multiple where statements.
eg
Criteria cr = session.createCriteria(YourEntityClass.class);
cr.add(Restrictions.eq("property1", value1));
cr.add(Restrictions.eq("property2", value2));
List results = cr.list();
have a look at these examples here

How to disable pretty-printing in Groovy MarkupBuilder?

I have a string input in my Mule flow. It passes through my Groovy Script and outputs XML. I originaly had the script followed by an XSLT converter to remove empty nodes and set the indent to "no" in the output tag. But now I removed it as I cannot use it in conjunction with my script if I want to keep the special characters (see previous question here).
Instead I now check each value before printing the nodes. But the problem I have is my XML needs to be unindented in order to work with my InDesign project I adapt the XML for. I lost that ability when I removed the XSLT so I fixed one problem but created another.
I found the method getPrinter(), I used it with the setAutoIndent(false) but it didn't change anything to the output and created no errors. Not to sure where to use it.
Here's my script :
public Boolean isEmpty(value){
if(value.toString().trim() == "" || value.toString().trim() == '' || value == null)
return true;
}
root = new XmlSlurper(false,false).parseText(payload)
if(root.name() == 'GetActivitiesResponse')
startEach = root.children().children()
else
startEach = root.children()
def xml = new StringWriter().with { w -> new groovy.xml.MarkupBuilder(w).with {
mkp.xmlDeclaration(version: "1.0", encoding: "utf-8")
escapeAttributes = false
getPrinter().setAutoIndent(false);
"w_import_saisie_web"() {
startEach.each { p -> "w_evenement"() {
if(!isEmpty(p.PresentationDate))
"w_dates"{ mkp.yieldUnescaped (p.PresentationDate.toString() + "
") }
if(!isEmpty(p.SubTitle))
"w_contexte"{ mkp.yieldUnescaped (p.SubTitle.toString() + "
") }
//if(!isEmpty(p.SubTitle))
"w_nom_evenement"{ /*p.GEVT_Type*/ mkp.yieldUnescaped ("Nom evenement" + "
") }
if(!isEmpty(p.Name))
"w_titre"{ mkp.yieldUnescaped (p.Name.toString() + "
")}
if(!isEmpty(p.ShortDescription) || !isEmpty(p.Teaser))
"w_texte"{mkp.yieldUnescaped (p.ShortDescription.toString() + p.Teaser.toString() + "
")}
p.SubEvents.children().each { q -> "w_bloc_sous_evenement"() {
if(!isEmpty(q.PresentationDate) || !isEmpty(q.Name))
"w_sous_eve_titre"{ mkp.yieldUnescaped (q.PresentationDate.toString() + q.Name.toString() + "
")}
if(!isEmpty(q.ShortDescription) || !isEmpty(q.Teaser) || !isEmpty(q.WebDescription))
"w_sous_eve_desc"{mkp.yieldUnescaped (q.ShortDescription.toString() + q.Teaser.toString() + q.WebDescription.toString() + "
")}
}
}
if(!isEmpty(p.Site) || !isEmpty(p.PresentationHours))
"w_coordonnees"{ mkp.yieldUnescaped ("teeeessdfsdfsdfst" + p.Site.toString() + ' - ' + p.PresentationHours.toString() + "
")}
}
}
}
}
w.toString()
}
Add an IndentPrinter when you create the MarkupBuilder.
def xml = new MarkupBuilder(new IndentPrinter(new PrintWriter(writer), "", true))
See this question:
groovy.xml.MarkupBuilder disable PrettyPrint
I tried a bunch of different things to see if setAutoIndent was effective (setting it before passing the IndentPrinter to the MarkupBuilder for example) and it didn't seem to have any effect. So, like you, I'm wondering about its purpose.
Realised I was searching too hard... just added this simple line to the toString() at the end...
w.toString().replaceAll(">\\s+<", "><").trim();

Categories

Resources