Handling empty R dataframe on JSP/Rserve web page - java

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

Related

Android API get attribute as list or null

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

How to catch and modify data over exception occurred during Stream usage

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

how to parse pdf file in java and save some data in mysql database

I want to parse a pdf file in java and extract some transactional data from it. I have used iText to read pdf. It returns whole pdf as a string. I am not able to extract data. What is the better approach to handle this?
Below are the content which i get after parsing my pdf file which is in string format and i need to filter the transactional data so that i can insert it into database.
Date Transaction Amount Units Price Unit
(INR) (INR) Balance
Birla Sun Li[e Mutual Fund
Folio No: 1016409683 PAN: AZMPB2802L KYC: OK PAN: OK
B291GZ-Birla Sun Life India GenNext Fund - Growth-Direct Plan(Advisor: DIRECT) Registrar : CAMS
Opening Unit Balance: 0.000
12-Mar-2014 Purchase 5,000.00 146.113 34.22 146.113
22-Apr-2014 Purchase - via Internet 1,500.00 41.993 35.72 188.106
05-May-2014 Purchase - via Internet 1,500.00 42.505 35.29 230.611
13-Jan-2015 Purchase - via Internet 1,500.00 28.604 52.44 259.215
3-Feb-2015 Purchase - via Internet 3,000.00 54.835 54.71 314.050
03-Mar-2015 Purchase - via Internet 3,000.00 53.476 56.10 367.5260
Valuation on 10-Mar-2016: INR 58,956.90
Closing Unit Balance: 1,143.462 NAV on 10-Mar-2016: INR 51.56
Depending on the specific situation you're in, you can try various approaches.
iText has a tool called pdf2Data, which sounds like it does exactly what you're looking for. It processes a document according to a template, and gives you an xml document. This is of course more suited for a commercial setting.
You can write your own extraction strategy, that handles the pdf document in a more clever way. Suppose for instance that you want to extract information from a table in a pdf document.
You would implement IEventListener, and listen for two kinds of events; line-drawing events (so that you get notified when the table is being drawn) and text-rendering events (to get the content in the table).
You then have to write several smart heuristics that define what constitutes a table. For a simple proof-of-concept you could simply look for lines that cross in 90 degree angles. Determine the bounding box. Then go looking for all text-rendering instructions within that box. Use another clever heuristic that is able to determine column and row-boundaries.
What you really need actually, IS a String and the procedure you're looking for is called parsing. Once you get that String containing the whole pdf, you need to write some "smart" (saying smart as it depends on the contents of your pdf) code that can split the main String into smaller, more useful (for you) parts.
After that, you need to setup a connection with a database with your java app and provide the necessary db code that will use the smaller String parts you created with your parser to fill up your tables.
Bellow, you can see some code i've written for an assignment which required parsing useful parts of a larger String object from a stream (in this case a .txt containing stats from a basketball game).
public static ArrayList<HashMap<String, String>> parse (InputStream input) throws IOException {
output = new ArrayList();
count = 0;
atcount = 0;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(input))) {
if (input != null) {
while ((line = reader.readLine()) != null) {
if (line.contains("Team")) {
playerBounds = false;
team2Bounds = true;
count = 0;
}
if (playerBounds == true && team2Bounds == false) {
count++;
listΑ = line.split("\t");
addToList();
//printAll();
}
if ((playerBounds == true) && (team2Bounds == true)) {
count++;
listΑ = line.split("\t");
addToList();
//printAll();
}
if (line.contains("Player")) {
playerBounds = true;
}
atcount = 0;
}
}
} catch (IOException ex) {
throw ex;
} finally {
try {
input.close();
} catch (Throwable ignore) {
}
}
return output;
}
I hope this can help you :)

How to select item in a list from search Result page using Selenium in Java?

am trying to click on this game to open it's page but every time gives me null pointer exception whatever locator am using still gives me same error also i tried to do a select from list as the link seems to be inside an "li" but didnt work also.
anyone could help me with the code to click this item ??
Targeted Page Url:
https://staging-kw.games.getmo.com:/game/43321031
Search(testCase);
WebElement ResultList = driver.findElement(By.xpath(testData.getParam("ResultList")));
log.info("list located ..");
List<WebElement> Results = ResultList.findElements(By.tagName(testData.getParam("ResultListItems")));
for (WebElement List : Results) {
String Link = List.getAttribute("href");
try {
if (Link.equals(null)) {
log.info("null");
}
if (Link.equals(testData.getParam("GameLink")) && !Link.equals("") && !Link.equals(null)) {
List.click();
}
} catch (NullPointerException countryIsNull) {
log.info("LinkIsNull");
}
}
//clickLink(GameLocator,driver);
}`
I got this code to work by just adding this line after the search method
driver.findElement(By.cssSelector("li.title")).click();
and how did i get it ? .. i used Selenium IDE to record the actions then converted the code to Java -TestNG to get the exact web element selector

Java Neo4j Deletion and Internal 500 Errors

When I delete my neo4j database after my tests like this
public static final DatabaseOperation clearDatabaseOperation = new DatabaseOperation() {
#Override public void performOperation(GraphDatabaseService db) {
//This is deprecated on the GraphDatabaseService interface,
// but the alternative is not supported by implementation (RestGraphDatabase)
for (Node node : db.getAllNodes()) {
for (Relationship relationship : node.getRelationships()) {
relationship.delete();
}
boolean notTheRootNode = node.getId() != 0;
if (notTheRootNode) {
node.delete();
}
}
When querying the database through an ajax search (i.e searching on an empty database it returns an internal 500 error)
localhost:9000/search-results?keywords=t 500 Internal Server Error
197ms
However if I delete the database manually like this
start r=relationship(*) delete r;
start n=node(*) delete n;
No exception is thrown
Its most likely an issue with my code at a lower level in the call and return.
Just wandering why the error only works on one of the scenarios above and not both
Use cypher,
you should probably state more obviously that you use the rest-graph-database.
Are you querying after the deletion or during it?
Please check your logs in data/graph.db/messages.log and data/log/console.log to find the error cause.
Perhaps you can also look at the response body of the http-500 request
As per your error I guess your data is getting corrupted after deletion.
I have used same code like yours and deleted the nodes, except I put the Iterator in transaction and shut down the database after opetation.
e.g.
Transaction _tx = _db.beginTx();
try {
for ( your conditions){
Your code
}
_tx.success();
} catch (Exception e) {
_logger.error(e.getMessage());
}finally{
_tx.finish();
_db.shutdown();
graphDbFactory.cleanUp();
}
Hope it will work for you.

Categories