Java: Accessing fields in Downloaded Object - java

I'm new to Java, but know Objective-C. I need to access fields < keys, values > in a downloaded Object.
Below is the code:
car is an Schema and car_id is the field to query
Map<String, List<SMObject>> feedback = new HashMap<String, List<SMObject>>();
List<SMCondition> query = new ArrayList<SMCondition>();
DataService ds = serviceProvider.getDataService();
List<SMObject> results;
try {
query.add(new SMEquals("car_id", new SMString(make)));
results = ds.readObjects("car", query);
if (results != null && results.size() > 0) {
feedback.put(make, results);
}
}
....
results is an Object downloaded from a remote Database that is basically a HashMap. Assuming there is only one object that is returned each time, what would be the code to access Key & Values in the returned results object?
Complete Code in case you want to see it.
EDIT
Can I do something like this:
SMObject resultObj;
if (results != null && results.size() > 0) {
resultObj = results[0];
resultObj.put("resolved", "1");
resultObj.put("accepted", "1");
resultObj.put("declined", "0");
String model = (String)resultObj.get("model");
}

If you wanted all the keys, you would do:
Map<String, List<SMObject>> feedback = new HashMap<String, List<SMObject>>();
List<String> myKeys = feedback.keySet();
To get the values, you would use the get method:
Map<String, List<SMObject>> feedback = new HashMap<String, List<SMObject>>();
feedback.get("yourKey");
For more info, check out: http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html
EDIT:
SMObject resultObj;
if (results != null && results.size() > 0) {
List<SMObject> myResults = feedback.get(make);
resultObj = myResults.get(0);
resultObj.put("resolved", "1");
resultObj.put("accepted", "1");
resultObj.put("declined", "0");
String model = (String)resultObj.get("model");
}
The general concept is that you use the key, to get the value from the hashMap. That value happens to be a list of objects; therefore, you need to iterate over that list as well and retrieve each object from the list.

Related

java delete all items in dynamodb

Im trying to delete all items in my table in dynamodb but it does not work.
try {
ScanRequest scanRequest = new ScanRequest().withTableName(table);
ScanResult scanResult = null;
do {
if (Check.nonNull(scanResult)) {
scanRequest.setExclusiveStartKey(scanResult.getLastEvaluatedKey());
}
scanResult = client.scan(scanRequest);
scanResult.getItems().forEach((Item) -> {
String n1 = Item.get("n1").toString();
String n2 = tem.get("n2").toString();
DeleteItemSpec spec = new DeleteItemSpec().withPrimaryKey("n1", n1, "n2", n2);
dynamodb.getTable(table).deleteItem(spec);
});
} while (Check.nonNull(scanResult.getLastEvaluatedKey()));
} catch (Exception e) {
throw new BadRequestException(e);
}
n1 is my Primary partition key
n2 is my Primary sort key
The best approach to delete all the items from DynamoDB is to drop the table and recreate it.
Otherwise, there are lot of read capacity and write capacity units being used which will cost you.
Dropping and recreating the table is the best approach.
PREAMBLE: While a scan operation is expensive, I was needing this answer for initialising a table for a test scenario (low volume). The table was being created by another process and I needed the test scenario on that table, I could therefore not delete and recreate the table.
ANSWER:
given:
DynamoDbClient db
static String TABLE_NAME
static String HASH_KEY
static String SORT_KEY
ScanIterable scanIterable = db.scanPaginator(ScanRequest.builder()
.tableName(TABLE_NAME)
.build());
for(ScanResponse scanResponse:scanIterable){
for( Map<String, AttributeValue> item: scanResponse.items()){
Map<String,AttributeValue> deleteKey = new HashMap<>();
deleteKey.put(HASH_KEY,item.get(HASH_KEY));
deleteKey.put(SORT_KEY,item.get(SORT_KEY));
db.deleteItem(DeleteItemRequest.builder()
.tableName(TRANSACTION_TABLE_NAME)
.key(deleteKey).build());
}
}
To delete all the items from the table first you need to perform scan operation over the table which will results you an scanoutcome. Using the iterator loop over the sacnoutcome with the primary key and it's primary key value.This will be one of the approach to delete all the items from the table. Hope that this code will work you. Thanks
Table table = dynamoDB.getTable(your_table);
ItemCollection<ScanOutcome> deleteoutcome = table.scan();
Iterator<Item> iterator = deleteoutcome.iterator();
while (iterator.hasNext()) {
your_table.deleteItem("PrimaryKey", iterator.next().get("primary key value"));
}
//May be we can make it look generic by reading key schema first as below
String strPartitionKey = null;
String strSortKey = null;
TableDescription description = table.describe();
List<KeySchemaElement> schema = description.getKeySchema();
for (KeySchemaElement element : schema) {
if (element.getKeyType().equalsIgnoreCase("HASH"))
strPartitionKey = element.getAttributeName();
if (element.getKeyType().equalsIgnoreCase("RANGE"))
strSortKey = element.getAttributeName();
}
ItemCollection<ScanOutcome> deleteoutcome = table.scan();
Iterator<Item> iterator = deleteoutcome.iterator();
while (iterator.hasNext()) {
Item next = iterator.next();
if (strSortKey == null && strPartitionKey != null)
table.deleteItem(strPartitionKey, next.get(strPartitionKey));
else if (strPartitionKey != null && strSortKey != null)
table.deleteItem(strPartitionKey, next.get(strPartitionKey), strSortKey, next.get(strSortKey));
}

