public
Created

SendGrid StackMob - query datastore

  • Download Gist
gistfile1.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
JSONParser parser = new JSONParser();
 
try {
Object obj = parser.parse(request.getBody());
JSONObject jsonObject = (JSONObject) obj;
 
//We use the username passed to query the StackMob datastore
//and retrieve the user's name and email address
username = (String) jsonObject.get("username");
 
// The following values could be static or dynamic
subject = (String) jsonObject.get("subject");
text = (String) jsonObject.get("text");
from = (String) jsonObject.get("from");
} catch (ParseException e) {
logger.error(e.getMessage(), e);
responseCode = -1;
responseBody = e.getMessage();
}
if (username == null || username.isEmpty()) {
HashMap<String, String> errParams = new HashMap<String, String>();
errParams.put("error", "the username passed was empty or null");
return new ResponseToProcess(HttpURLConnection.HTTP_BAD_REQUEST, errParams); // http 400 - bad request
}
// get the StackMob datastore service and assemble the query
DataService dataService = serviceProvider.getDataService();
// build a query
List<SMCondition> query = new ArrayList<SMCondition>();
query.add(new SMEquals("username", new SMString(username)));
 
SMObject userObject;
List<SMObject> result;
try {
// return results from user query
result = dataService.readObjects("user", query);
if (result != null && result.size() == 1) {
userObject = result.get(0);
to = userObject.getValue().get("email").toString();
toname = userObject.getValue().get("name").toString();
} else {
HashMap<String, String> errMap = new HashMap<String, String>();
errMap.put("error", "no user found");
errMap.put("detail", "no matches for the username passed");
return new ResponseToProcess(HttpURLConnection.HTTP_OK, errMap); // http 500 - internal server error
}
} catch (InvalidSchemaException e) {
...
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.