want output as json instead of array while using criteria - arrays

This is my code and i am using projection to display only specific columns and i am getting the result as array.But i want the output as json what can i do to get the output as json.
Please help me out
public List<Educationlevel> getAllEducationlevel() {
Session session = SessionFactoryUtil.getSessionFactory().openSession();
try {
session.beginTransaction();
Criteria criteria = session.createCriteria(Educationlevel.class);
ProjectionList projlist =Projections.projectionList();
projlist.add(Projections.property("education_level"));
projlist.add(Projections.property("education_level_id"));
projlist.add(Projections.property("country_id"));
criteria.add(Restrictions.eq("delete_flag", false));
criteria.setProjection(projlist);
return criteria.list();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
session.getTransaction().commit();
session.close();
}
}
AND OUTPUT WHICH I AM GETTING
[["PG",0,2],["PHD",1,2]]
AND THE OUTPUT WHICH I AM EXPECTING
IN THIS I WANT only 3 columns say education_level_id,country_id,education_level
{
education_level_id: 0
country_id: 2
education_level: "PG"
delete_flag: false
insert_by: null
insert_date: "2015-10-19 12:49:52.0"
update_by: null
update_date: "2015-10-19 12:49:52.0"
}

JSONObject jo = new JSONObject();
jo.put("education_level", "PG");
jo.put("education_level_id", "0");
JSONArray ja = new JSONArray();
ja.put(jo);

Related

An unexpected null key in HashSet, the first be added not the rest

I'm learning Activiti 7, I drew a BPMN diagram as below:
When the highlight1 UserTask has been completed but the highlight2 UserTask is still pending, I ran the following code to highlight the completed flow element.
private AjaxResponse highlightHistoricProcess(#RequestParam("instanceId") String instanceId,
#AuthenticationPrincipal UserInfo userInfo) {
try {
// Get the instance from the history table
HistoricProcessInstance instance = historyService
.createHistoricProcessInstanceQuery().processInstanceId(instanceId).singleResult();
BpmnModel bpmnModel = repositoryService.getBpmnModel(instance.getProcessDefinitionId());
Process process = bpmnModel.getProcesses().get(0);
// Get all process elements, including sequences, events, activities, etc.
Collection<FlowElement> flowElements = process.getFlowElements();
Map<String, String> sequenceFlowMap = Maps.newHashMap();
flowElements.forEach(e -> {
if (e instanceof SequenceFlow) {
SequenceFlow sequenceFlow = (SequenceFlow) e;
String sourceRef = sequenceFlow.getSourceRef();
String targetRef = sequenceFlow.getTargetRef();
sequenceFlowMap.put(sourceRef + targetRef, sequenceFlow.getId());
}
});
// Get all historical Activities, i.e. those that have been executed and those that are currently being executed
List<HistoricActivityInstance> actList = historyService.createHistoricActivityInstanceQuery()
.processInstanceId(instanceId)
.list();
// Each history Activity is combined two by two
Set<String> actPairSet = new HashSet<>();
for (HistoricActivityInstance actA : actList) {
for (HistoricActivityInstance actB : actList) {
if (actA != actB) {
actPairSet.add(actA.getActivityId() + actB.getActivityId());
}
}
}
// Highlight Link ID
Set<String> highSequenceSet = Sets.newHashSet();
actPairSet.forEach(actPair -> {
logger.info("actPair:{}, seq:{}", actPair, sequenceFlowMap.get(actPair));
highSequenceSet.add(sequenceFlowMap.get(actPair));
logger.info("{}",highSequenceSet.toString());
});
// Get the completed Activity
List<HistoricActivityInstance> finishedActList = historyService
.createHistoricActivityInstanceQuery()
.processInstanceId(instanceId)
.finished()
.list();
// Highlight the completed Activity
Set<String> highActSet = Sets.newHashSet();
finishedActList.forEach(point -> highActSet.add(point.getActivityId()));
// Get the pending highlighted node, i.e. the currently executing node
List<HistoricActivityInstance> unfinishedActList = historyService
.createHistoricActivityInstanceQuery()
.processInstanceId(instanceId)
.unfinished()
.list();
Set<String> unfinishedPointSet = Sets.newHashSet();
unfinishedActList.forEach(point -> unfinishedPointSet.add(point.getActivityId()));
...
return AjaxResponse.ajax(ResponseCode.SUCCESS.getCode(),
ResponseCode.SUCCESS.getDesc(),
null);
} catch (Exception e) {
e.printStackTrace();
return AjaxResponse.ajax(ResponseCode.ERROR.getCode(),
"highlight failure",
e.toString());
}
}
Please see this piece of code:
// Highlight Link ID
Set<String> highSequenceSet = Sets.newHashSet();
actPairSet.forEach(actPair -> {
logger.info("actPair:{}, seq:{}", actPair, sequenceFlowMap.get(actPair));
highSequenceSet.add(sequenceFlowMap.get(actPair));
logger.info("{}",highSequenceSet.toString());
});
It was expected to get 2 elements in the highSequenceSet, but it got 3, with a unexpected null.
The log printed in the console was:
Why is the first null added to the HashSet but not the rest?
Why is the first null added to the HashSet but not the rest?
HashSet implements the Set interface, duplicate values are not allowed.

