A code snippet sonarQube suggests removing the local variables that aren't used in the lambda expression. I still don't deal with what's new in Java 8, especially lambda expressions. How can I replace these variables that are not used? The IntelliJ doesn't suggest anything to me.
My code
validation.stream().filter(aValidation -> aValidation.getSpec() != null).forEach(aValidation -> {
if (aValidation.getArquivo() != null) {
String nomeOriginal = aValidation.getSpec().get("peca_nome").toString();
itemsValidacao.put(nomeOriginal, aValidation.getResultadoConsolidado());
} else {
if (aValidation.getSpec().get("peca_nome") != null) {
String nomeOriginal = aValidation.getSpec().get("peca_nome").toString();
itemsValidacao.put(nomeOriginal, aValidation.getResultadoConsolidado());
}
}
});
chaves.stream().filter(chave -> chave != null).forEach(chave -> {
String value = cabecalho.get(chave);
try {
String novaChave = mapper.getChave(value.trim().toLowerCase());
if (!novaChave.isEmpty()) {
cabecalhoNormalizado.put(novaChave, chave);
}
} catch (NullPointerException e) {
Log.info(this, "Erro ao obter chave: " + value, e);
}
});
sonarQube
Remove this unused "chave" local variable.
Remove this unused "aValidation" local variable.
In that code snippet, don't remove them. They are being used in places like String nomeOriginal = aValidation.getSpec().get("peca_nome").toString() and cabecalhoNormalizado.put(novaChave, chave). Trying to remove them would almost certainly break the program, so I'm not sure why IntelliJ thinks that they are "unused."
Related
I am trying to get a solution to the following problem.
How can I find values from "conditions" in "stream"?
At the moment I can only filter with the "line.contains method". But I want that the user can give a number of conditions which would be saved in the Array "conditions". I tried to build a for-loop in the stream.filter but I failed.^^ Maybe you know an efficient way. :)
Thanks.
private static void streamSelectedFile(String p, String[] conditions) {
try (
Stream<String> stream = Files.lines(Paths.get(p), StandardCharsets.ISO_8859_1)) {
Stream<String> filteredStream =
stream.filter(line -> line.contains("conditionValue"));
filteredStream.forEach(elem -> {
System.out.println(elem + " Path: " + p);
});
} catch (IOException e) {
...
}
}
Use allMatch
stream.filter(line -> Stream.of(conditions).allMatch(line::contains))
I have a requirement where I need to append multiple values from multiple web service calls into one final string with comma as a separator.
Some of the values might be null, in that case I need to check for not null and then append it as empty string.
If there is no value for one of the string, comma should not get appended.
Please help me resolving this. here is the code what I did.
StringBuilder sb = new StringBuilder();
if (usersList.totalCount != 0 && usersList.totalCount >= 1) {
logger.info("usersList.totalCount ----->"
+ usersList.totalCount);
for (KalturaUser user : usersList.objects) {
if (user.id != null) {
sb.append(userId);
}
if (user.firstName != null) {
sb.append(",").append(userFirstName);
}
if (user.lastName != null) {
sb.append(",").append(user.lastName);
}
if (user.email != null) {
sb.append(",").append(user.email);
}
if (user.roleNames != null) {
sb.append(",").append(user.roleNames);
}
if (user.partnerData != null) {
sb.append(",").append(user.partnerData);
}
}
System.out.println(sb);
}
Thanks,
Raji
I think you are looking for something like this:
public static String asString(Object value) {
return value == null ? "" : value.toString();
}
for (KalturaUser user : usersList.objects) {
sb.append(asString(user.id));
sb.append(",").append(asString(user.firstName));
sb.append(",").append(asString(user.lastName));
sb.append(",").append(asString(user.email));
sb.append(",").append(asString(user.roleNames));
sb.append(",").append(asString(user.partnerData));
}
Well, in your tests like
if (user.id != null) {
sb.append(userId);
}
you are checking user.id but appending userId. These are two different variables.
You should probably change it into
if (user.id != null) {
sb.append(user.id); //instead of sb.append(userId);
}
It is not clear what your problem is, but if you are looking for a better or different approach, I found that it is best to append to a List<String> and then use StringUtils.join to produce the final string.
You can use a class from a google library called Joiner.
String concatenedString = Joiner.on(",").skipNulls().join(itemToAdd);
You can find this class on google-collections-1.0.jar
I would do something like that. It's based on Java8 streams, but here you don't need to do the non-null check on every property(.filter does this for you). I assumed that users.object is an array list, if it's not you might need to convert it into stream in other way
if (userList.totalCount > 0) {
logger.info("usersList.totalCount ----->" + usersList.totalCount);
String result = userList
.objects
.stream()
.map(user -> {
return Stream.of(user.firstName, user.id, user.lastName, user.email, user.roleNames, user.partnerData) //get the properties you need into the stream
.filter(property -> property != null) // filter out null properties
.collect(Collector.joining(",")); //join them by comma
})
.collect(Collector.joining(",")); //join user strings with comma
System.out.println(result);
}
I'm stuck on the very last part of my homework. I have to return an Agent value, but for some reason I keep getting an error saying that "This method must return type Agent", even though what I am returning is an Agent. Any help would be greatly appreciated.
import java.io.File;
import java.util.HashMap;
import jeff.ini.Ini;
public class ConfigLoader
{
private Ini _ini;
private HashMap<String, Space> _spaces = new HashMap<String, Space>();
private HashMap<String, Portal> _portals = new HashMap<String, Portal>();
private HashMap<String, Agent> _agents = new HashMap<String, Agent>();
public ConfigLoader(File iniFile)
{
_ini = new Ini(iniFile);
}
public Agent buildAll()
{
_buildSpaces();
_buildPortals();
_buildExits();
_buildDestinations();
_buildAgents();
return _selectStartAgent();
}
private void _buildSpaces(){
for(String spaceName : _ini.keys("spaces")){
String descrip= _ini.get("spaces", spaceName);
String image= _ini.get("images", "images");
Space space1= new Space(spaceName, descrip, image, null);
_spaces.put(spaceName, space1);
}
}
private void _buildPortals(){
for(String portalName : _ini.keys("portals")){
String descrip= _ini.get("portal", portalName);
Portal portal1=new Portal(portalName, descrip, null);
_portals.put(portalName, portal1);
}
}
private void _buildExits(){
for(String spaceName : _ini.keys("exits")){
String spaceExit = _ini.get("exits", spaceName);
Space space = _spaces.get(spaceName);
Portal exit = _portals.get(spaceExit);
space.setPortal(exit);
}
}
private void _buildDestinations(){
for(String portalName : _ini.keys("destinations")){
String destination = _ini.get("destinations", portalName);
Space des = _spaces.get(destination);
if(des == null){
System.out.print("ERROR");
System.exit(1);
}
else{
Portal portal = _portals.get(portalName);
portal.setDestination(des);
}
}
}
private void _buildAgents(){
for(String agentName : _ini.keys("agents")){
String agent = _ini.get("agents" , agentName);
Space space = _spaces.get(agent);
if(space == null){
System.out.print("ERROR");
System.exit(1);
}
else{
Agent a = new Agent(space, agentName);
_agents.put(agentName, a);
}
}
}
private Agent _selectStartAgent(){
for(String agentName : _ini.keys("start")){
String agent = _ini.get("start" , agentName);
Agent agent1 = _agents.get(agent);
if(agent == null){
System.out.print("ERROR");
System.exit(1);
}
else{
return agent1;
}
}
}
}
A method should return a value in all the different execution path. You are returning a value only in else block, which means in case when else block is not executed the value will not be returned and hence compiler complains for it. Make sure that you return a value in all different execution path, when if is not executed, when else is not executed, when for loop itself is not executed.
The key is that all execution paths must return a value of type Agent, which could be null. The calling method must, as usual, check whether the returned value is null.
Now let's look at what are missing:
The if branch does not return a value, instead it abruptly exits.
If the for loop is never entered, the method does not return anything either.
With all those fixed, the entire code could be something like:
for (String agentName : _ini.keys("start")){
String agent = _ini.get("start" , agentName);
Agent agent1 = _agents.get(agent);
if (agent == null){
System.out.print("ERROR");
return null;
} else {
return agent1;
}
return null;
}
The problem with your _selectStartAgent method is that a return isn't executed in all cases. You do call System.exit(1) inside this method, but the compiler doesn't care; it sees that as another method call. Even if it won't return because the JVM will be exited, the compiler still requires a return in the case where agent is null.
You could just place a return null; after System.exit(1). However, this method shouldn't be handling an error. It just needs to report the error. Just have it return null (or have it throw an exception).
if(agent == null){
return null;
// or
// throw an exception here
}
The method that calls _selectStartAgent should check for null (or handle the exception, depending on which you choose).
Additionally, the compiler doesn't assume that there will be an iteration of any for loop. There is no return there either. You can place a return statement after the for loop, to ensure that there is a return when there is no iteration of the for loop.
I believe it has to do with if your for loop doesn't have anything to loop through. In that case, you have no return statement.
Try adding return null after the for loop.
private Agent _selectStartAgent(){
for(String agentName : _ini.keys("start")){
String agent = _ini.get("start" , agentName);
Agent agent1 = _agents.get(agent);
if(agent == null){
System.out.print("ERROR");
System.exit(1);
}
else{
return agent1;
}
}
return null;
}
Our goal is to fetch some of the content from Liferay Portal via SOAP services using Java. We are successfully loading articles right now with JournalArticleServiceSoap. The problem is that the method requires both group id and entry id, and what we want is to fetch all of the articles from a particular group. Hence, we are trying to get the ids first, using AssetEntryServiceSoap but it fails.
AssetEntryServiceSoapServiceLocator aesssLocator = new AssetEntryServiceSoapServiceLocator();
com.liferay.client.soap.portlet.asset.service.http.AssetEntryServiceSoap assetEntryServiceSoap = null;
URL url = null;
try {
url = new URL(
"http://127.0.0.1:8080/tunnel-web/secure/axis/Portlet_Asset_AssetEntryService");
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
assetEntryServiceSoap = aesssLocator
.getPortlet_Asset_AssetEntryService(url);
} catch (ServiceException e) {
e.printStackTrace();
}
if (assetEntryServiceSoap == null) {
return;
}
Portlet_Asset_AssetEntryServiceSoapBindingStub assetEntryServiceSoapBindingStub = (Portlet_Asset_AssetEntryServiceSoapBindingStub) assetEntryServiceSoap;
assetEntryServiceSoapBindingStub.setUsername("bruno#7cogs.com");
assetEntryServiceSoapBindingStub.setPassword("bruno");
AssetEntrySoap[] entries;
AssetEntryQuery query = new AssetEntryQuery();
try {
int count = assetEntryServiceSoap.getEntriesCount(query);
System.out.println("Entries count: " + Integer.toString(count));
entries = assetEntryServiceSoap.getEntries(query);
if (entries != null) {
System.out.println(Integer.toString(entries.length));
}
for (AssetEntrySoap aes : assetEntryServiceSoap.getEntries(query)) {
System.out.println(aes.getEntryId());
}
} catch (RemoteException e1) {
e1.printStackTrace();
}
Although getEntriesCount() returns a positive value like 83, getEnries() always returns an empty array. I'm very new to Liferay portal, but it looks really weird to me.
By the way, we are obviously not looking for performance here, the key is just to fetch some specific content from the portal remotely. If you know any working solution your help would be much appreciated.
Normally a AssetEntryQuery would have a little more information in it for example:
AssetEntryQuery assetEntryQuery = new AssetEntryQuery();
assetEntryQuery.setClassNameIds(new long[] { ClassNameLocalServiceUtil.getClassNameId("com.liferay.portlet.journal.model.JournalArticle") });
assetEntryQuery.setGroupIds(new long[] { groupId });
So this would return all AssetEntries for the groupId you specify, that are also JournalArticles.
Try this and see, although as you say, the Count method returns a positive number so it might not make a difference, but give it a go! :)
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I have this Hash Set code and when I try to run my compile method on it I get the Null Pointer Exception: null error on it. Here is the code:
private void initKeywords() {
keywords = new HashSet<String>();
keywords.add("final");
keywords.add("int");
keywords.add("while");
keywords.add("if");
keywords.add("else");
keywords.add("print");
}
private boolean isIdent(String t) {
if (keywords.contains(t)) { ***//This is the line I get the Error***
return false;
}
else if (t != null && t.length() > 0 && Character.isLetter(t.charAt(0))) {
return true;
}
else {
return false;
}
}
The other lines that goes along with this error is:
public void compileProgram() {
System.out.println("compiling " + filename);
while (theToken != null) {
if (equals(theToken, "int") || equals(theToken, "final")) {
compileDeclaration(true);
} else {
compileFunction(); //This line is giving an error with the above error
}
}
cs.emit(Machine.HALT);
isCompiled = true;
}
private void compileFunction() {
String fname = theToken;
int entryPoint = cs.getPos();
if (equals(fname, "main")) {
cs.setEntry(entryPoint);
}
if (isIdent(theToken)) theToken = t.token(); ***//This line is giving an error***
else t.error("expecting identifier, got " + theToken);
symTable.allocProc(fname,entryPoint);
accept("(");
compileParamList();
accept(")");
compileCompound(true);
if (equals(fname, "main")) cs.emit(Machine.HALT);
else cs.emit(Machine.RET);
}
Are you sure you're running initKeywords() before isIdent()?
Either keywords or t is null. Using either a debugger or print statements it should be pretty simple to determine. If keywords is null, I'd assume that initKeywords() has not been called yet.
You probably want to call initKeywords from the constructor of this object.
I personally try to stay away from init methods. As previously mentioned, a constructor serves as an initializer, and so does the static block:
private final static Set<String> KEYWORDS = new HashSet<String>();
static {
keywords.add("final");
keywords.add("int");
keywords.add("while");
keywords.add("if");
keywords.add("else");
keywords.add("print");
}