retrieve data from couchdb - java

I am new couchdb user and I am using lightcouch API.
currently, I can get data from couchdb, but what I can get is not I need. You can see the following code: username value and password value are stored, and these two values are needed to store into jsonarray.
However, the problem is when I tried to print the data, it only showing me this:
{"id":"0a3f38cfc5ca45d6bcd76725faf5b917","key":"0a3f38cfc5ca45d6bcd76725faf5b917","value":{"rev":"1-32d4a8325e8995d0eddd5b2626b752df"}}.
The problem is that I can not get username and password. BTW, another question is, when the servlet send jsonarray for example named data, how does the jquery get the message and username from data.
CouchDbProperties properties = new CouchDbProperties(
"db_test",
true,
"http",
"127.0.0.1",
5984, null, null);
CouchDbClient dbClient2 = new CouchDbClient(properties);
Map<String, Object> map = new HashMap<>();
map.put("username", "justin");
map.put("message", "hello world");
dbClient2.save(map);
List<JsonObject> jsonList = dbClient2.view("_all_docs").query(JsonObject.class);
for (int i=0; i< jsonList.size(); i++){
System.out.println(jsonList.get(i));
}

You can have "views" specified in CouchDb, in that case instead of "_all_docs" you would give your view path "_design/something/_view/someview".
More about views https://wiki.apache.org/couchdb/Introduction_to_CouchDB_views
Or look into "_all_docs?include_docs=true", since "_all_docs" does not return data itself, just documents info like ids.

Related

How do I use the Grafana client for java to upload dashboards with a time-series filled panel to Grafana?