getJSONObject(int) is undefined for the type JSONArray

I am getting an JSON array in response from rest webservice and I want to iterate over it to get the various attributes of it. There are multiple json array with the same name and only the attributes values and different. For this I have tried various code snippets. I have mentioned all my tried code snippets with the error I got.
ResponseEntity<String> response = restTemplate.exchange("xyz.com",
HttpMethod.GET, entity, String.class);
JSONParser parser=new JSONParser();
System.out.println("Response is"+response.getBody());
try{
//JSONObject outerObject = (JSONObject)parser.parse(response.getBody()); Class Cast Exception
//JSONObject jsonObj = new JSONObject(response.getBody()); jsonobject must begin with {
JSONArray jsonArray = (JSONArray) parser.parse(response.getBody());
for (int i = 0; i < jsonArray.size(); i++)
{
/*JSONObject object = jsonArray.getJSONObject(i);*/// getJSONObject(int) is undefined for the type JSONArray
}
}catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The Webservices response is like
[
{"mutualFund":{"fundCode":"xyz","fundName":"123","isin":"IE000"}},
{"mutualFund":{"fundCode":"xyz","fundName":"123","isin":"xyz"}},
{"mutualFund":{"fundCode":"xyz","fundName":"123","sedol":"WB1"}}
]
You don't have to use Parser, becuase json array constructor takes string as paramter
Download the following JSON lib to make the json easy to parse
ResponseEntity<String> response = restTemplate.exchange("xyz.com",
HttpMethod.GET, entity, String.class);
System.out.println("Response is"+response.getBody());
try{
JSONArray outerObject = new JSONArray(response.getBody());
for(JSONObject object: outerObject)
{
// Your Logic
}
}catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

How can I access sqlite database on a webserver in codename one

Pls How can I access sqlite database on the webserver in codename one? I can only use database API to access database on the device. In order to access this on the webserver I think is quite different thing. Pls I need a snippet code on this. Thanks
Use the code below, not tested and you may have to adjust it to suite your need. Leave a comment if there's an issue:
ConnectionRequest req = new ConnectionRequest() {
#Override
protected void handleException(Exception ex) {
//handle error
}
};
req.setUrl(YourURL);
req.setPost(true);
req.setHttpMethod("POST"); //Change to GET if necessary
req.setDuplicateSupported(true);
req.addArgument("argumentToSendThroughPostOrGet1", "value1");
req.addArgument("argumentToSendThroughPostOrGet2", "value2");
NetworkManager.getInstance().addToQueueAndWait(req);
if (req.getResponseCode() == 200) {
Map<String, Object> out = new HashMap<>();
Display.getInstance().invokeAndBlock(() -> {
JSONParser p = new JSONParser();
try (InputStreamReader r = new InputStreamReader(new ByteArrayInputStream(req.getResponseData()))) {
out.putAll(p.parseJSON(r));
} catch (IOException ex) {
//handle error
}
});
if (!out.isEmpty()) {
List<Map<String, Object>> responses = (List<Map<String, Object>>) out.get("response");
for (Object response : responses) {
Map res = (Map) response;
System.out.println(res.get("key"));
}
} else {
//handle error
}
} else {
//handle error
}
TEST JSON RESPONSE:
{
"response": [
{
"key": "I was returned",
}
]
}
EDIT:
To pass data from TextField:
req.addArgument("argumentToSendThroughPostOrGet1", myTextField.getText());
Based on your comment, you can read those arguments in PHP as simple as below:
$var1 = $_POST["argumentToSendThroughPostOrGet1"];
$var1 = $_GET["argumentToSendThroughPostOrGet1"]; // if GET method is used in Codename One
//Or use $_REQUEST which supports both methods but not advisable to be used for production
...
And you can use those variables in your php code normally.
Example of Usage with MySql Query:
class Connection {
function connect() {
$mysqli = mysqli_init();
$mysqli->real_connect("localhost", "username", "password", "databaseName") or die('Could not connect to database!');
$mysqli->query("SET NAMES 'UTF8'");
return $mysqli;
}
function close() {
mysqli_close($this->connect);
}
}
$connection = new Connection();
$mysqli = $connection->connect();
$mysqli->query("SELECT * FROM MyTable WHERE ColumnName LIKE '%$var1%' ORDER BY PrimaryKeyId ASC LIMIT 100");

