PMD Xpath, how to compare 2 #Image? - xpath

It's is pretty easy to compare one path's #Image to a static string but how to compare 2 paths'#Image ?
Code that should trigger the rule :
public class Foo implements {
public String checkDBConnexion() {
try {
int result = jdbcTemplate.queryForObject("SELECT 1 FROM dual ", Integer.class);
} catch (DataAccessException e) {
// This is Ok : throw new MyException(test, e);
// this is not : hrow new MyException(test);
// This is also not ok if there are no thrown;
return "KO : " + e.getMessage();
}
}
}
Xpath for the param name of the Catch block :
//CatchStatement[//FormalParameter//VariableDeclaratorId]
Xpath for the variable name of the thrown method :
//ThrowStatement//Arguments//Expression//Name
It's easy to compare both to 'e' :
//CatchStatement[//FormalParameter//VariableDeclaratorId[#Image = 'e']]
//CatchStatement[//ThrowStatement//Arguments//Expression//Name[#Image = 'e']]
How do I compare them with eachother ?
Also if you have a link with detailled PMD XPath synthax exemple.
The basic PMD page has ... well the basic ;)

Answering myself :
//CatchStatement[//FormalParameter//VariableDeclaratorId/#Image =
//ThrowStatement//Arguments//Expression//Name/#Image]

Related

org.hibernate.MappingException: Could not locate CollectionPersister for role : com.jbk.Entity.Product.productName

`Whenever, I try to run below method it is giving above error
public static List<Product> productGettingWithSize(int size) {
Session session = factory.openSession();
List<Product> list = null;
try {
Criteria criteria = session.createCriteria(Product.class);
criteria.add(Restrictions.sizeEq("productName", size));
list = criteria.list();
if (list.isEmpty()) {
System.out.println("No Data Found..!!");
} else {
System.out.println(list);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
So, here in this code in DB productName is REDMI so, I m passing 5 as an size but, I m not getting the expected output.
So could anyone help me regarding this code or Can any anyone Tell how to use Restrictions(Size), all method related to size or can anyone send me the documentation where it is been explained explicitly.
Thank You...!!!
Expecting a solution on This..!!`

Is there another way of converting a value entered by a user in an entry without using Convert?.... (Convert.ToDouble or Convert.ToInt)

I am using syncfusion numeric textbox because I want the user to enter double value into the textbox. But when i use the ConvertToDouble or ToInt if it's null then it returns a value of 0. Is there any option I can use for conversion?
//from database
public double rain1vol { get; set; }
[MaxLength(3)]
public double rain2vol { get; set; }
//user entered to database
Post post = new Post()
{
rain1vol = Convert.ToDouble(Sfrain1Entry.Value),
rain2vol = Convert.ToDouble(Sfrain2Entry.Value),
rain2vol = Sfrain2Entry.Value == null ? null : Convert.ToDouble(Sfrain2Entry.Value);
//this is the line i've tried but has error
// no implicit conversion between null and int.
// rain1vol = rain1Entry.Text,
//rain2vol = rain2Entry.Text
};
You can use method String.IsNullOrEmpty() to check the value and try- catch to achieve this .
For example, you can do like this:
var value = Sfrain1Entry.Text;
if (!String.IsNullOrWhiteSpace(value))
{
double result1;
try
{
result1 = Convert.ToDouble(value);
System.Diagnostics.Debug.WriteLine("The input is : " + result1);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Exception: " + ex.Message);
}
}
else if (value.Trim().Length == 0)
{
System.Diagnostics.Debug.WriteLine("The input is IsWhiteSpace...");
}
else {
System.Diagnostics.Debug.WriteLine("The input is invalid...");
}
Note:
You can use method String.IsNullOrWhiteSpace to filter the input data.
After that , you can use method value.Trim().Length == 0 to verify if it is whitespaces.
You can adjust the code according your requirement.

Unchecked call to ifPresent inspection, why? [duplicate]

