Why does s:iterator show only one result? - java

I'd like to know why my iterator shows only one result from my jsp. Here's my code in s:iterator:
<s:iterator value="origins" var="items">
<s:select list="#items" label="Select origin" name="origin">
</s:select>
</s:iterator>
And here's my code from action:
public class QueryAction{
private Sector sectorBean = null;
private List<String> origins;
private List<String> destinations;
public List<String> getOrigins() {
return origins;
}
public void setOrigins(List<String> origins) {
this.origins = origins;
}
public List<String> getDestinations() {
return destinations;
}
public void setDestinations(List<String> destinations) {
this.destinations = destinations;
}
public String listing() {
SectorDA sda = new SectorDAImpl();
origins = sda.getOrigins();
destinations = sda.getDestinations();
return "success";
}
}
The values of both origin and destination are : New York, New Orleans, Michigan, Memphis, Chicago, and Pittsburgh. And both only showed Chicago. Can anyone help me?
-UPDATE-
I've discovered why the iterator shows only one result. It's because of the class' corresponding DA. Here are the codes:
private static final String GET_ALL_SECTORS = "SELECT cSectorId, cOrigin, cDestination, cWeekDay1, cWeekDay2, mFirstClassFare, mBusinessClassFare, mEconomyClassFare FROM Sector";
#Override
public List<Sector> getAllSectors() {
List<Sector> sectors = new ArrayList<Sector>();
Statement stat = null;
try {
stat = DatabaseConnector.getConnection().createStatement();
ResultSet rs = stat.executeQuery(GET_ALL_SECTORS);
if(rs.next()) {
String sectorId = rs.getString(1);
String origin = rs.getString(2);
String destination = rs.getString(3);
String weekDay1 = rs.getString(4);
String weekDay2 = rs.getString(5);
BigDecimal fcFare = rs.getBigDecimal(6);
BigDecimal bcFare = rs.getBigDecimal(7);
BigDecimal ecFare = rs.getBigDecimal(8);
Sector e = new Sector(sectorId, origin, destination, weekDay1, weekDay2, fcFare, bcFare, ecFare);
sectors.add(e);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if(stat != null) {
try {
stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return sectors;
}
Please help me.

Related

Logic in this method?

I am creating a java application to generate questions, and the method shown below is used to generate the questions. I have used a stack to order these questions by how many times they have appeared in the loop.
My problem is that it keeps producing multiple questions which are the same, which this method should prevent.
public ArrayList<String> generateQuestions(String transcript, String className, int classYear, String classGroup) {
ArrayList<String> results = new ArrayList<String>();
ArrayList<String> tags = new ArrayList<String>();
//get tags from the database
Statement stmt = null;
try {
stmt = handler.getConnection().createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
if(stmt != null){
try {
String result = "";
ResultSet rs = stmt.executeQuery("SELECT tags.TagName FROM class, tags, questtag, questions, questclass WHERE questtag.QuestionID = questions.QuestionID AND tags.TagID = questtag.TagID AND questions.QuestionID = questclass.QuestionID AND questclass.ClassID = class.ClassID AND class.ClassName ='"+className+"' AND class.ClassYear="+classYear+" AND class.ClassGroup ='"+classGroup+"' GROUP BY tags.TagID");
while (rs.next()) {
result = rs.getString(1);
tags.add(result);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
Stack<Question> stack = new Stack<Question>();
for (String word : transcript.split("\\s+")) {
if( ! word.equalsIgnoreCase("the") || ! word.equalsIgnoreCase("I")) {
for(String tag : tags) {
if(word.equalsIgnoreCase(tag)) {
try {
stmt = handler.getConnection().createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
if(stmt != null){
try {
String result = "";
ResultSet rs = stmt.executeQuery("SELECT questions.Question FROM class, tags, questtag, questions, questclass WHERE questtag.QuestionID = questions.QuestionID AND tags.TagID = questtag.TagID AND questions.QuestionID = questclass.QuestionID AND questclass.ClassID = class.ClassID AND class.ClassName ='"+className+"' AND class.ClassYear="+classYear+" AND class.ClassGroup ='"+classGroup+"' AND tags.TagName = '"+tag+"'");
while (rs.next()) {
result = rs.getString(1);
Stack<Question> searchStack = new Stack<Question>();
boolean multiple = false;
if(stack.isEmpty()) { //1st question we've come to
Question question = new Question(result);
stack.push(question);
} else {
while(multiple == false && !stack.isEmpty()) {
//search through the stack
searchStack.push(stack.pop());
//if question is not already in the stack
if(((Question)searchStack.peek()).getQuestion().equalsIgnoreCase(result)) {
//then it is multiple
//add one to its noOfTimes
((Question)searchStack.peek()).addToNoOfTimes();
//order this above others with lower score
if(!stack.isEmpty()) {
if(((Question)stack.peek()).getNoOfTimes() < ((Question)searchStack.peek()).getNoOfTimes()) {
Question thisQuestion = searchStack.pop();
while(((Question)stack.peek()).getNoOfTimes() < thisQuestion.getNoOfTimes() && !stack.isEmpty()) {
searchStack.push(stack.pop());
}
stack.push(thisQuestion);
} else {
stack.push(searchStack.pop());
}
}
multiple = true;
}
}
while(!searchStack.empty())
stack.push(searchStack.pop());
if(multiple == false) {
Question question = new Question(result);
stack.push(question);
}
}
}
} catch (SQLException e) {
e.printStackTrace();
}
Stack<Question> reorderStack = new Stack<Question>();
while(!stack.empty()) {
reorderStack.push(stack.pop());
}
while(!reorderStack.empty()) {
Question thisQuestion = reorderStack.pop();
results.add(thisQuestion.getQuestion());
stack.push(thisQuestion);
}
}
}
}
}
}
return results;
}

Freemarker template not able to parse the Java object

I have a POJO (the class has getters set for each field) which i am sending back to a variable in a different class where the template configuration is done. Somehow i am getting an error when the ftl tries to populate the view.
I don't know how to present an object of this type to a template: org.test.config.TransformerInfoBuilder. Here is the code where the error comes from:
[line 13, column 5 in templates/ConfigMain.ftl]
list TransformerInfoBuilders as TransformerInfoBuilder
Java error stacktrace:
freemarker.template.TemplateModelException: Don't know how to present an object of this type to a template: org.test.config.TransformerInfoBuilder
at freemarker.template.SimpleObjectWrapper.handleUnknownType(SimpleObjectWrapper.java:139)
at freemarker.template.SimpleObjectWrapper.wrap(SimpleObjectWrapper.java:116)
at freemarker.template.WrappingTemplateModel.wrap(WrappingTemplateModel.java:131)
at freemarker.template.SimpleSequence.get(SimpleSequence.java:197)
at freemarker.template.IteratorBlock$Context.runLoop(IteratorBlock.java:163)
at freemarker.template.Environment.visit(Environment.java:316)
at freemarker.template.IteratorBlock.accept(IteratorBlock.java:94)
at freemarker.template.Environment.visit(Environment.java:180)
at freemarker.template.IfBlock.accept(IfBlock.java:81)
at freemarker.template.Environment.visit(Environment.java:180)
at freemarker.template.MixedContent.accept(MixedContent.java:91)
at freemarker.template.Environment.visit(Environment.java:180)
at freemarker.template.Environment.process(Environment.java:166)
at freemarker.template.Template.process(Template.java:238)
at org.mule.config.ConfigLoader.main(ConfigLoader.java:116)
The ftl is as below.
<#if TransformerInfoBuilders?has_content>
<#list TransformerInfoBuilders as TransformerInfoBuilder>
<flow name="${TransformerInfoBuilder.id}">
</flow>
</#list>
<#else>
no content
</#if>
Java class for creating the object.
public class TransformerInfoBuilder {
String id="";
String name="";
String returnClass="";
String ignoreBadInput="";
String encoding="";
String mimeType="";
String templateName="";
public TransformerInfoBuilder(String id, String name,String returnClass, String encoding, String ignoreBadInput)
{
this.id=id;
this.name=name;
this.returnClass=returnClass;
this.encoding=encoding;
this.ignoreBadInput=ignoreBadInput;
}
public void setid(String id)
{
this.id=id;
}
public void setname(String name)
{
this.name=name;
}
public String getname()
{
return this.name;
}
public String getid()
{
return this.id;
}
public String getreturnClass()
{
return this.returnClass;
}
public String getignoreBadInput()
{
return this.ignoreBadInput;
}
public String getencoding()
{
return this.encoding;
}
}
Java class where the call to configurator is made:
public class ConfigLoader {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException, IOException {
Configuration cfg = new Configuration();
Template template = cfg.getTemplate("/templates/ConfigMain.ftl");
Connection dbconn=null;
Statement stmt=null;
ResultSet rs= null;
String id="";
HashMap<String,Map<String,String>> tinfo= new HashMap<String,Map<String,String>> ();
List<String> flowList = new ArrayList<String>();
List<TransformerInfoBuilder> TransformerInfoBuilders = new ArrayList<TransformerInfoBuilder>();
//Map<String,Object> flistfinal = new HashMap<String,Object>();
Map<String, Object> data = new HashMap<String, Object>();
List<Map<String,ArrayList<String>>> mapsfinal = new ArrayList<Map<String,ArrayList<String>>>();
try {
// Load the template
String configId =args[0];
System.out.println("+++++++++++++++++++++++configID is " + configId + " +++++++++++++++++++++++");
dbconn=DBConnection.connection();
System.out.println("\n\n++++++++++++++++++ Obtained DB connection ++++++++++++++++");
stmt = dbconn.createStatement();
System.out.println("\n\n++++++++++++++++++ Querying for Config Application Name ++++++++");
rs = stmt.executeQuery("SELECT * FROM FlowInfo where ConfigFileId =" + configId);
while (rs.next()) {
id = rs.getString("FlowID");
flowList.add(id);
}
TransformerInfoBuilders=Transformer.TransformerInfo(flowList);
data.put("TransformerInfoBuilders",TransformerInfoBuilders);
data.put("message","#[payload]");
Writer writer = new FileWriter("output/MainConfig.xml");
template.process(data, writer);
writer.flush();
writer.close();
//out.flush();
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException et) {
et.printStackTrace();
}finally {
try { if (rs != null) rs.close(); } catch (SQLException e) { e.printStackTrace(); }
try { if (stmt != null) stmt.close(); } catch (SQLException e) { e.printStackTrace(); }
try { if (dbconn != null) dbconn.close(); } catch (SQLException e) { e.printStackTrace(); }
}
}
}
Any pointers on what i might be doing wrong over here??
Thanks
Salim
After extending the DefaultObjectWrapper class the problem was solved. I had to upgrade it to a higher version of Freemarker.jar.

Fetching nodes with a label and index using cypher

I want to fetch node and its information using label and index using cypher query but still i get null value in variable "result" in CypherQuery() method.
NewCypherQuery.java (bean)
public class NewCypherQuery {
private static final String DB_PATH = "/var/lib/neo4j/data/";
private static String resultString;
private static String columnsString, nodeResult, rows = "", query;
private static ExecutionResult result;
private static ExecutionEngine engine;
private static GraphDatabaseService db;
private static Node amad = null, pari = null, sona = null;
private static Relationship rel;
private static IndexDefinition inxamd, inxpri;
private static Label amd,pri;
public static void callAllMethods() {
clearDbPath();
setUp();
createNodes();
CypherQuery();
}
public static void CypherQuery() {
try (Transaction ignored = db.beginTx();) {
result = engine.execute("MATCH (m:inxamd)-->(n:inxpri) USING INDEX m:inxamd(name) USING INDEX n:inxpri(name) WHERE m.name = 'Amad' AND n.name= 'Pari' RETURN m");
for (Map<String, Object> row : result) {
resultString = engine.execute("MATCH (m:inxamd)-->(n:inxpri) USING INDEX m:inxamd(name) USING INDEX n:inxpri(name) WHERE m.name = 'Amad' AND n.name= 'Pari' RETURN m").dumpToString();
System.out.println(resultString);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void setUp() {
try {
db = new GraphDatabaseFactory().newEmbeddedDatabase(DB_PATH);
try (Transaction tx = db.beginTx()) {
engine = new ExecutionEngine(db);
Schema schema = db.schema();
inxamd = schema.indexFor(amd).on("name").create();
inxpri = schema.indexFor(pri).on("name").create();
tx.success();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static void createNodes() {
try (Transaction tx = db.beginTx();) {
amad = db.createNode();
amad.setProperty("name", "Amad");
amad.setProperty("age", 24);
amad.setProperty("edu", "mscit");
pari = db.createNode();
pari.setProperty("name", "Pari");
pari.setProperty("age", 20);
pari.setProperty("edu", "mscit");
sona = db.createNode();
sona.setProperty("name", "Sona");
sona.setProperty("age", 21);
sona.setProperty("edu", "mscit");
rel = amad.createRelationshipTo(pari, RelTypes.KNOWS);
rel.setProperty("rel", "friend");
rel = pari.createRelationshipTo(sona, RelTypes.KNOWS);
rel.setProperty("rel", "friend");
System.out.println("Nodes created.....");
tx.success();
} catch (Exception e) {
e.printStackTrace();
}
}
private static void clearDbPath() {
try {
deleteRecursively(new File(DB_PATH));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
InsertNodes.java (Servlet):-
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
NewCypherQuery ncq=new NewCypherQuery();
ncq.callAllMethods();
}
index.jsp
<form method="post" action="InsertNodes">
<input type="text" name="txtname" value="Hello World !!!!!"></input>
<input type="submit" value="Neo4j World"></input>
</form>
You haven't really defined values for the two labels amd (inxamd) and pri (inxpri) and nor have you assigned them to any nodes created.
You can either implement the Label class and assign a name to a label such as "inxamd" or use DynamicLabel.
Then, assign the label to your node using
amad.addLabel(thelabel);
Unrelated to your issue above, a label name is usually a descriptive string indicating what set the node belongs to e.g. Person, Dog
And in most cases you don't need to explicitly provide the index hint (USING INDEX)

Getting null value from table

i have a piece of jsp code . this code takes data from a table and displays it on a console
For integer values it is working good but for String values it displays null
the issue is not with the table . i have tried other tables also but same result
jsp code :
<%
int mots_id = 0 ;
String mots_name = "" ;
String accesstype = "" ;
GetAccess obj = new GetAccess();
List<GetAccessVO> accesslist = obj.access(attUID);
if(accesslist!=null)
{
Iterator<GetAccessVO> iter = accesslist.iterator();
while(iter.hasNext())
{
GetAccessVO getaccessVO = iter.next();
mots_id = getaccessVO.getmotsid();
String mots_name = getaccessVO.getmotsname();
String accesstype = getaccessVO.getaccess();
out.println(accesstype); // it displays null
}
}
%>
java code :
public class GetAccess{
final static DBConnection db=new DBConnection();
public List<GetAccessVO> access(String attuid)
{
List<GetAccessVO> accesslist = new ArrayList<GetAccessVO>();
try
{
Connection con = db.getConnection();
String query ="select mots_id ,mots_name,access_type from ENV_TEAM where userid = ?";
PreparedStatement pstmt = con.prepareStatement(query);
pstmt.setString(1, attuid);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{
GetAccessVO getaccessVO = new GetAccessVO();
getaccessVO.setmotsid(rs.getInt(1));
getaccessVO.setmotsname(rs.getString(2));
getaccessVO.setaccess(rs.getString(3));
accesslist.add(getaccessVO);
}
rs.close();
pstmt.close();
con.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return accesslist;
}
}
the setter getter class :
public class GetAccessVO {
private int mots_id;
private String mots_name;
private String access;
public String getmotsname() {
return mots_name;
}
public void setmotsname(String mots_name) {
this.mots_name = mots_name;
}
public int getmotsid() {
return mots_id;
}
public void setmotsid(int mots_id) {
this.mots_id = mots_id;
}
public String getaccess() {
return access;
}
public void setaccess(String access) {
this.access = access;
}
}
i have tried almost everything but the String values always are null
SQL> select * from env_team ;
USERID MOTS_ID MOTS_NAME ACCESS_TYPE
------- ---------- ------------------------------ ------------------------------
as045e 7921 BDS external

update data from jTable to database -null pointer exception error

Im trying to read values from my jTable1
private void jcmdOKActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
int colum=jTable1.getSelectedColumn();
int row=jTable1.getSelectedRow();
System.out.println("row of selected is "+row+"col is "+colum);
final String remark1 = (String) jTable1.getValueAt(row, 8);
final String remark2 = (String) jTable1.getValueAt(row, 9);
final String invoiceno = (String) jTable1.getValueAt(row, 11);
final String id=(String) jTable1.getValueAt(row, 12);
System.out.println(id + "id");
try{
Transaction t = new Transaction(s) {
public Object transact() throws BasicException {
System.out.println("try loop for update");
SentenceExec followinsert = new PreparedSentence(s
, "UPDATE FOLLOWUP SET REMARK1= ?, REMARK2=?, INVOICENO=? WHERE ID= ?"
, SerializerWriteParams.INSTANCE);
followinsert.exec(new DataParams() { public void writeValues() throws BasicException {
System.out.println("executing command");
setString(1, remark1);
setString(2, remark2);
setString(3, invoiceno);
setString(2, id);
//System.out.println(" after update line");
}});
return null;
}
};
t.execute(); //im getting null pointer exception here :(
}
catch (BasicException ex) {
Logger.getLogger(FollowUp.class.getName()).log(Level.SEVERE, null, ex);
}
}
i get this error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at com.openbravo.data.loader.Transaction.execute(Transaction.java:42)
at com.openbravo.pos.followup.FollowUp.jcmdOKActionPerformed(FollowUp.java:679)
at com.openbravo.pos.followup.FollowUp.access$300(FollowUp.java:66)
at com.openbravo.pos.followup.FollowUp$5.actionPerformed(FollowUp.java:193)
Transaction.java is
public abstract class Transaction<T> {
private Session s;
/** Creates a new instance of Transaction */
public Transaction(Session s) {
this.s = s;
}
public final T execute() throws BasicException {
if (s.isTransaction()) {
return transact();
} else {
try {
try {
s.begin();
T result = transact();
s.commit();
return result;
} catch (BasicException e) {
s.rollback();
throw e;
}
} catch (SQLException eSQL) {
throw new BasicException("Transaction error", eSQL);
}
}
}
protected abstract T transact() throws BasicException;
}

Categories