Indent lambda function body in Intellij - java

I have this example code that I want to pass some checkstyle rules but my formatter is not properly set up.
I just want an extra indent to lambda function body and change location of its right bracket }
This is what my code looks currently when I format it (Ctrl + Alt + L)
Optional.ofNullable(customerClient.
getActiveCustomers()).map(customer -> {
String firstName = customer.getFirstName();
String lastName = customer.getLastName();
return firstName + " " + lastName;
}).orElse(null);
but I need to change my formatter so that the code would look like this:
Optional.ofNullable(customerClient.
getActiveCustomers()).map(customer -> {
String firstName = customer.getFirstName();
String lastName = customer.getLastName();
return firstName + " " + lastName;
}
).orElse(null);

It's a known issue. Feel free to vote.

Related

Specific query in java spring called from rest controller

I'm trying to filter a table called Measure through its field customerId. This is what the beginning of the controller for the path looks like:
#RequestMapping(method = GET, path = "/nodes/{id}/ports/{portid}/measures")
#ResponseBody
public ResponseEntity<?> getPortMeasures(#PathVariable long id, #PathVariable long portid,
#RequestParam Optional<Long> from,
#RequestParam Optional<String> order,
#RequestParam Optional<String> countername,
#RequestParam Optional<Long> to) {
Followed by the method that calls the query undernath
if (order.isPresent() && order.get().equals("asc")) {
return ResponseRestBuilder.createSuccessResponse(
measureRepository.
searchAsc
(networkElementList.get(0).ip, portList.get(0).rack, portList.get(0).frame, portList.get(0).slot,
portList.get(0).portSerial, countername.get(), from.orElse(0L), to.orElse(99999999999999999L)));
}
else{
return ResponseRestBuilder.createSuccessResponse(
measureRepository.
searchDesc
(networkElementList.get(0).ip, portList.get(0).rack, portList.get(0).frame, portList.get(0).slot,
portList.get(0).portSerial, countername.get(), from.orElse(0L), to.orElse(99999999999999999L)));
}
This is what the queries look like:
#Query("SELECT mes FROM Measure mes WHERE " +
"mes.nodeIp = (:nodeIp) AND " +
"mes.rack = (:rack) AND " +
"mes.frame = (:frame) AND " +
"mes.slot = (:slot) AND " +
"mes.portSerial = (:portSerial) AND " +
"lower(mes.counterName) LIKE concat('%', lower(:countername), '%') AND"+
"mes.timestamp > (:timestamp1) AND " +
"mes.timestamp < (:timestamp2) "+
"ORDER BY mes.timestamp DESC")
List<Measure> searchDesc(#Param("nodeIp") String nodeIp, #Param("rack") String rack, #Param("frame") String frame,
#Param("slot") String slot, #Param("portSerial") String portSerial, #Param("countername") String countername,
#Param("timestamp1") Long timestamp1, #Param("timestamp2") Long timestamp2);
#Query("SELECT mes FROM Measure mes WHERE " +
"mes.nodeIp = :nodeIp AND " +
"mes.rack = :rack AND " +
"mes.frame = :frame AND " +
"mes.slot = :slot AND " +
"mes.portSerial = :portSerial AND " +
"lower(mes.counterName) LIKE concat('%', lower(:countername), '%') AND " +
"mes.timestamp > :timestamp1 AND " +
"mes.timestamp < :timestamp2 "+
"ORDER BY mes.timestamp ASC")
List<Measure> searchAsc(#Param("nodeIp") String nodeIp, #Param("rack") String rack, #Param("frame") String frame,
#Param("slot") String slot, #Param("portSerial") String portSerial, #Param("countername") String countername,
#Param("timestamp1") Long timestamp1, #Param("timestamp2") Long timestamp2);
It's not filtering anything because the controller replies with 0 rows. I'm 100% confident there are actual rows because I've checked with other rest calls. What am I doing wrong?
EDIT: debug
Most probably the issue is with the timestamp field ,it seems from the code that you are passing a long, but actually it's waiting for a timestamp literal , timestamp literal in jpa is in the format {ts '2009-11-05 12-45-52.325'} ... just to check , try removing the timestamp from the query then put it again and provide the literals manually ... if it works, you then need to find a way to parse the passed long to the corresponding literal
The problem with it was the field portList.get(0).rack being "null". Appartently this made the whole query not work.

Derived Attribute/Property in Java?

I am new to Java - I am trying to understand how to use a "derived" "attribute" in a class. My understanding is that this is basically the same as the typical "full name" use case using a getter in C#, but I want to make sure. In C#, I would write.
public string fullName
{
get {return this.fName + " " + this.lName;}
}
and then call it like this:
Dude homieG = new Dude()
{
fName = "Homie",
lName = "G"
};
Console.WriteLine(homieG.fullName);
https://dotnetfiddle.net/0ppd8j
How do I do this in Java? Googling "derived attribute (or 'property') java" gives me nothing.
Create a method. There are no "properties" in java.
public String getFullBlammy()
{
return firstName + " " + lastName;
}

Split String using split method

I have one String text that i would like to split,result i want to get is that when i take text/split output each part like for example: Name: John, Last Name: Davidson, Date of Birth: 05051968, Place of Birth: London. But i am not getting correct result. my code is following:
public class Person{
public String name;
public String lastName;
public String dateOfBirth;
public String placeOfBirth;
poblic void printDetails(){
String text = "John.Davidson/0505168/London Micheal.Bartson/06061680/Paris";
String[] newText = text.split("[./ ]");
for(int i=0; i<newText.length; i++){
String name = newText[i].split("")[0];
String lastName = newText[i].split("")[0];
String dateOfBirth = newText[i].split("")[0];
String placeOfBirth = newText[i].split("")[0];
System.out.println("Name: " + name + ", last name: " + lastName + ", date of birth: " + dateOfBirth + ", place of birth: " + placeOfBirth);
}
Result i am getting is following:
Name: J, last Name: J, date of birth: J, place of birth: J
Name: D, last name: D, date of birth: D, place of birth: D .......
and it goes like that for every first character in text. Please can some one look and tell me where i am mistaking?
The results of the split come in groups of four, so you need to set the step of your loop at 4, and get the individual parts through offsets 0, 1, 2, and 3, like this:
for(int i=0; i<newText.length; i+=4){
String name = newText[i];
String lastName = newText[i+1];
String dateOfBirth = newText[i+2];
String placeOfBirth = newText[i+3];
System.out.println("Name: " + name + ", last name: " + lastName + ", date of birth: " + dateOfBirth + ", place of birth: " + placeOfBirth);
}
Demo.
You're splitting using the "" which means split every character. Then you take the first character. I don't know why you're doing it that way.
In summary, what happens in every loop is it takes the first character ([0]) of element i of the array, then sets every single value that wil lbe printed in the string to that character. Instead, try this
String[] newText = text.split("[./ ]");
for(int i = 0; i < newText.length - 4; i+=4){
System.out.println("Name: " + newText[i] + ", last name: " + newText[i+1] + ", date of birth: " + newText[i+2] + ", place of birth: " + newText[i+3]);
}
However, this is a terrible solution, it relies on fixed sized entries and should not be used in practice. What if someone enters the string in a different order, or with one too many inputs or one too few? Try using more flexible designs, such as the usage of a csv format parser, so you always split using commas, and the rows can be something like
entry-type, entry
entry-type, entry2
entry-type, entry3
Or something like that. Try it out. Always try to aim for flexible solutions that don't rely on exact input to work, otherwise you will have exceptions and runtime issues like there's no tomorrow.
PS the point of the split() method is to split the string between occurences of the specified input, i.e. [./], so don't use it if you want to just give a "", that's no different than making a charArray (except instead of char[] it is String[])

How do I create a method that capitalizes the first letter of a string in java? [duplicate]

This question already has answers here:
How to capitalize the first letter of a String in Java?
(59 answers)
Closed 8 years ago.
what I'm trying to do is write a method that has one argument and returns a new string that capitalises that string and returns in its parameter.
this is my code so far:
public void input(){
this.printmessage("Dillon", "Francis", "chimes", "chimes from hudson mohawke", "2", "$69.00", "$420.00", "$1337.00");
}
public void printmessage(String firstName, String lastname, String product, String company, String number, String retail, String price, String saving){
UI.println("text " + firstName + ",");
UI.println(text + " " + product + "s text, text text text text -");
UI.println(" ");
}
What I want to do is capitalise the product parameter (chimes) and then return into into the printMessage capitalized if it is used at the beginning of a sentence.
Will something like this work?
public String capitalise(String product){
return Character.toUpperCase(product.charAt(0)) + product.substring(1);
}
I'm really stuck and would love some help.
Thanks.
I've tried this
String pls = (product + " example");
if ( pls.startsWith(product) ) {
product = capitalise(product);
}
UI.println(pls);
but it doesnt print out the capitalised version.
change this line :
UI.println(text + " " + product + "s text, text text text text -");
to:
UI.println(text + " " + capitalize(product) + "s text, text text text text -");
But your code needs a bit more structuring. Focus on even indentation. And if you need the capitalized product later on, you'd better save it before you use it, like
...
product = capitalize(product);
UI.println(text + " " + product + "s text, text text text text -");
...
EDIT:
For this I'm assuming the line is contained in a String called line.
First check if the line begins with product. Then capitalize it.
...
String line = text + " " + product + "s text, text text text text -";
line = line.trim(); // removes whitespaces.
if ( line.startsWith( product ) ) {
product = capitalize ( product ); //or whatever.
}
UI.println(line);
...

Java - RegEx pattern that consists of LDAP attributes

Is there a way to use LDAP attributes stored in Strings as the RegEx pattern?
I am thinking something like this:
PASSWORD_WITH_LDAP_ATTRIBUTE = Pattern.compile(userid + "|" + ssn + "|" + bdate + "|" + empNo + "|" + telNo);
I already tried this one out. In any string that I input, the regex always finds a match even though its not a clear match.
Is this possible or am I venturing to the impossible?
Here is the whole method:
private static Pattern PASSWORD_WITH_LDAP_ATTRIBUTE = null;
private boolean checkForLdapAttributes(final String newPassword) throws LDAPException{
LoggingEnt loggingEnt = new LoggingEnt();
String userid = loggingEnt.getUseridCode();
String ssn = loggingEnt.getSocialSecurityNumber();
String bdate = loggingEnt.getBirthDate();
String empNo = loggingEnt.getEmployeeNumber();
String telNo = loggingEnt.getTelephoneNumber();
PASSWORD_WITH_LDAP_ATTRIBUTE = Pattern.compile(userid + "|" + ssn + "|" + bdate + "|" + empNo + "|" + telNo);
matcher = PASSWORD_WITH_LDAP_ATTRIBUTE.matcher(newPassword);
if(PASSWORD_WITH_LDAP_ATTRIBUTE.matcher(newPassword).find()){
isPasswordAccepted = false;
loggingEnt.setMsg1("You cannot use any of your Username, Social Security No., Birthdate, Employee No., and Telephone No. as password.");
throw new LDAPException("Invalid password combination for " + userid, LDAPException.INVALID_CREDENTIALS);
} else {
loggingEnt.setMsg1("Password accepted.");
isPasswordAccepted = true;
}
return matcher.matches();
}
You're doing this wrong. You're not supposed to match the password attribute yourself. You are supposed to attempt to 'bind' to LDAP specifying a username and password, and it will match the password for you. Or not.
In JNDI, 'bind' corresponds to LdapContext.reconnect().

Categories

Resources