How to use the QueryResult in Bluemix to get the BasicDocumentRevision - ibm-cloud

public List<Task> allTasks() {
int nDocs = this.mDatastore.getDocumentCount();
List<BasicDocumentRevision> all = this.mDatastore.getAllDocuments(0, nDocs, true);
List<Task> tasks = new ArrayList<Task>();
// Filter all documents down to those of type Task.
IndexManager im = new IndexManager(mDatastore);
List<Object> indexFields = new ArrayList<Object>();
indexFields.add("city");
indexFields.add("price");
indexFields.add("Area");
indexFields.add("Information");
indexFields.add("imagename");
// Create the index
im.ensureIndexed(indexFields);
Map<String, Object> query = new HashMap<String, Object>();
query.put("desc", "RESIDENTIAL PROPERTY");
QueryResult result = im.find(query);
for(BasicDocumentRevision rev :all) {
Task t = Task.fromRevision(rev);
if (t != null) {
tasks.add(t);
}
}
return tasks;
How do you use queryresult to get it stored in a task class object? I want my query to only be listed in listview. I am working on Bluemix, which uses Cloudant syn.

You can get the document revision from the QueryResult by iterating over the QueryResult Object like :
for(DocumentRevision rev : result){
Task t = Task.fromRevision(rev);
if(task != null)
tasks.add(t);
}

Related

spring boot not able to retrieve gridfs

So I have been trying for hours or even the whole day on how to retrieve my gridfs from the mongodb.
This is how I save it:
DBObject dbObject = new BasicDBObject();
Map<String, Boolean> values = new HashMap<>();
values.put("boolean", true);
dbObject.put("tags", tags);
dbObject.put("description", des);
Object id = gridFsTemplate.store(file.getInputStream(), String.valueOf(file.getName()), dbObject);
Query query = new Query();
query.addCriteria(Criteria.where("email").is(jwt.extractEmail(token)));
Update update = new Update();
if(repository.findByEmail(jwt.extractEmail(token)) == null){
update.set("gridFsId", Arrays.asList(id.toString()));
}
else{
User user = repository.findByEmail(jwt.extractEmail(token));
List<String> gridFsId = user.gridFsId;
gridFsId.add(id.toString());
update.set("gridFsId", gridFsId);
}
template.updateMulti(query, update, User.class);
values.put("boolean", true);
return values;
and this is how I try to get it:
public List<item> get_items(String token){
User user = repository.findByEmail(jwt.extractEmail(token));
List<GridFSFile> items = new ArrayList<>();
}
for some reason whenever I try to use GridFSDBFile the whole line is read.
Please help ;)

Get multiple list grouped by different fields

I'm using this method to send multiple list to client.
public ResponseEntity<?> getFiveLastRequestOfEachVehicleType() {
ResponseContent content = getResponseContent();
Map<String, List<Request>> map = new HashMap<>();
GroupBy groupBy = new GroupBy();
groupBy.initialDocument("vehicleTypeEnum");
query = new Query();
queryFieldsFilterLastFiveRequest(query, VehicleTypeEnum.NEISAN);
map.put("NEISAN", mongoOperations.find(query, Request.class));
query = new Query();
queryFieldsFilterLastFiveRequest(query, VehicleTypeEnum.BADSAN);
map.put("BADSAN", mongoOperations.find(query, Request.class));
query = new Query();
queryFieldsFilterLastFiveRequest(query, VehicleTypeEnum.BUJE);
map.put("BUJE", mongoOperations.find(query, Request.class));
content.setData(map);
return getReturn(content);
}
And this method apply criteria to each query
private void queryFieldsFilterLastFiveRequest(Query query, VehicleTypeEnum vehicleTypeEnum) {
query.addCriteria(Criteria.where("vehicleTypeEnum").is(vehicleTypeEnum));
query.addCriteria(Criteria.where("unlock").is(true));
query.fields()
.include("id")
.include("goodsTypeTitle")
.include("originCityTitle")
.include("price");
query.limit(5);
}
I wonder if there is any way to retrieve all list in one request to database using MongoOperations.
I would go to grouping manually later on, first query for all vehicleType :
private void queryFieldsFilterLastFiveRequest(Query query, VehicleTypeEnum... vehicleTypeEnum..) {
query.addCriteria(Criteria.where("vehicleTypeEnum").in(vehicleTypeEnum));
query.addCriteria(Criteria.where("unlock").is(true));
query.fields()
.include("id")
.include("goodsTypeTitle")
.include("originCityTitle")
.include("price");
query.limit(5);
}
Here the is has been changed by in, and accept a list of VehicleTypeEnum
Then to use it :
public ResponseEntity<?> getFiveLastRequestOfEachVehicleType() {
ResponseContent content = getResponseContent();
Map<String, List<Request>> map;
query = new Query();
queryFieldsFilterLastFiveRequest(query, VehicleTypeEnum.NEISAN, VehicleTypeEnum.BADSAN, VehicleTypeEnum.BUJE);
map = mongoOperations.find(query, Request.class).stream()
.collect(Collectors.toMap(r -> r.getVehicleTypeEnum().name(),r -> r));
content.setData(map);
return getReturn(content);
}
Here i use the stream api to group result by VehiculeTypeEnum name