This question already has answers here:
What is a raw type and why shouldn't we use it?
(16 answers)
Closed 3 years ago.
My code:
public static boolean searchLineOnLogFile(String...keywords)
{
Collection select = null;
try (final Stream<String> lines = Files.lines(get(getServerLog().toString())))
{
select = CollectionUtils.select(lines.collect(Collectors.toCollection(LinkedList::new)),
new Predicate()
{
public boolean evaluate(Object object)
{
String line = (String) object;
return Arrays.stream(keywords).allMatch(line::contains);
}
});
} catch (IOException e)
{
e.printStackTrace();
Assert.fail(e.getMessage());
}
select.stream().findFirst().ifPresent(firstLine -> LogAutomation.info((String)firstLine));
return select.size() > 0;
}
select.stream().findFirst().ifPresent(firstLine -> log.info((String)firstLine));
Why I get 'uncheck call to isPresent' inspection ? how can I improve my code?
full inspection message
from what I 'v read all the idea is to avoid null check:
"So instead of writing something like:
if(optional.isPresent){
doSomething(optional.get);
}
You can write:
optional.ifPresent(val->doSomething(val));
or if you prefer:
optional.ifPresent(this::doSomething);
You can use Optional.ofNullable, as answered by Butiri.
You can also use Objects.requireNonNullElse.
With this second case you can define a default value if is empty.
Example:
public class Main {
public static void main(String[] args) {
Collection<Integer> select = null;
if (Math.random() > 0.5) {
select = Arrays.asList(1, 2, 3);
}
Objects.requireNonNullElse(select, Collections.singletonList(99)).stream().
findFirst().
ifPresent(e -> System.out.println("found: " + e));
}
}
The warning is because the select can be null. Can be fixed by Optional.ofNullable
Optional.ofNullable(select).stream().findFirst().ifPresent(firstLine -> LogAutomation.info((String) firstLine));

StanfordNLP Default Model + Custom NER Model

How can I combine the default model provided by Stanford NLP(english.all.3class.distsim.crf.ser.gz) together with my custom model(ner-model.ser.gz)? I want to recognize Toyota as an 'PERS' entity and the rest of the sentence as the default 'O' entity. It must be recognised as a 'PERS' entity by the engine for later usages (Sentiment/Concept) by the StanfordNLP.
I've already trained the custom model by following the instructions in http://nlp.stanford.edu/software/crf-faq.html#a. I'm using the code as follows for the combination of classifiers:
String serializedClassifier = "ner-model.ser.gz";
String serializedClassifier2 = "edu/stanford/nlp/models/ner/english.all.3class.distsim.crf.ser.gz";
try {
NERClassifierCombiner classifier = new NERClassifierCombiner(false,
false, serializedClassifier, serializedClassifier2);
String ss = "Toyota is not an organisation, it is a person's name.";
System.out.println("---");
List<List<CoreLabel>> out = classifier.classify(ss);
for (List<CoreLabel> sentence : out) {
for (CoreLabel word : sentence) {
System.out.println(word.word() + '('
+ word.get(AnswerAnnotation.class) + ')');
}
System.out.println();
}
} catch (ClassCastException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The result is as follows:
Toyota(PERS)
is(O)
not(PERS)
an(O)
organization(PERS)
,(O)
it(PERS)
is(O)
a(PERS)
person(O)
's(PERS)
name(O)
.(PERS)
If I was to use the default model(ner-model.ser.gz) only, I would get
Toyota(ORGANIZATION)
is(O)
not(O)
an(O)
organization(O)
,(O)
it(O)
is(O)
a(O)
person(O)
's(O)
name(O)
.(O)
Thank you for your help in advance.

Why is my break label erroring?

Hey guys I am trying to break out of a for loop that searches thru all files and breaks once it finds the file. The best thing I have found is the labeling break but its giving an error saying it doesn't exist can you guys take a look and see what I am doing wrong?
import java.nio.file.Files;
import java.nio.file.Paths;
import org.dom4j.Document;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.jaxen.dom4j.*;
public class Load
{
static String info = "";
public static String LoadSum(String projNum)
{
info = "";
try
{
searching:
Files.walk(Paths.get("D:/workspace/Project Program/Projects/")).forEach(filePath ->
{
if(Files.isRegularFile(filePath))
{
try
{
System.out.println("Checking");
SAXReader reader = new SAXReader();
Document document = reader.read(filePath.toFile());
Node node = document.selectSingleNode("//Project/Info/ProjectNumber");
String projectNumber = node.getStringValue();
if(projNum.equals(projectNumber))
{
System.out.println("Found it");
node = document.selectSingleNode("//Project/Info/Name");
info += node.getStringValue() + " : ";
//node = document.selectSingleNode("//Project/Info/Owner");
info += "Owner" + " : ";
node = document.selectSingleNode("//Project/Info/Status");
info += node.getStringValue() + " : ";
break searching; // error here searching doe not exist
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
return info;
}
}
}
The break statement is not into a loop, so you cannot use it.
To forEach statement accepts an Anonymous function that is applied to all the elements found by the Paths.get("D:/workspace/Project Program/Projects/")) statement.
You can stop the operation by throwing an exception, if it's suitable for you.
Source: Java Docs
Edit: considering the fact that what you are passing is an anonymous function you can wrap all the function block with an if statement that depends on a boolean variable defined outside the function: if you find the element you toggle the variable so for the next elements it will be just a no-op. If you wanna know more about Java lambda expressions look here.

Resources