I am currently comparing time-series. They are stored in InfluxDB. My task is to get two time-series from InfluxDB, compare them and upload a visualization to Grafana. The comparison result would be output to console and the two time-series would be uploaded to Grafana in a dashboard and they should be in the same panel. I am trying to use the grafana-api-java-client found here. My problem is that I can not figure out how to do this with the provided examples and Javadocs. There is not a lot of documentation and the examples don't work properly in my case. I hope that someone has worked with this client and can explain how to properly add two time-series to a panel in a dashboard and upload it.
I will provide what I am doing and then post the examples from the github page of the API.
First of all this is how I am getting my time series:
public List<Double> getTimeSeries(String streetName, String start, String stop) {
//gets the query result
QueryResult queryResult = influxDB.query(new Query(String.format("SELECT value FROM your_measurement WHERE street='%s' " +
"AND time >= '%s' AND time <= '%s'", streetName, start, stop)));
//Gets the values from the query result
List<List<Object>> values = queryResult.getResults().iterator().next().getSeries().iterator().next().getValues();
//Adds the values to a list
List<Double> timeSeries = new ArrayList<>();
for (List<Object> li : values) {
timeSeries.add(Double.valueOf(li.get(1).toString()));
}
return timeSeries;
}
I can convert this list to an array of doubles:
double[] timeSeriesArray = timeSeries.stream().mapToDouble(d -> d).toArray();
The following is the first example. It works properly up until the getDashboard() and deleteDashboard() methods, where I get the error that such a dashboard does not exist, even though it does. I don't know what causes this error. Every new dashboard ends up in the folder "General". The method createDashboard() creates, as expected, an empty dashboard in Grafana.
import com.appnexus.grafana.client.GrafanaClient;
//Setup the client
GrafanaConfiguration grafanaConfiguration =
new GrafanaConfiguration().host("your_grafana_host").apiKey("Bearer your_secret_key");
GrafanaClient grafanaClient = new GrafanaClient(grafanaConfiguration);
//Setup the dashboard
String DASHBOARD_NAME = "new_dashboard";
Dashboard dashboard = new Dashboard()
.title(DASHBOARD_NAME)
.version(0);
GrafanaDashboard grafanaDashboard = new GrafanaDashboard().dashboard(dashboard);
//Make API calls
grafanaClient.createDashboard(grafanaDashboard);
grafanaClient.getDashboard(DASHBOARD_NAME);
grafanaClient.deleteDashboard(DASHBOARD_NAME);
This is the second example. I assume that I have to modify it in order to solve my problem. I had to replace two things to get this example to work, which I will explain with code comments. When executing this code it creates a dashboard with an empty panel. I expected something to be shown on the panel but it is empty and there are no axes.
import com.appnexus.grafana.client.GrafanaClient;
//Setup the client
GrafanaConfiguration grafanaConfiguration =
new GrafanaConfiguration().host("your_grafana_host").apiKey("Bearer your_secret_key");
GrafanaClient grafanaClient = new GrafanaClient(grafanaConfiguration);
//Setup the dashboard
String DASHBOARD_NAME = "new_dashboard";
DashboardPanelTarget dashboardPanelTarget =
new DashboardPanelTarget().refId("getSomeMetric").target("*");
DashboardPanelXAxis dashboardPanelXAxis =
new DashboardPanelXAxis().show(true).mode(DashboardPanelXAxis.Mode.TIME);
DashboardPanelYAxis dashboardPanelYAxis =
new DashboardPanelYAxis().format(DashboardPanelYAxis.Format.SHORT).logBase(1).show(true);
//Datasource is required or alerts cannot be added
DashboardPanel dashboardPanel =
new DashboardPanel()
//This might be where my data has to go but I am not sure.
.targets(new ArrayList<>(Collections.singletonList(dashboardPanelTarget)))
//Had to change DASHBOARD_DATA_SOURCE to a String -> "DASHBOARD_DATA_SOURCE", I assume it's just the name of the datasource.
//.datasource(DASHBOARD_DATA_SOURCE)
.datasource("DASHBOARD_DATA_SOURCE")
.type(DashboardPanel.Type.GRAPH)
.fill(1)
.title(dashboardName)
.linewidth(1)
.lines(true)
.height("300px")
.span(12)
.xaxis(dashboardPanelXAxis)
.yaxes(new ArrayList<>(Arrays.asList(dashboardPanelYAxis, dashboardPanelYAxis)));
DashboardRow dashboardRow =
new DashboardRow()
.collapse(false)
.panels(new ArrayList<>(Collections.singletonList(dashboardPanel)));
Dashboard dashboard =
new Dashboard()
.title(dashboardName)
.schemaVersion(1)
.rows(new ArrayList<>(Collections.singletonList(dashboardRow)));
DashboardMeta dashboardMeta = new DashboardMeta().canSave(true).slug(dashboardName);
GrafanaDashboard grafanaDashboard =
new GrafanaDashboard().meta(dashboardMeta).dashboard(dashboard);
//create new dashboard
//Had to change createDashboardTest() to createDashboard(), because createDashboardTest() doesn't seem to exist
//DashboardMeta createdDashboardMeta = createDashboardTest(grafanaDashboard);
DashboardMeta createdDashboardMeta = createDashboard(grafanaDashboard);

Can We Pass Multiple Parameters to RestCypherQueryEngine.query?

