Logic: Display drop down (data from TABLE_ONE) in page1.amx and based on the selection it needs to get data from TABLE_TWO, then render the retrieved data into page2.amx. Below is the sample which I have tried,
I have created service class ServiceClass.java in my service package and created DataControl (ServiceClassDC) for that class.
From my FirstPage.amx I'm calling service class method using valueChangeListener in drop down (Drop down value will be populated from DB, let's take TABLE_ONE ID). Below is the piece of code for this logic,
FirstPage.amx
<amx:selectOneChoice value="#{bindings.selectId.inputValue}" label="Select Id" id="soc1"
valueChangeListener="#{ServiceClass.callThisMethod}">
<amx:selectItems value="#{bindings.selectId.items}" id="si1"/>
</amx:selectOneChoice>
Based on the selection using WHERE condition, I got the list of objects in productList which is having the result set data.
ServiceClass.java
public void callThisMethod(ValueChangeEvent valueChangeEvent) {
System.out.println("Selected Value: "+valueChangeEvent.getNewValue());
String selectedValue = valueChangeEvent.getNewValue().toString();
ClassMappingDescriptor descriptor = ClassMappingDescriptor.getInstance(TableTwo.class);
DBPersistenceManager pm = getLocalPersistenceManager();
try{
StringBuffer sql = pm.getSqlSelectFromPart(descriptor);
sql.append(" WHERE ID='"+selectedValue+"'");
sql = pm.constructOrderByClause(sql, descriptor);
ResultSet set = pm.executeSqlSelect(sql.toString(), new ArrayList());
System.out.println("Result set >> "+set);
List productList = pm.createEntitiesFromResultSet(set, (List) descriptor.getAttributeMappingsDirect());
System.out.println("productList "+productList);
} catch(Exception exp){
System.out.println("Exception : "+exp);
}
}
Now, I want to display the List object data (productList) into SecondPage.amx screen. How to do this?
Please comment below, if you want any more details regarding this.
You need to expose your List productList in a public method (so provide a get method) and expose that method in a Data Control. You can then drag and drop it on your page.
Example:
public Product[] getProductArray() {
return (Product[]) productList.toArray();
}
Note that this is an example from a MAF version where Java 1.4 was used!
Related
currently I am programming a stocks project for my Bachelor degree, but I'm stuck.
For Frontend I use Angular and Backend Java with a Postgres DB.
I'm getting a 500 response when I try to update a row in my DB. The error is
org.glassfish.jersey.server.ContainerException: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "empty" (class org.json.JSONObject), not marked as ignorable (0 known properties: ])
In Angular I have a Watchlist Interface, which I want to update with an additional investment in it, send the new Watchlist to the backend, to store it in the db.
export interface Watchlist{
id?: number,
userid?: number,
watchlist?: any
}
on button click in the template I access the following method.
hinzufuegenWatchlist(){
this.mainComponent.watchlist.watchlist[this.isin] = this.investment;
this.watchlistService.sendRequestUpdateWatchlist(this.mainComponent.watchlist)
.subscribe(response => console.log('Investment zur Watchlist hinzugefügt'));
}
sendRequestUpdateWatchlist(watchlist : Watchlist){
return this.http
.put<Investment>(this.getServiceURL().concat("updateWatchlist"), JSON.stringify(watchlist),this.getOptions())
}
In the backend I use a JSONObject for the watchlist. The idea is to store every investment with its isin as an accessible key, to easily check whether its already stored or not. And easily store the whole watchlist in one row in the DB:
public class Watchlist {
private int id;
private int userid;
private JSONObject watchlist;
#PUT
#Path("updateWatchlist")
#Consumes({MediaType.APPLICATION_JSON})
public void updateWatchlist(Watchlist watchlist){
try {
String sql = "UPDATE watchlistdb set watchlist=? where id=?";
PreparedStatement ps = DatabaseHelper.connectDatabase().prepareStatement(sql);
ps.setString(1,watchlist.getWatchlist().toString());
ps.setInt(2,watchlist.getId());
ps.execute();
} catch (Exception e){
e.printStackTrace();
}
}
My first thoughts are, that it can't be mapped because it isn't a standard Java type like string or int. But how can I solve that problem?
Thank you for your time and help!
I am currently reworking an ADF Fusion Web application using Jdev v12.2.1.4.0 (Oracle 12c).
On one of the jsf pages I have a SelectOneChoice inside a table column. The jsf-implementation looks like this:
<af:column
headerText="#{ManagedBean.column5HeaderText}"
sortable="false"
visible="true"
id="c5">
<af:selectOneChoice
binding="#{ManagedBean.bindingErrorCaseSelectOneChoice}"
label="error case"
unselectedLabel="---"
autoSubmit="true"
id="soc1">
<f:selectItems value="#{ManagedBean.errorCases}" id="si1"/>
</af:selectOneChoice>
</af:column>
I left out the required attribute because it is not necessary for the process to select a value here.
The coherent parts of my ManagedBean.java are as following:
//declaring
private RichSelectOneChoice bindingErrorCasesSelectOneChoice;
private List<SelectItem> errorCases = new ArrayList<SelectItem>();
//...
//populating errorCases List from a database
public void getErrorCasesFromDB() {
errorCases= new ArrayList<SelectItem>();
try {
//HC is a helper class to connect to a specific database
Conection conn = HC.getConn();
PreparedStatement pstmt = conn.prepareStatement("some SQL");
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
errorCases.add(new SelectItem("i"+ rs.getRow(), rs.getString(1)));
}
conn.close();
} catch(Exception e) {
e.printStackTrace();
}
}
As I run the jsf page the SelectOneChoices inside the table get rendered and all the expected items are enlisted. I am facing a problem whenever i try to access the selected item of the SelectOneChoice.
I want to read the value of the selectedItem when I hit a button on the page, so I figured I could leave out having to deal with that in a valueChangeListener, and did the following in my button action:
public void buttonSaveReceivedResults(ActionEvent actionEvent) {
//...
if (bindingErrorCaseSelectOneChoice.getValue != null) {
//... insert the selected value into an SQL statement
//in the case the unselected label is selected, skip
System.out.println(bindingErrorCasesSelectOneChoice.getValue().toString())
}
}
This block always gets skipped. Also when i inspected the process, the getValue() call always returned null, even if i select an item from the list.
Now i'm asking you guys, where is the missing part in the chain? Did I do the data bindings correctly. Do I access the elements in the wrong way? Thanks in advance.
The value attribute stores the output of af:selectOneChoice component. Since you have not added it, value returned was null.
Trying to use a similar example from the sample code found here
My sample function is:
void query()
{
String nodeResult = "";
String rows = "";
String resultString;
String columnsString;
System.out.println("In query");
// START SNIPPET: execute
ExecutionEngine engine = new ExecutionEngine( graphDb );
ExecutionResult result;
try ( Transaction ignored = graphDb.beginTx() )
{
result = engine.execute( "start n=node(*) where n.Name =~ '.*79.*' return n, n.Name" );
// END SNIPPET: execute
// START SNIPPET: items
Iterator<Node> n_column = result.columnAs( "n" );
for ( Node node : IteratorUtil.asIterable( n_column ) )
{
// note: we're grabbing the name property from the node,
// not from the n.name in this case.
nodeResult = node + ": " + node.getProperty( "Name" );
System.out.println("In for loop");
System.out.println(nodeResult);
}
// END SNIPPET: items
// START SNIPPET: columns
List<String> columns = result.columns();
// END SNIPPET: columns
// the result is now empty, get a new one
result = engine.execute( "start n=node(*) where n.Name =~ '.*79.*' return n, n.Name" );
// START SNIPPET: rows
for ( Map<String, Object> row : result )
{
for ( Entry<String, Object> column : row.entrySet() )
{
rows += column.getKey() + ": " + column.getValue() + "; ";
System.out.println("nested");
}
rows += "\n";
}
// END SNIPPET: rows
resultString = engine.execute( "start n=node(*) where n.Name =~ '.*79.*' return n.Name" ).dumpToString();
columnsString = columns.toString();
System.out.println(rows);
System.out.println(resultString);
System.out.println(columnsString);
System.out.println("leaving");
}
}
When I run this in the web console I get many results (as there are multiple nodes that have an attribute of Name that contains the pattern 79. Yet running this code returns no results. The debug print statements 'in loop' and 'nested' never print either. Thus this must mean there are not results found in the Iterator, yet that doesn't make sense.
And yes, I already checked and made sure that the graphDb variable is the same as the path for the web console. I have other code earlier that uses the same variable to write to the database.
EDIT - More info
If I place the contents of query in the same function that creates my data, I get the correct results. If I run the query by itself it returns nothing. It's almost as the query works only in the instance where I add the data and not if I come back to the database cold in a separate instance.
EDIT2 -
Here is a snippet of code that shows the bigger context of how it is being called and sharing the same DBHandle
package ContextEngine;
import ContextEngine.NeoHandle;
import java.util.LinkedList;
/*
* Class to handle streaming data from any coded source
*/
public class Streamer {
private NeoHandle myHandle;
private String contextType;
Streamer()
{
}
public void openStream(String contextType)
{
myHandle = new NeoHandle();
myHandle.createDb();
}
public void streamInput(String dataLine)
{
Context context = new Context();
/*
* get database instance
* write to database
* check for errors
* report errors & success
*/
System.out.println(dataLine);
//apply rules to data (make ContextRules do this, send type and string of data)
ContextRules contextRules = new ContextRules();
context = contextRules.processContextRules("Calls", dataLine);
//write data (using linked list from contextRules)
NeoProcessor processor = new NeoProcessor(myHandle);
processor.processContextData(context);
}
public void runQuery()
{
NeoProcessor processor = new NeoProcessor(myHandle);
processor.query();
}
public void closeStream()
{
/*
* close database instance
*/
myHandle.shutDown();
}
}
Now, if I call streamInput AND query in in the same instance (parent calls) the query returns results. If I only call query and do not enter ANY data in that instance (yet web console shows data for same query) I get nothing. Why would I have to create the Nodes and enter them into the database at runtime just to return a valid query. Shouldn't I ALWAYS get the same results with such a query?
You mention that you are using the Neo4j Browser, which comes with Neo4j. However, the example you posted is for Neo4j Embedded, which is the in-process version of Neo4j. Are you sure you are talking to the same database when you try your query in the Browser?
In order to talk to Neo4j Server from Java, I'd recommend looking at the Neo4j JDBC driver, which has good support for connecting to the Neo4j server from Java.
http://www.neo4j.org/develop/tools/jdbc
You can set up a simple connection by adding the Neo4j JDBC jar to your classpath, available here: https://github.com/neo4j-contrib/neo4j-jdbc/releases Then just use Neo4j as any JDBC driver:
Connection conn = DriverManager.getConnection("jdbc:neo4j://localhost:7474/");
ResultSet rs = conn.executeQuery("start n=node({id}) return id(n) as id", map("id", id));
while(rs.next()) {
System.out.println(rs.getLong("id"));
}
Refer to the JDBC documentation for more advanced usage.
To answer your question on why the data is not durably stored, it may be one of many reasons. I would attempt to incrementally scale back the complexity of the code to try and locate the culprit. For instance, until you've found your problem, do these one at a time:
Instead of looping through the result, print it using System.out.println(result.dumpToString());
Instead of the regex query, try just MATCH (n) RETURN n, to return all data in the database
Make sure the data you are seeing in the browser is not "old" data inserted earlier on, but really is an insert from your latest run of the Java program. You can verify this by deleting the data via the browser before running the Java program using MATCH (n) OPTIONAL MATCH (n)-[r]->() DELETE n,r;
Make sure you are actually working against the same database directories. You can verify this by leaving the server running. If you can still start your java program, unless your Java program is using the Neo4j REST Bindings, you are not using the same directory. Two Neo4j databases cannot run against the same database directory simultaneously.
iam trying to orderlookup droplet API by passing some parameters.I assume that the parameters which are mandatory is userId and organisationIds which i have passed and additionally i have also passed "state" parameter.All these params are passed thru request and then the service method of droplet is invoked.But the service method returns nothing.My goal is to check whether this droplet this retrieving the expected set of orders or not.We can use droplet invoker but i tried that way but it didnt work may be i missed something.Please help me out!!
this is my code when i tried to use OrderLookUp API
DynamoHttpServletRequest request = ServletUtil.getCurrentRequest();
mTestService.setCurrentRequest(request);
if (request == null) {
mTestService.vlogError("Request is null.");
Assert.fail("Request is null ");
}
else
{
Object droplet = mTestService
.getRequestScopedComponent("OrderLookupDroplet");
OrderLookupDroplet=(OrderLookup) droplet;
request.setParameter("state", "submitted");
request.setParameter("organisationIds", organizationIds);
request.setParameter("userId", userId);
ByteBuffer buffer = ByteBuffer.allocate(1024);
DynamoHttpServletRequest dynRequest = (DynamoHttpServletRequest) request;
TestingDynamoHttpServletRequest wrappedRequest = new TestingDynamoHttpServletRequest(
dynRequest, buffer);
TestingDynamoHttpServletResponse wrappedResponce = new TestingDynamoHttpServletResponse(
dynRequest.getResponse());
OrderLookupDroplet.service(wrappedRequest, wrappedResponce);
}
the above sample is only part of the code..
this is the code when i tried using droplet invoker
DropletInvoker invoker = new DropletInvoker(mNucleus);
invoker.getRequest().setParameter("state", "submitted");
// String [] siteIds = {"siteA", "siteB"};
// invoker.getRequest().setParameter("siteIds", Arrays.asList(siteIds));
String [] organizationIds = {"OrgA", "OrgB"};
invoker.getRequest().setParameter("organizationIds", organizationIds);
String [] orderIds = {"orderautouser001OrgA" , "orderautouser001OrgB"};
invokeDroplet(invoker, "autouser001", orderIds);
......
protected void invokeDroplet(DropletInvoker pInvoker, String pUserId, String[] pOrderIds) throws Exception
{
Map<String, Object> localParams = new HashMap();
localParams.put("userId", pUserId);
DropletResult result = pInvoker.invokeDroplet("/atg/commerce/order/OrderLookup", localParams);
RenderedOutputParameter oparam = result.getRenderedOutputParameter("output", 0);
assertNotNull("'output' oparam was not rendered", oparam);
assertEquals("Check totalCount.", pOrderIds.length, oparam.getFrameParameter("totalCount"));
List<Order> orders = (List<Order>)oparam.getFrameParameter("result");
assertEquals("Check order array length.", pOrderIds.length, orders.size());
for (int index = 0; index < pOrderIds.length; index++) {
boolean found = false;
for (Order order: orders) {
if (pOrderIds[index].equals(order.getId())) {
found = true;
break;
}
}
assertTrue("Expected orderId " + pOrderIds[index] + " not found in result array", found);
}
in first case i donno how to retrieve the orders by directly using orderlookup api....and in second case though i know how to use it ,iam still failing!! please help me out..thanks in advance
You should't use droplets in java classes they should be used only inside jsp pages. Documentation of OrderLookup with example hot to use it on jsp page is here.
If you want to get orders or any other data stored in a repository you should use repository API with RQL (Repository Query Language). Example how to get data from repository you can find here and RQL grammar here.
Thanks for giving your opinions.Good news is we can invoke droplets from any other API
OrderLookup droplet = (OrderLookup) sNucleus.resolveName("/atg/commerce/order/OrderLookup");
ServletTestUtils utils = new ServletTestUtils();
mRequest = utils.createDynamoHttpServletRequestForSession(sNucleus, null, null);
ServletUtil.setCurrentRequest(mRequest);
mResponse = new DynamoHttpServletResponse();
mRequest.setResponse(mResponse);
mResponse.setRequest(mRequest);
mResponse.setResponse(new GenericHttpServletResponse());
mRequest.setParameter("userId", "publishing");
droplet.setSearchByUserId(true);
droplet.service(mRequest, mResponse);
ArrayList<Order> orders = (ArrayList<Order>) mRequest.getObjectParameter("result");
here the "result" param is output param which this droplet sets.and the userId i have hardcoded as "publishing" which i have created.Ignore servletTestUtils class that is created by me which has not much to do with droplet theory here :)
I assume from your code example, and the fact that you mention DropletInvoker that you are writing a unit test, and that this is not functional code.
If it is functional code, you really, really, should not invoke a droplet from another Nucleus component. A droplet exists solely to be used in a JSP page. If you need the functionality of the droplet in Java code, you should refactor the droplet into a service that holds the main logic, and a droplet that simply acts as a façade to the service to allow it to be invoked from a page.
In the case of the OrderLookup look droplet, you don't need to refactor anything. The service to use should be OrderManager or OrderTools depending on what you need. Note, there is a difference between Order objects and Order repository items, and you should prefer to use order objects - so only use the Order Repository directly if you really need to.
I'm new here and would be great if someone could help me with this small crisis I have been having. I have been following Jeff Sharkeys Separate List Adapter tutorial which can be found here and I got it all working appropriately to how he explains it.
My problem is I have a database, pre made one which has a table that I am trying to put the extracted data into a list view using Jeffs adapter. I need this data to be put in different sections according to the Category ID column.
The table I am currently extracting data from is the Food table, which has 6 columns, categoriID, menuID, Item, Description, price and a PK _id
My database works properly as in other activities I use a SimpleCursorAdapter to bind data to a list view. (from other tables)
I use the following method in the Database Helper class to retrieve the data I need
public List<FoodModel> getData(String catid, String menuid) {
List<FoodModel> FoodListModel = new ArrayList<FoodModel>();
Cursor cursor = myDataBase.query(FOOD_TABLE, new String [] {FOODITEM_COLUMN, FOODITEMDESCRIPTION_COLUMN,FOODPRICE_COLUMN}, "catid = ? AND menuid = ?",
new String[] { catid, menuid},null, null, null, null);
if (cursor.moveToFirst()){
do{
FoodModel FoodModel = new FoodModel();
FoodModel.setItem(cursor.getString(0));
FoodModel.setdescrription(cursor.getString(1));
FoodModel.setprice(Double.parseDouble(cursor.getString(2)));
FoodListModel.add(FoodModel);} while (cursor.moveToNext());
}
return FoodListModel;
}
the Food Model class is the standard get set class to store the cursors data.
This public method works accordingly as in my main activity (jeffs ListSample.java) I output to the log cat the required information using
Log.d("Reading: ", "Testing Cursor");
List<FoodModel> Data1 = dba.getData("1", "1");
for (FoodModel fd : Data1){
String log = "Item: "+fd.getitem()+" ,Description: " + fd.getdescription() + " ,Price: " + fd.getprice();
Log.d("Name: ", log);
This outputs a list of all the data I need to put into 1 section of the SeperateListAdapter but to the log cat
The 3 things i am trying to output to the list view are the Item, description and price.
My problem is How do I add this data to the list view under the correct section?
as oposed to manually inserting it as Jeff shows
List<Map<String,?>> security = new LinkedList<Map<String,?>>();
security.add(createItem("Remember passwords", "Save usernames and passwords for Web sites"));
security.add(createItem("Clear passwords", "Save usernames and passwords for Web sites"));
security.add(createItem("Show security warnings", "Show warning if there is a problem with a site's security"));
I didn't want to start my first experience of using this site by pasting all my classes is as this is my first time using this website, my English is not the best and it took me a while to write this I hope it is acceptable as a question, I would be really great full if someone could kindly help me or point me in the right direction.
EDIT: Will gladly post the rest of my code just didnt whant to bombard everyone with loads of information