Unchecked call to ifPresent inspection, why? [duplicate] - java-8

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));

Related

SonarQube showing Cognitive Complexity error Even there is only 7 loops

I am review my code using SonarQube. I am receiving the following issue.
Refactor this method to reduce its Cognitive Complexity from 21 to the 15 allowed.
But my method contains only 7 loops. Herewith I attached the code.
private void LayoutTouch(int touchType, int index) {
if (touchType != -1) { //+1
try {
ViewConfiguration vc = ViewConfiguration.get(ctContext);
mSlop = vc.getScaledTouchSlop();
parentLayout[index]
.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v,
MotionEvent event) {
if(!isValidEvent()){ //+2
return false;
}
if(checkTouchIndex(index)){ //+3
try{
// Code here
if (animationStarted) { //+4
return false;
}
final ViewConfiguration vc = ViewConfiguration
.get(getContext());
final int deltaX = (int) (event.getX() + 0.5f)
- mGestureCurrentX;
initiateVelocityTracker();
mVelocityTracker.addMovement(event);
mVelocityTracker
.computeCurrentVelocity(1000);
if(!doSwitchAndNeedToReturn(v, event, index, vc, deltaX)) // +5
return false;
}catch(Exception e){ //+6
setTouchProgressIndex(-1);
}finally{
setTouchProgressIndex(-1);
}
}
return false;
}
});
} catch (Exception e) { //+7
Log.e("Testing","Exception "+ e);
}
}
}
Why I am getting this issue. Please help me on this.
I agree with SonarQube that the code is overly complex.
Simplifications possible:
combine if statements
use a lambda
(not done here) use an extra method for the lambda code
So:
private void LayoutTouch(int touchType, int index) {
if (touchType != -1) { //+1
try {
ViewConfiguration vc = ViewConfiguration.get(ctContext);
mSlop = vc.getScaledTouchSlop();
parentLayout[index]
.setOnTouchListener((v, event) -> {
if (isValidEvent() && checkTouchIndex(index)) {
try{
// Code here
if (animationStarted) { //+4
return false;
}
final ViewConfiguration vc = ViewConfiguration
.get(getContext());
final int deltaX = (int) (event.getX() + 0.5f)
- mGestureCurrentX;
initiateVelocityTracker();
mVelocityTracker.addMovement(event);
mVelocityTracker
.computeCurrentVelocity(1000);
if (!doSwitchAndNeedToReturn(v, event, index, vc, deltaX)) // +5
return false;
} catch(Exception e) { //+6
setTouchProgressIndex(-1);
} finally {
setTouchProgressIndex(-1);
}
}
return false;
});
} catch (Exception e) { //+7
Log.e("Testing","Exception "+ e);
}
}
}
The extra method:
.setOnTouchListener(this::onTouch);
private boolean onTouch(View v, MotionEvent event) {
...
}
The checked exception handling is very unspecific. If not a specific exception can happen, maybe drop it (at the end).
Using member variables named with the prefix m, is not conventional in java. These variables indeed seem many, but with mouse, touch and so that might make sense.
I mention this, as the calculations seem refactorable.
But my method contains only 7 loops
Sonar is telling you that the method is hard to understand (cognitive complexity). And I do agree with the criteria. The complexity does not grow linearly and that is why it goes +1, +2, +3, +4 +5 +6 +7 = 28 > 21.
As a developer I would really want this piece of code cleaned up. Here are some suggestions:
Extract the OnTouchListener into a class (inner or not)
Change the initial check as a guard condition with an early return.
Review why are you doing the same thing in finally and the exception. setTouchProgressIndex(-1)

Pagination and Sorting - custom sorting of data