DynamoDB Pagination

I am doing pagination in DynamoDb and see that the result not like my expected, but I still don't know where wrong in my code.
I have searched for this document and see that I just need to set evaluated key which I got last evaluated key from last request to pass to next request.
Here is my code :
public QueryResultPage<SbmBookingInfo> getListBooking(String email, int size,
String lastTimeStamp, String lastBookingId, boolean isForward) {
DynamoDBMapper mapper = new DynamoDBMapper(getClient());
Map<String, AttributeValue> expressionAttributeValues = new HashMap<>();
expressionAttributeValues.put(":email", new AttributeValue().withS(email));
if (lastBookingId == null) {
DynamoDBQueryExpression<SbmBookingInfo> queryExpression = new DynamoDBQueryExpression<SbmBookingInfo>()
.withIndexName("practitioner-index").withKeyConditionExpression("email=:email")
.withExpressionAttributeValues(expressionAttributeValues).withConsistentRead(false).withLimit(size);
QueryResultPage<SbmBookingInfo> result = mapper.queryPage(SbmBookingInfo.class, queryExpression);
m_log.info("Last evaluated key " + result.getLastEvaluatedKey());
return result;
} else {
Map<String, AttributeValue> lastEvaluatedKey = new HashMap<>();
lastEvaluatedKey.put("timeStamp", new AttributeValue().withN(lastTimeStamp));
lastEvaluatedKey.put("bookingId", new AttributeValue().withN(lastBookingId));
lastEvaluatedKey.put("email", new AttributeValue().withS(email));
DynamoDBQueryExpression<SbmBookingInfo> queryExpression = new DynamoDBQueryExpression<SbmBookingInfo>().withLimit(size)
.withIndexName("practitioner-index").withKeyConditionExpression("email=:email")
.withExpressionAttributeValues(expressionAttributeValues).withConsistentRead(false)
.withScanIndexForward(isForward).withExclusiveStartKey(lastEvaluatedKey);
m_log.info("Exclusive key" + queryExpression.getExclusiveStartKey());
return mapper.queryPage(SbmBookingInfo.class, queryExpression);
}
}
This table has three key: bookingId is hashkey, index: email, and timeStamp is rangeKey.
I checked this function by making the first request and I receive last evaluated key then I make second request with passing the info that I received but seem like it didn't work.
Please help me at this case. Thanks

Java - Getting a list of contacts using Infusionsofts API

I'm using Java and Infusionsofts API to get a list of contacts based on the customer id. I can't figure out a way to do this. I'm using Googles Guava to use multimap but it's producing an error:
org.apache.xmlrpc.common.XmlRpcExtensionException: Serializable objects aren't supported, if isEnabledForExtensions() == false
So now i'm trying hashmap and i'm inserting "Id" as the key and the customer id as the value but there's always one entry in the hashmap.
How can I add to the parameters variable a map that contains:
["Id",11111]
["Id",22322]
["Id",44444]
List parameters = new ArrayList();
parameters.add(APP_ID);
parameters.add(TABLE_NAME);
parameters.add(LIMIT);
parameters.add(pageNumber);
HashMap<String, Integer> map = new HashMap<String, Integer>();
for(int customerId : customerIds){
map.put("Id", customerId);
}
//PROBLEM IS HERE
parameters.add(map);
//THIS IS THE PROBLEM, I NEED TO ADD ["Id", customerId] multiple
//times with the customerId being different but since there's a hashmap
//There's always 1 entry in the map
String[] fields = {"Email","FirstName"};
parameters.add(fields);
Object[] contacts = null;
try{
contacts = ( Object [] ) client.execute("DataService.query",parameters);
}catch(XmlRpcException e){
e.printStackTrace();
}
for (int i = 0; i < contacts.length; i++) {
Map contact = (Map) contacts[i];
System.out.println(contact+"\n\n");
}

Pass an ArrayList as parameter to StoredProcedure from a class