Dynamic JPQL query qith JOIN

Had to write a jpql query, based on the input need to add and condition and for some input had to need JOIN queries.
#Override
public List<IncidentHdr> fetchIncidents(IncidentHdrDto incidentHdrDto) {
StringBuilder query = new StringBuilder();
query.append(ReposJPQL.GET_INCIDENT_DETAILS);
Map<String, Object> parameters = new HashMap<String, Object>();
List<String> criteria = new ArrayList<String>();
if(incidentHdrDto.getIncidentId() > 0) {
criteria.add("inc.incidentId = :incidentId");
parameters.put("incidentId", incidentHdrDto.getIncidentId());
}
if(incidentHdrDto.getCatCode() > 0) {
criteria.add("inc.catCode = :catCode");
parameters.put("catCode", incidentHdrDto.getCatCode());
}
if(incidentHdrDto.getType != null) {
//here i need to generate a join query
//SELECT * FROM INCIDENT JOIN CATEGORY_MAST ON(INCIDENT.CAT_CODE = CATEGORY_MAST.CAT_CODE) WHERE CATEGORY_MAST.TYPE_CODE = 16
}
Query q = em.createQuery(query.toString());
logger.info("Get Incidents Query : "+query.toString());
for (Entry<String, Object> entry : parameters.entrySet()) {
q.setParameter(entry.getKey(), entry.getValue());
}
List<IncidentHdr> incidentHdrs = q.getResultList();
return incidentHdrs;
}
where as ReposJPQL is the base query which had a where condition.
public interface ReposJPQL {
public String GET_INCIDENT_DETAILS = "SELECT inc FROM IncidentHdr inc WHERE 1 = 1" ;
}

android - trying to create listview