I have a problem with sorting data in my project.
Since I implemented pagination I don't know how solve this issue.
Before pagination I fetched whole list of entities and sort it by this class:
public class EntitySorter {
private static final Logger LOG = Logger.getLogger(EntitySorter.class);
public static int sort(String s1, String s2) {
if (StringUtils.isBlank(s1) || StringUtils.isBlank(s2)) {
return -1;
}
if (!s1.contains("/") || !s2.contains("/")) {
return -1;
}
if (s1.substring(s1.lastIndexOf("/") + 1).length() != 4 ||
s2.substring(s2.lastIndexOf("/") + 1).length() != 4) {
return -1;
}
final String year1 = s1.substring(s1.lastIndexOf("/") + 1);
final String year2 = s2.substring(s2.lastIndexOf("/") + 1);
if (!NumberUtils.isDigits(year1) || !NumberUtils.isDigits(year2)) {
return -1;
}
final int result = NumberUtils.toInt(year1) - NumberUtils.toInt(year2);
if (result != 0) {
return result;
}
final String caseNumber1 = s1.substring(0, s1.indexOf("/"));
final String caseNumber2 = s2.substring(0, s2.indexOf("/"));
if (!NumberUtils.isDigits(caseNumber1) && NumberUtils.isDigits(caseNumber2)) {
try {
final int intCaseNumber1 = Integer.parseInt(caseNumber1.replaceAll("[^0-9]", ""));
return intCaseNumber1 - Integer.parseInt(caseNumber2);
} catch (NumberFormatException e) {
LOG.error(e.getMessage(), e);
}
return -1;
}
if (NumberUtils.isDigits(caseNumber1) && !NumberUtils.isDigits(caseNumber2)) {
try {
final int intCaseNumber2 = Integer.parseInt(caseNumber2.replaceAll("[^0-9]", ""));
return Integer.parseInt(caseNumber1) - intCaseNumber2;
} catch (NumberFormatException e) {
LOG.error(e.getMessage(), e);
}
return -1;
}
if (!NumberUtils.isDigits(caseNumber1) && !NumberUtils.isDigits(caseNumber2)) {
try {
final int intCaseNumber1 = Integer.parseInt(caseNumber1.replaceAll("[^0-9]", ""));
final int intCaseNumber2 = Integer.parseInt(caseNumber2.replaceAll("[^0-9]", ""));
return intCaseNumber1 - intCaseNumber2;
} catch (NumberFormatException e) {
LOG.error(e.getMessage(), e);
}
return -1;
}
return NumberUtils.toInt(caseNumber1) - NumberUtils.toInt(caseNumber2);
}
}
Let's take some example:
We have a list of IDs:
101/2021
102/2021
1/2022
86/2020
Correct sorted list is:
1/2022
102/2021
101/2021
86/2020
In database this ID is one column. It's not split to number and year. I tried to use Sort.by() but I didn't make a success. How can I use pagination and keep correct sorting?
For pagination to work optimally, the data should be indexed correctly..
If there is a different representation of the data you can use with one column then it's the best way.
If not then the easy way would just to decompose one column to multiple columns, create a multi column index and sort by these columns + you need to understand if the natural ordering of the columns fits your logic.
The hard way would be to create user defined function and index on it and other solutions, but I would avoid the unnecessary complexity.
Keep it simple!

Java 8 stream short circuit manually [duplicate]