I want to implement a log in portal using java, neo4j REST API and Spring Framework. I am using the RestCypherQueryEngine class to send a cypher query to the server.
The query looks like -->
String query = "MATCH n WHERE n.Email = {email} AND n.Password = {pass} RETURN n;"
final QueryResult<Map<String,Object>> result = engine.query(query, Map.Util("Email", email), Map.Util("Password", pass);
.
"email" and "pass" are both Strings with the respective values.
I wanted to know if this is a valid query and can two parameters be passed like this ?
and how to know if a node has been returned or not or if the the login is authenticated. ?
Thank you.
You need to put all parameters into one map:
Map<String,Object> params = new HashMap<>();
params.put("email", email");
params.put("password", pass);
QueryResult<Map<String,Object>> result = engine.query(query,params);
NB: Query parameters are case sensitive.

how to retrieve orders from ordertools component in atg or how to test orderlookup droplet api

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.

Solr LukeRequest is returning an empty fieldInfo map

I am trying to inspect a solr schema using LukeRequest. I am able to browse the schema using solr admin schema browser. However when I try to retrieve it using the following piece of code it returns an empty field info map
String url = "<host>:<port>/solr/";
SolrServer server = new HttpSolrServer(url);
LukeRequest luke = new LukeRequest();
luke.setShowSchema(false);
final LukeResponse process = luke.process(server);
final Map<String, FieldInfo> fieldInfo = process.getFieldInfo();
for(String key: fieldInfo.keySet()){
FieldInfo info = fieldInfo.get(key);
System.out.println(key + ":" + info.getType());
}
(the fieldInfo variable gets an empty map)
I am using solr 3.6
Strangely this has started to work once again, if I figure what had gone wrong I will update this question
Please try to change luke.setShowSchema(true) and than try it should work.

Deleting Attribute in DynamoDB

I'm trying to figure out the best way to delete an attribute from an item in Dynamo DB. Below is what I tried, but I get an exception saying that DELETE is not a supported for either type N or S.
Exception in thread "main" Status Code: 400, AWS Service: AmazonDynamoDB, AWS Request ID: 09MRO4PVTJ8IK6OHLKSM551REJVV4KQNSO5AEMVJF66Q9ASUAAJG, AWS Error Code: ValidationException, AWS Error Message: One or more parameter values were invalid: Action DELETE is not supported for the type N
at com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:544)
at com.amazonaws.http.AmazonHttpClient.executeHelper(AmazonHttpClient.java:284)
at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:169)
at >com.amazonaws.services.dynamodb.AmazonDynamoDBClient.invoke(AmazonDynamoDBClient.java:675)
at >com.amazonaws.services.dynamodb.AmazonDynamoDBClient.updateItem(AmazonDynamoDBClient.java:371)
Key pk = new Key(new AttributeValue().withN(Long.toString(123)));
AttributeValueUpdate avu = new AttributeValueUpdate(new AttributeValue().withN("555"), "DELETE");
Map<String, AttributeValueUpdate> m = new HashMap<String, AttributeValueUpdate>();
m.put(String.valueOf(555), avu);
UpdateItemRequest uir = new UpdateItemRequest("users", pk, m);
dynamoDB.updateItem(uir);
One point of confusion is why the attribute value matters for a deletion. I really want to delete an attribute name and any associated values, but couldn't find the appropriate way to do that in the SDK.
Help would be appreciated.
I could have sworn I already tried this but by replacing the AttributeValue with a null value it works:
Key pk = new Key(new AttributeValue().withN(Long.toString(123)));
AttributeValueUpdate avu = new AttributeValueUpdate(null, "DELETE");
Map<String, AttributeValueUpdate> m = new HashMap<String, AttributeValueUpdate>();
m.put(String.valueOf(555), avu);
UpdateItemRequest uir = new UpdateItemRequest("users", pk, m);
dynamoDB.updateItem(uir);
This also works.
Table table = dynamoDB.getTable("users");
table.updateItem(new PrimaryKey("<MY HASH KEY NAME>", <MY HASH VALUE>), new AttributeUpdate("columnToRemove").delete());
or you can even use Expressions in an Item Update.
REMOVE - Removes one or more attributes from an item.
To delete an Attribute from Dynamo DB while Updating an item of the table
UpdateItemRequest updateItemRequest =new UpdateItemRequest().withTableName(tableName).withKey(key);
updateItemRequest.addAttributeUpdatesEntry("privileges",new AttributeValueUpdate()
.withAction(AttributeAction.DELETE));
updateItemRequest.addAttributeUpdatesEntry("description", new AttributeValueUpdate()
.withValue(new AttributeValue().withS("description")));
In above Example, First I removed privileges from Item and then updated description in Item.

Categories

Resources