Why is my break label erroring? - label

Hey guys I am trying to break out of a for loop that searches thru all files and breaks once it finds the file. The best thing I have found is the labeling break but its giving an error saying it doesn't exist can you guys take a look and see what I am doing wrong?
import java.nio.file.Files;
import java.nio.file.Paths;
import org.dom4j.Document;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.jaxen.dom4j.*;
public class Load
{
static String info = "";
public static String LoadSum(String projNum)
{
info = "";
try
{
searching:
Files.walk(Paths.get("D:/workspace/Project Program/Projects/")).forEach(filePath ->
{
if(Files.isRegularFile(filePath))
{
try
{
System.out.println("Checking");
SAXReader reader = new SAXReader();
Document document = reader.read(filePath.toFile());
Node node = document.selectSingleNode("//Project/Info/ProjectNumber");
String projectNumber = node.getStringValue();
if(projNum.equals(projectNumber))
{
System.out.println("Found it");
node = document.selectSingleNode("//Project/Info/Name");
info += node.getStringValue() + " : ";
//node = document.selectSingleNode("//Project/Info/Owner");
info += "Owner" + " : ";
node = document.selectSingleNode("//Project/Info/Status");
info += node.getStringValue() + " : ";
break searching; // error here searching doe not exist
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
return info;
}
}
}

The break statement is not into a loop, so you cannot use it.
To forEach statement accepts an Anonymous function that is applied to all the elements found by the Paths.get("D:/workspace/Project Program/Projects/")) statement.
You can stop the operation by throwing an exception, if it's suitable for you.
Source: Java Docs
Edit: considering the fact that what you are passing is an anonymous function you can wrap all the function block with an if statement that depends on a boolean variable defined outside the function: if you find the element you toggle the variable so for the next elements it will be just a no-op. If you wanna know more about Java lambda expressions look here.

Related

PMD Xpath, how to compare 2 #Image?

It's is pretty easy to compare one path's #Image to a static string but how to compare 2 paths'#Image ?
Code that should trigger the rule :
public class Foo implements {
public String checkDBConnexion() {
try {
int result = jdbcTemplate.queryForObject("SELECT 1 FROM dual ", Integer.class);
} catch (DataAccessException e) {
// This is Ok : throw new MyException(test, e);
// this is not : hrow new MyException(test);
// This is also not ok if there are no thrown;
return "KO : " + e.getMessage();
}
}
}
Xpath for the param name of the Catch block :
//CatchStatement[//FormalParameter//VariableDeclaratorId]
Xpath for the variable name of the thrown method :
//ThrowStatement//Arguments//Expression//Name
It's easy to compare both to 'e' :
//CatchStatement[//FormalParameter//VariableDeclaratorId[#Image = 'e']]
//CatchStatement[//ThrowStatement//Arguments//Expression//Name[#Image = 'e']]
How do I compare them with eachother ?
Also if you have a link with detailled PMD XPath synthax exemple.
The basic PMD page has ... well the basic ;)
Answering myself :
//CatchStatement[//FormalParameter//VariableDeclaratorId/#Image =
//ThrowStatement//Arguments//Expression//Name/#Image]

How do I combine Domino view data and JDBC query in a repeat control

Currently, I have a repeat control with computed fields that display column values from a Domino view. In each row in the repeat control I have another computed field that executes a SQL query that returns a value from a SQL table. The SQL query has a parameter that uses one of the column values from the Domino view.
For the SQL computed field I wrote a function that instantiates a JDBC connection and then executes a SQL query for each row in the repeat control. The function looks like this (the pTextNo argument comes from one of the column values in the Domino view):
function getFormulaTextDetailRows(pTextNo){
if(pTextNo == null){return ""};
var con:java.sql.Connection;
try {
con = #JdbcGetConnection("as400");
vStatement = "SELECT TXSQN, TXDTA FROM LIB1.PRTEXTS WHERE RTRIM(TEXT#) = ? ORDER BY TXSQN";
var vParam = [pTextNo];
var resultset:java.sql.ResultSet = #JdbcExecuteQuery(con, vStatement, vParam);
var returnList = "<ul>";
//format the results
while(resultset.next()){
returnList += ("<li>" + resultset.getString("TXDTA").trim() + "</li>");
}
returnList += "</ul>";
}catch(e){
returnList = e.toString()
}finally{
con.close();
}
return returnList;
}
This works fine but I'm sure this isn't the most efficient way of utilising the JDBC connection. Opening and closing a JDBC connection on each row in the repeat control isn't right and I'm concerned that when more than one person opens the XPage the server will run into difficulties with the number of open connections.
After doing some research on the internet it seems I should be using a jdbcConnectionManager on the page.
I added a jdbcConnectionManager to my custom control and also added a jdbcQuery data source to the panel that holds the repeat control. The jdbcConnectionManager looks like this:
<xe:jdbcConnectionManager
id="jdbcConnectionManager1"
connectionName="as400">
</xe:jdbcConnectionManager>
And the jdbcQuery data source looks like this:
<xe:jdbcQuery
var="jdbcProcessText"
scope="request"
calculateCount="true"
sqlQuery="SELECT TXSQN,TXDTA FROM DOMINO.PRTEXTS WHERE RTRIM(TEXT#) = ? AND TXSQN != '0' ORDER BY TXSQN"
connectionManager="jdbcConnectionManager1">
<xe:this.sqlParameters>
<xe:sqlParameter value="#{javascript:requestScope.processTextNo}">
</xe:sqlParameter>
</xe:this.sqlParameters>
</xe:jdbcQuery>
My computed field's value property in the repeat control looks like this:
requestScope.processTextNo = textrow.getDocument().getItemValueString('ProcessTextNo');
var vCount = jdbcProcessText.getCount();
var returnList = "<ul>";
for(i=0; i<vCount; i++){
returnList += ("<li>" + jdbcProcessText.get(i).getColumnValue("TXDTA") + "</li>");
}
returnList += "</ul>";
return returnList;
The problem I've run into is that I don't get any data from the JDBC query at all. Even if I hard code a value I know exists in the SQL table in the sqlParameter property of the jdbcQuery object I still get no results. I suspect I'm not calling the jdbcQuery object correctly but I can't figure out how to do so. Any help will be greatly appreciated.
You may want to reconsider your approach. I would suggest creating a Java bean to get the Domino view data, loop through that and call out to your query for each row in the view. Build up a List (Java List) of a Row class that has all the data you want to show. Then in the repeat call to your Java bean to a method that returns the List of Row classes. In each control in the repeat you would call to the getXXX method in your Row class. This way you can quickly build the List the repeat works on. Doing it your way in the control in the repeat will be very slow.
Howard
Here's the bean I wrote to do the job. At the start it opens a connection to the SQL data source, grabs a viewEntryCollection using a document UNID as a key, and then puts the column values into a HashMap for each row in the viewEntryCollection. One of the values in the HashMap is pulled from a SQL query. My repeat control iterates over the List returned by the bean. In other words the bean returns a List of HashMaps where most of the values in each HashMap comes from Domino view entry data and one value comes from SQL (not sure if that's the correct way of saying it, but it makes sense to me!).
Here's my code:
package com.foo;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;
import javax.faces.context.FacesContext;
import lotus.domino.Database;
import lotus.domino.NotesException;
import lotus.domino.View;
import lotus.domino.ViewEntry;
import lotus.domino.ViewEntryCollection;
import com.ibm.xsp.extlib.relational.util.JdbcUtil;
import com.ibm.xsp.extlib.util.ExtLibUtil;
public class ProcessTextLines implements Serializable {
private static final long serialVersionUID = 1L;
private Connection conn = null;
public int rowCount = 0;
public int getRowCount() {
return rowCount;
}
// public void setRowCount(int rowCount) {
// this.rowCount = rowCount;
// }
public ProcessTextLines() {
/*
* argumentless constructor
*/
try {
// System.out.println("ProcessTextLines.java - initialising connection to as400");
this.conn = this.initialiseConnection();
} catch (SQLException e) {
e.printStackTrace();
}
finally {
if (this.conn != null) {
// System.out.println("ProcessTextLines.java - closing connection to as400");
try {
this.conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
public List<HashMap<String, String>> getRows(final String unid)
throws NotesException {
List<HashMap<String, String>> result = new ArrayList<HashMap<String, String>>();
try {
Database db = ExtLibUtil.getCurrentSession().getCurrentDatabase();
View view = db.getView("luProductMasterFormula");
view.setAutoUpdate(false);
ViewEntryCollection vec = view.getAllEntriesByKey(unid, true);
ViewEntry ve = vec.getFirstEntry();
while (ve != null) {
result.add(processRowVals(ve));
rowCount++;
ViewEntry tmp = vec.getNextEntry(ve);
ve.recycle();
ve = tmp;
}
view.recycle();
db.recycle();
vec.recycle();
} catch (NotesException e) {
e.printStackTrace();
}
return result;
}
/*
* Create a HashMap of names + column values from a ViewEntry
*/
#SuppressWarnings("unchecked")
private HashMap<String, String> processRowVals(ViewEntry ve) {
HashMap<String, String> processRow = new HashMap<String, String>();
try {
Vector cols = ve.getColumnValues();
processRow.put("sequenceNo", cols.get(1).toString());
processRow.put("textNo", cols.get(3).toString());
processRow.put("status", cols.get(6).toString());
processRow.put("textLines", getProcessTextLines(cols.get(3).toString()));
// unid of the entry's doc
processRow.put("unid", ve.getUniversalID());
} catch (NotesException e) {
e.printStackTrace();
}
return processRow;
}
private Connection initialiseConnection() throws SQLException {
Connection connection = null;
try {
connection = JdbcUtil.createNamedConnection(FacesContext
.getCurrentInstance(), "as400");
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
private String getProcessTextLines(String textNo) {
String resultHTML = "<ul class=\"processTextList\">";
try {
// System.out.println("ProcessTextLines.java - setting SQL parameter: " + textNo);
PreparedStatement prep = conn
.prepareStatement("SELECT TXSQN,TXDTA FROM LIB1.PRTEXTS WHERE RTRIM(TEXT#) = ? AND TXSQN != '0' ORDER BY TXSQN");
// supply a value to the PreparedStatement's parameter (the first
// argument is 1 because it is the first parameter)
prep.setString(1, textNo);
ResultSet resultSet = prep.executeQuery();
while (resultSet.next()) {
resultHTML += ("<li>" + resultSet.getString("TXDTA").trim() + "</li>");
}
} catch (SQLException e) {
// e.printStackTrace();
}
resultHTML += "</ul>";
return resultHTML;
}
}
It took me a while because of my lack of Java knowledge but with the pointers #Howard gave plus the few bits and pieces I found on the web I was able to cobble this together.
Opening and closing the SQL connection in the constructor feels counter intuitive to me, but it seems to work.

Use an alias on Pig UDF paramter

I need your help to know how to use an alias (stored tuple) on my Pig udf function, i exmplain:
my_file.csv
101,message here
102,message here
103,message here
...
My script PIG:
X = load'mydata.csv' using PigStorage(',') as (myVar:chararray);
A = load'my_file.csv' using PigStorage(',') as (key:chararray,value:chararray);
B = GROUP par ALL;
C = foreach B {
D = ORDER par BY key;
GENERATE BagToTuple(D);
};
the result of the C is something like (101,message here, 102, message here, 103, message here...)
Now what i need is to pass this result in my udf function like :
Z = foreach X generate MYUDF(myVar, C);
the alias "C" is the tuple key,value,key,value...
MYUDF :
import java.io.IOException;
import java.util.regex.Pattern;
import org.apache.pig.EvalFunc;
import org.apache.pig.data.Tuple;
import org.apache.pig.PigWarning;
import org.apache.pig.data.DataType;
import org.apache.pig.impl.util.WrappedIOException;
import org.apache.pig.impl.logicalLayer.schema.Schema;
public class ReDecode extends EvalFunc<String> {
int numParams = -1;
Pattern mPattern = null;
#Override
public Schema outputSchema(Schema input) {
try {
return new Schema(new Schema.FieldSchema(getSchemaName(this
.getClass().getName().toLowerCase(), input),
DataType.CHARARRAY));
} catch (Exception e) {
return null;
}
}
#Override
public String exec(Tuple tuple) throws IOException {
if (numParams==-1) // Not initialized
{
numParams = tuple.size();
if (numParams <= 2) {
String msg = "Decode: Atleast an expression and default string is required.";
throw new IOException(msg);
}
if (tuple.size()%2!=0) {
String msg = "ItssPigUDFs.ReDecode : Some parameters are unmatched.";
throw new IOException(msg);
}
}
if (tuple.get(0)==null)
return null;
try {
for (int count = 1; count < numParams - 1; count += 2)
{
mPattern=Pattern.compile((String)tuple.get(count));
if (mPattern.matcher((String)tuple.get(0)).matches())
{
return (String)tuple.get(count+1);
}
}
} catch (ClassCastException e) {
warn("ItssPigUDFs.ReDecode : Data type error", PigWarning.UDF_WARNING_1);
return null;
} catch (NullPointerException e) {
String msg = "ItssPigUDFs.ReDecode : Encounter null in the input";
throw new IOException(msg);
}
return (String)tuple.get(tuple.size()-1);
}
Thank you for your help
I don't think numParams is needed; the number of params that you get to the UDF will be input.size().
Therefore, if you call MYUDF(myVar, C), then you should be able to get those values in Java like String myVar = (String) input.get(0) and Tuple param2 = input.get(1).

p-value calculation using Java

I want to make a Java program to calculate the P-value of my data that I want to upload, but getting too much trouble to do so. The data is been read by the Java program, but next step is to solve data for getting p-value.
The input file is:
The input Should be:-
Name A B C
a 1.7085586 0.73179674 3.3962722
b 0.092749596 -0.10030079 -0.47453594
c 1.1727467 0.15784931 0.0572958
d -0.91714764 -0.62808895 -0.6190882
e 0.34570503 0.10605621 0.30304766
f 2.333506 -0.2063818 0.4022169
g 0.7893815 1.449388 1.5907407
And the Output should be like this:-
Name pValue
a 0.129618298
b 0.4363544
c 0.323631285
d 0.017916658
e 0.076331828
f 0.385619995
g 0.035449488
I have run this data in R program but I want to write some Java to solve this.
My Java code till now is:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Abc {
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:/Documents and Settings/Admin/Desktop/test.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
//output = BufferedReader.getParser().getAsDoubleArray("br");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
This is only reading my data and showing it in the console of Java. How to proceed?
I think your are facing problem with retrieving and printing values from file. Below program gives output in required format :
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Abc {
public static void main(String[] args) {
BufferedReader br = null;
String sCurrentLine;
try {
br = new BufferedReader(new FileReader("C:/Documents and Settings/Admin/Desktop/test.txt"));
// Override Default Header Row
br.readLine();
System.out.println("Name" + "\t" + "pValue");
while ((sCurrentLine = br.readLine()) != null) {
int i = 0;
String str[] = sCurrentLine.split("\t");
System.out.print(str[i] + "\t");
Double dValue1 = Double.parseDouble(str[++i]);
Double dValue2 = Double.parseDouble(str[++i]);
Double dValue3 = Double.parseDouble(str[++i]);
// Do pValue Calc here
Double pValue = 1.2334;
System.out.println(pValue);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}

Pulling this custom readDataFile function into Eclipse to print .dat file data to console

Goal: Get the data from a .dat file and print it to the console in Eclipse
Resources: fpfret.java and PointF.java and dichromatic.dat
I have resolved all my issues and have just a few console errors, here's my code and my question is: How do I add the getCodeBase() method?
package frp3;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.EOFException;
import java.net.URL;
import java.util.Vector;
public class FileRead {
public static void main(String[] args) { //getDocumentBase
System.out.println(readDataFile(getCodeBase() + "dichromatic.dat", 300, 750));
}
private static String getCodeBase() {
// TODO Auto-generated method stub
return null;
}
#SuppressWarnings("unchecked")
private static PointF[] readDataFile(String filename, int min, int max) {
#SuppressWarnings("rawtypes")
Vector v = new Vector();
try {
DataInputStream dis = new DataInputStream(new BufferedInputStream((new URL(filename)).openStream()));
float f0, f1;
while (true) {
try {
f0 = dis.readFloat();
f1 = dis.readFloat();
if (min < 0 || max < 0 || (f0 >= min && f0 <= max)) {
v.addElement(new PointF(f0, f1));
}
}
catch (EOFException eof) {
break;
}
}
}
catch (Exception e) {
e.printStackTrace();
}
PointF[] array = new PointF[v.size()];
for (int i = 0; i < v.size(); i++) {
array[i] = (PointF) v.elementAt(i);
}
return array;
}
}
Here's my console errors:
java.net.MalformedURLException: no protocol: nulldichromatic.dat
at java.net.URL.<init>(Unknown Source)
at java.net.URL.<init>(Unknown Source)
at java.net.URL.<init>(Unknown Source)
at frp3.FileRead.readDataFile(FileRead.java:27)
at frp3.FileRead.main(FileRead.java:12)
[Lfrp3.PointF;#29be513c
Here's my Project View in Eclipse:
Alright. This is actually more complex then I thought at first pass. Basically, readDataFile expects the dichromatic.dat file to be a resource available on the Internet. Look at the following line from readDataFile:
DataInputStream dis = new DataInputStream(new BufferedInputStream((new URL(filename)).openStream()));
Basically, whatever filename gets passed in, is used as a URL. For your use-case, where your file is hosted on your local filesystem, I recommend a few changes.
First, replace the above DataInputStream declaration line with:
DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(filename)));
Second, replace getCodeBase with:
private static String getCodeBase() {
return "";
}
I've simply replace null with an empty string. Since "dichromatic.dat" is in the root of your project, it should be sufficient to use an empty string, indicating project root, as the result for getCodeBase(), as the result of that function gets pre-pended to "dichromatic.dat" before being passed to readDataFile as filename.
If you put dichromatic.dat in a different place, just modify that empty string to be the "path" that leads to the file.
Hope this helps.
Forgot to mention -- be sure to update your imports list to include import java.io.FileInputStream -- although Eclipse should handle this gracefully for you.

Resources