This question already has answers here:
Limit a stream by a predicate
(19 answers)
Closed 6 years ago.
Is there any way to manually short circuit a stream (like in findFirst)?
Example:
Imagine a huge dictionary ordered by word size and alphabet:
cat
... (many more)
lamp
mountain
... (many more)
Only ready and compute the file from beginning, return immediately when line size exceeds 4:
read cat, compute cat
...
read tree, compute lamp
read mountain, return
The following code is very concise but does not take into advantage the order of the stream, it has to ready every line:
try (Stream<String> lines = Files.lines(Paths.get(DICTIONARY_PATH))) {
return lines
// filter for words with the correct size
.filter(line -> line.length() == 4)
// do stuff...
.collect(Collectors.toList());
}
Answer based on Limit a stream by a predicate, processing correctly stops when predicate returns false. Hopefully this method comes available in Java 9:
private static List<String> getPossibleAnswers(int numberOfChars, char[][] possibleChars) throws IOException {
try (Stream<String> lines = Files.lines(Paths.get(DICTIONARY_PATH)) {
return takeWhile(lines, line -> line.length() <= numberOfChars)
// filter length
.filter(line -> line.length() == numberOfChars)
// do stuff
.collect(Collectors.toList());
}
}
static <T> Spliterator<T> takeWhile(Spliterator<T> splitr, Predicate<? super T> predicate) {
return new Spliterators.AbstractSpliterator<T>(splitr.estimateSize(), 0) { boolean stillGoing = true;
#Override
public boolean tryAdvance(Consumer<? super T> consumer) {
if (stillGoing) {
boolean hadNext = splitr.tryAdvance(elem -> {
if (predicate.test(elem)) {
consumer.accept(elem);
} else {
stillGoing = false;
}
});
return hadNext && stillGoing;
}
return false;
}
};
}
static <T> Stream<T> takeWhile(Stream<T> stream, Predicate<? super T> predicate) {
return StreamSupport.stream(takeWhile(stream.spliterator(), predicate), false);
}

getting slower performance in textBox1_TextChanged in windows phone

I have a search text-box in my app. In my database there are two column named English and Bangla. I can search either Bangla or English. there is a button beside search text-box.By default English search is activated. I can change the search option by clicking the button. It works correctly but problem is that the search is very slow.
search option selection code by clicking button is:
private void button5_Click(object sender, RoutedEventArgs e)
{
if (SearchMood % 2 != 0)
{
//search bangla column from the database
button5.Content = "Eng";
}
else {
//search english column from the database
button5.Content = "Bng";
}
SearchMood++;
}
Code for searching is:
private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
{
List<dataLists> mylist = new List<dataLists>();
string word = textBox1.Text;
try
{
if (SearchMood % 2 == 0)// for english search
{
// show 5 words in listbox matched with entered text
var contacts = (from m in db.Dics where m.English.StartsWith(word) select new { m.English, m.Bangla }).Take(5);
string s1, s2;
try
{
foreach (var a in contacts)
{
s1 = a.English;
s2 = a.Bangla;
mylist.Add(new dataLists() { Eng = s1, Bng = s2 });
}
}
catch (Exception ex) { MessageBox.Show(ex.ToString()); }
listBox1.ItemsSource = mylist;
}
else // for bangla search
{
// show 5 words in listbox matched with entered text
var contacts = (from m in db.Dics where m.Bangla.StartsWith(word) select new { m.English, m.Bangla }).Take(5);
string s1, s2;
try
{
foreach (var a in contacts)
{
s1 = a.English;
s2 = a.Bangla;
mylist.Add(new dataLists() { Eng = s1, Bng = s2 });
}
}
catch (Exception ex) { MessageBox.Show(ex.ToString()); }
listBox1.ItemsSource = mylist;
}
}
catch { }
}
How can I increase the performance of searching??? Can anyone give any solution|???
N:B: My table creation script looks like
public System.Data.Linq.Table<Dic> Dics
{
get
{
return this.GetTable<Dic>();
}
}
public System.Data.Linq.Table<Learn_table> Learn_tables
{
get
{
return this.GetTable<Learn_table>();
}
}
}
[global::System.Data.Linq.Mapping.TableAttribute(Name="dic")]
public partial class Dic : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private int _Serial;
private string _English;
private string _Bangla;
private System.Nullable<int> _Fav;
#region Extensibility Method Definitions
partial void OnLoaded();
partial void OnValidate(System.Data.Linq.ChangeAction action);
partial void OnCreated();
partial void OnSerialChanging(int value);
partial void OnSerialChanged();
partial void OnEnglishChanging(string value);
partial void OnEnglishChanged();
partial void OnBanglaChanging(string value);
partial void OnBanglaChanged();
partial void OnFavChanging(System.Nullable<int> value);
partial void OnFavChanged();
#endregion
public Dic()
{
OnCreated();
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Name="serial", Storage="_Serial", AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
public int Serial
{
get
{
return this._Serial;
}
set
{
if ((this._Serial != value))
{
this.OnSerialChanging(value);
this.SendPropertyChanging();
this._Serial = value;
this.SendPropertyChanged("Serial");
this.OnSerialChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Name="english", Storage="_English", DbType="NVarChar(2000)")]
public string English
{
get
{
return this._English;
}
set
{
if ((this._English != value))
{
this.OnEnglishChanging(value);
this.SendPropertyChanging();
this._English = value;
this.SendPropertyChanged("English");
this.OnEnglishChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Name="bangla", Storage="_Bangla", DbType="NVarChar(2000)")]
public string Bangla
{
get
{
return this._Bangla;
}
set
{
if ((this._Bangla != value))
{
this.OnBanglaChanging(value);
this.SendPropertyChanging();
this._Bangla = value;
this.SendPropertyChanged("Bangla");
this.OnBanglaChanged();
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Name="fav", Storage="_Fav", DbType="Int")]
public System.Nullable<int> Fav
{
get
{
return this._Fav;
}
set
{
if ((this._Fav != value))
{
this.OnFavChanging(value);
this.SendPropertyChanging();
this._Fav = value;
this.SendPropertyChanged("Fav");
this.OnFavChanged();
}
}
}
public event PropertyChangingEventHandler PropertyChanging;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void SendPropertyChanging()
{
if ((this.PropertyChanging != null))
{
this.PropertyChanging(this, emptyChangingEventArgs);
}
}
protected virtual void SendPropertyChanged(String propertyName)
{
if ((this.PropertyChanged != null))
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Your problem appears in using TextChanged event Handler. Place a breakpoint there and you will see it firing twice and hence causing the slow performance for you. It seems a bug in WP7 TextBox control.
Use KeyUp event handler, instead of textBox1_TextChanged
void textBox1_KeyUp(object sender, KeyEventArgs e)
{
//your code
}
Hope this solves your problem. !!
You can use of AutoCompleteBox rather than use of TextBox. AutoCompleteBox available in Microsoft.Phone.Control.Toolkit.
Execute you select query at once when you select language on buttonClick and assign result of your query to AutoCompleteBox.Itemsource. It should really increase search performance.
<toolkit:AutoCompleteBox x:Name="AutoBoxFood" Width="440" SelectionChanged="txtFodd_SelectionChanged" FilterMode="StartsWith" HorizontalAlignment="Left" Height="70"/>
Add indexes to the columns in the database file.

C3P0 Statement.close deadlock

Google returns lots of people with deadlock issues in C3P0, but none of the solutions appear to apply (most people suggest setting maxStatements = 0 and maxStatementsPerConnection = 0, both of which we have).
I am using a ComboPooledDataSource from C3P0, initialised as;
cpds = new ComboPooledDataSource();
cpds.setDriverClass("org.postgresql.Driver");
cpds.setJdbcUrl("jdbc:postgresql://" + host + ":5432/" + database);
cpds.setUser(user);
cpds.setPassword(pass);
My query function looks like;
public static List<Map<String, Object>> query(String q) {
Connection c = null;
Statement s = null;
ResultSet r = null;
try {
c = cpds.getConnection();
s = c.createStatement();
s.executeQuery(q);
r = s.getResultSet();
/* parse result set into results List<Map> */
return results;
}
catch(Exception e) { MyUtils.logException(e); }
finally {
closeQuietly(r);
closeQuietly(s);
closeQuietly(c);
}
return null;
}
No queries are returning, despite the query() method reaching the return results; line. The issue is that the finally block is hanging. I have determined that the closeQuietly(s); is the line that is hanging indefinitely.
The closeQuietly() method in question is as you would expect;
public static void closeQuietly(Statement s) {
try { if(s != null) s.close(); }
catch(Exception e) { MyUtils.logException(e); }
}
Why would this method hang on s.close()? I guess it is something to do with the way I am using C3P0.
My complete C3P0 configuration (almost entirely defaults) can be viewed here -> http://pastebin.com/K8XDdiBg
MyUtils.logException(); looks something like;
public static void logException(Exception e) {
StackTraceElement ste[] = e.getStackTrace();
String message = " !ERROR!: ";
for(int i = 0; i < ste.length; i++) {
if(ste[i].getClassName().contains("packagename")) {
message += String.format("%s at %s:%d", e.toString(), ste[i].getFileName(), ste[i].getLineNumber());
break;
}
}
System.err.println(message);
}
Everything runs smoothly if I remove the closeQuietly(s); line. Both closing the ResultSet and Connection object work without problem - apart from Connection starvation of course.

Resources