I am currently working over CSV exports. I am fetching header from properties file with below code -
String[] csvHeader = exportables.get(0).getCSVHeaderMap(currentUser).keySet().stream().
map(s ->messageSource.getMessage("report."+s, null, locale)).toArray(String[]::new);
The above code works well. But i need to find a way to handle exception and also fetch data from another file, if it is not found in above file. I am expecting to use somewhat below code -
try{
exportables.get(0).getCSVHeaderMap(currentUser).keySet().stream().
map(s ->messageSource.getMessage("report."+s, null, locale)).toArray(String[]::new);
}catch(NoSuchMessageException e){
// code to work over lacking properties
}
I want to catch the 's' element in catch block (or in other good way). So that i can fetch it from another file and also add its return to current csvHeader.
One way is to make for each element a try catch block like:
exportables.get(0).getCSVHeaderMap(currentUser).keySet().stream().
map(s -> {
String result;//Put the class to which you map
try{
result = messageSource.getMessage("report."+s, null, locale);
}catch(NoSuchMessageException e){
// code to work over lacking properties here you have access to s
}
return result;
}
).toArray(String[]::new);
Another solution will be to check for specific problems and then there is no need to catch exceptions. For example if s is null and then you want to get the data from another place:
exportables.get(0).getCSVHeaderMap(currentUser).keySet().stream().
map(s -> {
String result;//Put the class to which you map
if(null == s)// Some condition that you want to check.
{
//get info from another place
//result = ....
}
else
{
result = messageSource.getMessage("report."+s, null, locale);
}
return result;
}
).toArray(String[]::new);
Related
I'm creating an API that return Vaccination Info of people. The code below is that I'm getting list of vaccination IDs. If people injected 1 or more, the API working fine, I get a list as expected. Vice versa, if they haven't injected, the data on server is null. In that case, when I make an API call I will get the error that vaccinationInfoList is null, but it's still have the size 1. I tried as below to locate the error but it's cannot catch any exception.
try {
Response<List<Vaccination_info>> res = call.execute();
Log.v("RES" , String.valueOf(res));
if (res.body() != null){
try {
vaccinationInfoList = res.body();
}
catch (Exception n){
Log.v("ExceptionN" , String.valueOf(n));
}
} else {
Log.v("NULL" , "NULL");
}
} catch (IOException e) {
e.printStackTrace();
}
Log.v("VACC", String.valueOf(vaccinationInfoList.size()));
Can someone recommend me a solution or a different aproach? Thanks so much
If you have access and can change api response so change response from null to empty array list []
If not You can use com.google.gson.JsonElement
Im trying to use the findDistinct function from mongoTemplate but i always retrieve an empty result list.
Can you help me out to spot the problem ? Or maybe you have a simpliest way to do it
NB:
I do have data in my collection
(on a basic find, i fetch more than 300 results in the list but all of this result are the same excepting on one key, i want all the distinct object from their NAME value for instance )
I tryied this :
List<DiffusionListImpl> list = new ArrayList<>();
try{
query = new Query(Criteria.where("CUSTOMERNUMBER").is(1));
list = mongoTemplate.findDistinct(query, KeyWhereIWantTheDistinct, collectionName,
KlassResultModel.class);
} catch (MongoException e) {
logger.error("MongoException: " + e);
} catch (Exception e) {
logger.error("Error: " + e);
}
return list;
My bad, i misread the documentation.
But i find it akward to have this kind of comportement of this function.
I have to make a call to the DB to fetch a list of distinct value and then make another Call of the same DB to retrieve the object.
Is there any way to do it in one call? (Performance issue)
It can be done in one DB call, use below code.
final List<DiffusionListImpl> result =
IteratorUtils.toList(this.mongoTemplate.getCollection("collectionName")
.distinct("fieldName", query.getQueryObject(), DiffusionListImpl.class)
.iterator());
for IteratorUtils you can use apache
import org.apache.commons.collections4.IteratorUtils;
I have a list of json object coming in from AWS input stream.
Each json objects are specific custom/user objects.
I need help as I'm stuck in point 2.
picks json object-->converts to custom Object.
If the conversion fails with any parse exception of json, then the code should log/print in the console the error'd out a record. continue to next json record.
I have the object-mapper/JsonParser(from Jackson Library) to do the conversion using readValueAs() method.
I'm stuck in the second part to fetch the error'd out the record and log it. then continue with next record.
Examples are below
{
"col1":"col1Value",
"col2":"col2Value",
"col3":"col3Value",
{sub-json-objects}**,**
"col4":"col4Value"
}
{
"col11":"col11Value",
"col12":"col12Value",
"col13":"col13Value",
{sub-json-objects}***(supposingly if the comma is missing here)***
"col14":"col14Value"
}
i.e.
{
"col11":"col11Value",
"col12":"col12Value",
"col13":"col13Value", {sub-json-objects}
"col14":"col14Value"
}
If you guys can suggest me any other approach its fine. I'm looking for error'd out json + log and continue it further.
I tried below
#Override
public T next() {
try {
return (T) jp.readValueAs((Class<T>) type);
} catch (Exception ex) {
logger.info("Failed Record --> " + jp.currentToken());
logger.error(ex.getMessage(), ex);
}
return null;
}
Regards,
Pawan.
I am using UnboundID-LDAPSDK (2.3.8) to change the user's photo in our Microsoft Active Directory.
LDAPConnection ldap = null;
try {
ldap = new LDAPConnection("domain-srv", 389, "CN=admin,OU=Users,OU=ADM,DC=domain,DC=local", "password");
SearchResult sr = ldap.search("DC=domain,DC=local", SearchScope.SUB, "(sAMAccountName=" + getUser().getUsername() + ")");
if (sr.getEntryCount() == 1) {
SearchResultEntry entry = sr.getSearchEntries().get(0);
entry.setAttribute("thumbnailPhoto", getUser().getPhotoAsByteArray());
ldap.close();
return true;
} else
return false;
} catch (LDAPException e) {
e.printStackTrace();
}
But I get a java.lang.UnsupportedOperationException.
The documentation for setAttribute states:
Throws an UnsupportedOperationException to indicate that this is a
read-only entry.
I also tried to change the postalCode but I get the same exception.
Changing those attributes should be possible, because I can change them with jXplorer.
Do I have to enable a write-mode somehow?
Thank you
The SearchResultEntry object extends ReadOnlyEntry and is therefore immutable. But even if it weren't, merely calling entry.setAttribute would have no effect on the data in the server. You have to use a modify operation for that.
To do that, you'd need something like:
ModifyRequest modifyRequest = new ModifyRequest(entry.getDN(),
new Modification(ModificationType.REPLACE,
"thumbnailPhoto", getUser().getPhotoAsByteArray());
ldap.modify(modifyRequest);
Also, you should put the call to ldap.close() in a finally block because as the code is written now, you're only closing the connection if the search is successful and returns exactly one entry, but not if the search fails, doesn't match any entries, or the attempt to perform the modify fails.
Using a JSP web page and Rserve, I am getting data from a MySQL database and using an R dataframe to store the data. This works fine and plots perfect.
However, if the db query returns nothing the dataframe is then empty and it throws an error when trying to plot.
What I want to do is redirect to another JSP page which will then display the error but I am not sure how to do this.
I have found this R code (what it does was purely for testing purposes) which tells me if the dataframe is empty or not but how can I then include Java (or something else) to redirect the page?
if (nrow(df) != 0) {
df
} else {
df <- "Empty"
df
}
Edit: I have managed to get this far:
c.eval("if(nrow(df) != 0){ print(ggplot(df, aes(x=Date, y=UID))+geom_point(shape=1)) }"
+"else { print(\"Failed\") }");
The 'failed' doesn't print (I didn't really expect it to) but as said above in the else I would like a redirect. Any thoughts about how this would be possible?
A simply try{} catch{} solved the problem! Don't know why I didn't think of that earlier.
So instead of:
c.eval("if(nrow(df) != 0){ print(ggplot(df, aes(x=Date, y=UID))+geom_point(shape=1)) } else { print(\"Failed\") }");
I have used this:
try {
c.eval("print(ggplot(df, aes(x=Date, y=UID)) + geom_point(shape=1))"); // point graph
System.out.print("Success");
} catch (Exception e) {
out.print(e.getMessage());
System.out.print("Failed");
}