i'm trying to write data from sqlite to a listview. the compiler doesn't show error, but when I run the app on my phone, it crashes. please help me
Cursor resultSet = db.rawQuery("Select * from weight_listview ORDER BY `id` DESC",null);
resultSet.moveToFirst();
String[] list = new String[] {};
String[] weighttolist={};
String[] datetolist={};
ArrayList<String> List=new ArrayList<String>();
ArrayList<String> List2=new ArrayList<String>();
resultSet.moveToFirst();
int x = 0;
while(resultSet.moveToNext()){
String data = resultSet.getString(resultSet.getColumnIndex("weight"));
String data2 = resultSet.getString(resultSet.getColumnIndex("date"));
String id = resultSet.getString(resultSet.getColumnIndex("ID"));
List.add(data + " " + data2);
x++;
}
final ListView listView = (ListView) findViewById(R.id.listView1);
if(List != null){
weighttolist=(String[])List.toArray(new String[0]);
String[] from = { "weight", "date" };
int[] to = { R.id.weight, R.id.date };
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this,R.layout.row, resultSet, from, to);
listView.setAdapter(cursorAdapter);
// ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
// android.R.layout.simple_list_item_1, android.R.id.text1, weighttolist);
// ListView.setAdapter(adapter);
}
edit:
I successed to fix the problem but now I have another problem. I want that the listview will show 2 columns , not only 1 . I created fill row.xml , as you can see in the first code.
Cursor resultSet = db.rawQuery("Select * from weight_listview ORDER BY `id` DESC",null);
resultSet.moveToFirst();
String[] list = new String[] {};
String[] weighttolist={};
String[] datetolist={};
ArrayList<String> List=new ArrayList<String>();
ArrayList<String> List2=new ArrayList<String>();
resultSet.moveToFirst();
int x = 0;
while(resultSet.moveToNext()){
String data = resultSet.getString(resultSet.getColumnIndex("weight"));
String data2 = resultSet.getString(resultSet.getColumnIndex("date"));
List.add(data + " " + data2);
x++;
}
final ListView listView = (ListView) findViewById(R.id.listView1);
if(List != null){
weighttolist=(String[])List.toArray(new String[0]);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, weighttolist);
listView.setAdapter(adapter);
}
Well without the exact error it is hard to see what is going wrong. Here is my guess you are using a SimpleAdapter who's constructor looks like this
SimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)
For your second parameter you are using a Cursor not a list, your from variable are keys so you need to use a hash map I believe
Comment out your code and try this
List<HashMap<String, String>> List = new ArrayList<HashMap<String, String>>();
int x = 0;
while(resultSet.moveToNext()){
HashMap<String, String> map = new HashMap<String, String>();
String weight = resultSet.getString(resultSet.getColumnIndex("weight"));
String date = resultSet.getString(resultSet.getColumnIndex("date"));
String id = resultSet.getString(resultSet.getColumnIndex("ID"));
map.put("weight", weight);
map.put("date", date);
List.add(map);
x++;
}
final ListView listView = (ListView) findViewById(R.id.listView1);
if(List != null){
weighttolist=(String[])List.toArray(new String[0]);
String[] from = { "weight", "date" };
int[] to = { R.id.weight, R.id.date };
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(this,R.layout.row, List, from, to);
listView.setAdapter(cursorAdapter);

How to retrieve an embedded list of object of Entity?

I have a simple problem storing and retrieving an embedded collection of entity to mongo. I have checked theses question :
how to serialize class? and Mongodb saves list of object
what I understand is to save a list objects the class of that objects must extends ReflactionDBObject. This worked for saving the object, by retrieving it with the embedded collection does not work.
here a simple test show that retrieving embedded entities does not work !
#Test
public void whatWasStoredAsEmbeddedCollectionIsRetrieved2() {
BasicDBObject country = new BasicDBObject();
country.put("name", "Bulgaria");
List<City> cities = Lists.newArrayList(new City("Tarnovo"));
country.put("listOfCities", cities);
DBCollection collection = db().get().getCollection("test_Collection");
collection.save(country);
DBCursor object = collection.find(new BasicDBObject().append("name", "Bulgaria"));
DBObject returnedCity = object.next();
DBObject embeddedCities = (DBObject) returnedCity.get("listOfCities");
System.out.println(embeddedCities);
}
Here is the City Class
class City extends ReflectionDBObject {
String name;
City() {
}
City(String name) {
this.name = name;
}
public String getName() {
return name;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof City)) return false;
City city = (City) o;
if (name != null ? !name.equals(city.name) : city.name != null) return false;
return true;
}
#Override
public int hashCode() {
return name != null ? name.hashCode() : 0;
}
#Override
public String toString() {
return "City{" +
"name='" + name + '\'' +
'}';
}
}
The out put of the System.out.println statement is [ { "_id" : null }]
Now how can get back the embedded object and the embedded list in it ?
If you do not have a requirement to define your own class City, you can define subdocuments using the BasicDBObjects. I only added the 'name' field to the citySubDoc1 and citySubDoc2, but of course, you can add more fields to these subdocuments.
// Define subdocuments
BasicDBObject citySubDoc1 = new BasicDBObject();
citySubDoc1.put("name", "Tarnovo");
BasicDBObject citySubDoc2 = new BasicDBObject();
citySubDoc2.put("name", "Sofia");
// add to list
List<DBObject> cities = new ArrayList <DBObject>();
cities.add(citySubDoc1);
cities.add(citySubDoc2);
country.put("listOfCities", cities);
collection.save(country);
// Specify query condition
BasicDBObject criteriaQuery = new BasicDBObject();
criteriaQuery.put("name", "Bulgaria");
// Perform the read
DBCursor cursor = collection.find(criteriaQuery);
// Loop through the results
try {
while (cursor.hasNext()) {
List myReturnedListOfCities = (List) cursor.next().get("listOfCities");
System.out.println(myReturnedListOfCities);
}
} finally {
cursor.close();
}