How to pass an ArrayList as parameter to StoredProcedure from a Java class?
I have a method from which database StoredProcedure is called like shown in below code:
public void insertFileDownload(ArrayList<String> spareaList, ArrayList<String> spcollrtList, ArrayList<String> spmaintRtList, ArrayList<String> spenfRtList) {
if (spareaList != null) {
for (String a : spareaList) {//for Areas
Map<String, Object> param = new HashMap<String, Object>();
param.put("areaName", a);
param.put("collroutesName", null);
param.put("maintrtsName", null);
param.put("enfrtsName", null);
genericDao.sqlQueryWithParameters(" {call sp_addMeterJob(:areaName,:collroutesName,:maintrtsName,:enfrtsName) }", param);
}
} else if (spcollrtList != null) {//for CollectionRoutes
for (String cllRt : spcollrtList) {
Map<String, Object> param = new HashMap<String, Object>();
param.put("areaName", null);
param.put("collroutesName", cllRt);
param.put("maintrtsName", null);
param.put("enfrtsName", null);
genericDao.sqlQueryWithParameters(" {call sp_addMeterJob(:areaName,:collroutesName,:maintrtsName,:enfrtsName) }", param);
}
..........
At present I am using if else conditions 4 times to check for each incoming array list parameter to set the values as parameters to stored procedures.
Is there any other better approach avoid many if else blocks?
Why not map the array in an XML file and pass it as the parameter (varchar)? That way you don't need to check for nulls in java. Then on the SP you retrieve it mapping it back to a table and it automatically puts nulls if a parameter is null or is missing from the xml:
alter PROCEDURE [dbo].[ProcessArrayXML] #xml varchar(max)
AS
BEGIN
declare #xmlHandler int
exec sp_xml_preparedocument #xmlHandler OUTPUT, #xml
select * into #xmlBorrar
from openxml(#xmlHandler,'param')
WITH (areaName varchar(50) '#areaName',
collroutesName varchar(50) '#collroutesName',
maintrtsName varchar(50) '#maintrtsName',
enfrtsName varchar(50) '#enfrtsName')
--DOSOMETHING
select * from #xmlBorrar
end
If you call it with:
exec [ProcessArrayXML]
'<?xml version="1.0" encoding="ISO-8859-1"?><param areaName = "1234" maintrtsName="1030" enfrtsName="1142" collroutesName="1204" />'
you've get a table with the parameters as columns, but if you leave one of the params out of the xml the column fills with null, for example...
exec [ProcessArrayXML]
'<?xml version="1.0" encoding="ISO-8859-1"?><param collroutesName="1204" />'
If you just want to clean up some of the boiler plate in your code, you should try something like this:
public void insertFileDownload(ArrayList<String> spareaList,
ArrayList<String> spcollrtList, ArrayList<String> spmaintRtList, ArrayList<String> spenfRtList) {
if (!processList(spareaList, "areaName"))
if (!processList(spcollrtList, "collroutesName"))
if (!processList(spmaintRtList, "maintrtsName"))
processList(spenfRtList, "enfrtsName");
}
private boolean processList(ArrayList<String> list, String mapKey) {
boolean processed = false;
if (list != null){
processed = true;
for (String a : list) {
Map<String, Object> param = new HashMap<String, Object>();
param.put(mapKey, a);
genericDao.sqlQueryWithParameters(" {call sp_addMeterJob(:areaName,:collroutesName,:maintrtsName,:enfrtsName) }", param);
}
}
return processed;
}
You don't need to add the explicit null key/values to the Map because any key not present in the Map will evaluate to null anyway if you call get for it. If you really need those explicit null key/values in the Map, let me know and I will tweak the code a bit.

Use HashMap in XMLRPC result

I am new in Android development, and I am trying to receive a HashMap in RESULT by using XMLRPC but every time it's crash the application, this is my code please advice me :
Object RESULT = XMLRPCClient.callEx(methodname,new Object[] {params});
Map FRESULT= (Map) RESULT;
I have been dealing with this also and managed to get the values this way:
try {
Object[] answer = (Object[]) client.call("call", sessionId, method, params);
HashMap map = (HashMap) answer[0]; // get first item of the response because in my case the response was an array of Objects with one item in it holding the HashMap
Object[] records = (Object[]) map.get("records"); // I only needed values from "records" key
for (int i = 0; i < records.length; i++) {
HashMap record = (HashMap) records[i]; // create another map from the records values, in my case uid's of categories
Category cat = new Category(); // creating new instance of my Category class
cat.setCatUid((String) record.get("uid")); // calling a method of the Category class to set Uid to the value from record HashMap
m_categories.add(cat); // this adds it to my ArrayList<Category>
}
} catch (XMLRPCException e) {
Log.e(method, "Exception", e);
}
I'm sure it's a mess, I'm noob in Java myself, but it worked for me. Hope it helps :)
Now the Application pass this peacefully after implementing :
Object RESULT = XmlRpcConnect.ServerCall_a(method,new Object[] {params});
Map<String, Object> FRESULT= (HashMap<String, Object>) RESULT;
with some changes in my XmlRpcConnect Class:
#SuppressWarnings("unchecked");
public static Object ServerCall_a(String method, Object[] params){
XMLRPCClient client = new XMLRPCClient(server);
HashMap<String, Object> result=null;
try{
result = (HashMap<String, Object>) client.callEx(method, params);
}
catch(XMLRPCFault f){
// result = ("Fault message: " + f.getMessage());
}
catch(XMLRPCException e){
// result = ("Exception message: " + e.getMessage());
}
return result;
}
but when trying to extract the values it's crash again , any advice :
if (FRESULT.get("status") == null) {
result = (String) FRESULT.get("status");
toastDialog(result);
}

Categories