Get Unread emails from Google API

I'm trying to get the count of unread email using google API, but not able. ANy help is highly appreciated. I'm not getting any error, but the count doesnt match the actual number shown in gmail.
try
{
String serviceAccountEmail = "xxx#developer.gserviceaccount.com";
var certificate = new X509Certificate2(#"C:\Projects\xxx\xyz\API Project-xxxxx.p12", "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
User = "xxx#gmail.com",
Scopes = new[] { Google.Apis.Gmail.v1.GmailService.Scope.GmailReadonly }
}.FromCertificate(certificate));
var gmailservice = new Google.Apis.Gmail.v1.GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "GoogleApi3",
});
try
{
List<Message> lst = ListMessages(gmailservice, "xxx#gmail.com", "IN:INBOX IS:UNREAD");
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
}
}
catch (Exception ex)
{
}
Just do: labels.get(id="INBOX") and it has those types of stats (how many messages in that label, how many are unread, and same for threads).
https://developers.google.com/gmail/api/v1/reference/users/labels/get
You can use the ListMessages method from the API example (included for completeness) for searching:
private static List<Message> ListMessages(GmailService service, String userId, String query)
{
List<Message> result = new List<Message>();
UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List(userId);
request.Q = query;
do
{
try
{
ListMessagesResponse response = request.Execute();
result.AddRange(response.Messages);
request.PageToken = response.NextPageToken;
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
}
} while (!String.IsNullOrEmpty(request.PageToken));
return result;
}
You can use this search method to find unread messages, for example like this:
List<Message> unreadMessageIDs = ListMessages(service, "me", "is:unread");
The q parameter (query) can be all kinds of stuff (it is the same as the gmail search bar on the top of the web interface), as documented here: https://support.google.com/mail/answer/7190?hl=en.
Note that you only a few parameters of the Message objects are set. If you want to retreive the messages you'll have to use GetMessage method from the api:
public static Message GetMessage(GmailService service, String userId, String messageId)
{
try
{
return service.Users.Messages.Get(userId, messageId).Execute();
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
}
return null;
}
I agree that the API is not straight forward and misses a lot of functionality.
Solution for .Net:
// Get UNREAD messages
public void getUnreadEmails(GmailService service)
{
UsersResource.MessagesResource.ListRequest Req_messages = service.Users.Messages.List("me");
// Filter by labels
Req_messages.LabelIds = new List<String>() { "INBOX", "UNREAD" };
// Get message list
IList<Message> messages = Req_messages.Execute().Messages;
if ((messages != null) && (messages.Count > 0))
{
foreach (Message List_msg in messages)
{
// Get message content
UsersResource.MessagesResource.GetRequest MsgReq = service.Users.Messages.Get("me", List_msg.Id);
Message msg = MsgReq.Execute();
Console.WriteLine(msg.Snippet);
Console.WriteLine("----------------------");
}
}
Console.Read();
}

JPA Query returns no result

I am trying to search for some entities of kind "Book" in datastore using codes below.But it is returning empty List.I get a empty result list with size=-1.Where am I getting wrong?
#ApiMethod(name = "searchBook")
public List<Book> searchBook(#Named("bookName") String bookName,#Named("languageId")String languageId, #Named("subjectId")String subjectId) {
EntityManager mgr = getEntityManager();
List<Book> bookList=new ArrayList<Book>();
String queryString="";
queryString="SELECT x FROM Book x WHERE ";
//If i dont want to set any parameter for some field, I send BLANK as the parameter..
if(bookName!=null && !bookName.matches("BLANK")){
queryString=queryString+"x.bookName =:bookName"+" AND ";
}
if(languageId!=null && !languageId.matches("BLANK")){
queryString=queryString+"x.languageId =:languageId"+" AND ";
}
if(subjectId!=null && !subjectId.matches("BLANK")){
queryString=queryString+"x.categoryId =:subjectId"+" AND ";
}
//Removing last word "AND" and whitespaces from the end of queryString
queryString=queryString.substring(0,queryString.length()-5);
Query q = mgr.createQuery(queryString);
//setting query parameters..
if(bookName!=null && !bookName.matches("BLANK")){
q.setParameter("bookName", bookName);
}
if(languageId!=null && !languageId.matches("BLANK")){
q.setParameter("languageId", languageId);
}
if(subjectId!=null && !subjectId.matches("BLANK")){
q.setParameter("subjectId", subjectId);
}
//executing the query...
try {
mgr.getTransaction().begin();
bookList = (List<Book>) q.getResultList();
mgr.getTransaction().commit();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
mgr.close();
}
return bookList;
}
In my case I have tested by setting only one parameter for subjectId. Is something wrong in setting parameters? Is this the correct way to set dynamic number of parameters in a query?

Resources