how to check if a JSONArray is empty in java? - arrays

I am working on an android app that get json content of a webservice called "WebUntis". The Json content i am getting looks like:
{"jsonrpc":"2.0","id":"req-002",
"result":[
{"id":125043,"date":20110117,"startTime":800,"endTime":850,
"kl":[{"id":71}],
"te":[{"id":23}],
"su":[{"id":13}],
"ro":[{"id":1}]},
{"id":125127,"date":20110117,"startTime":1055,"endTime":1145,
"kl":[{"id":71}],
"te":[{"id":41}],
"su":[{"id":19}],
"ro":[{"id":31}]},
...]}
As you can see in the result-array there are also other arrays like "kl", "su" and "ro"
I am getting the content of these array and then i store them in an arraylist.
But when one of these array is empty, like;
{"jsonrpc":"2.0","id":"req-002",
"result":[
{"id":125043,"date":20110117,"startTime":800,"endTime":850,
"**kl":[]**,
"te":[{"id":23}],
"su":[{"id":13}],
"ro":[{"id":1}]},
{"id":125127,"date":20110117,"startTime":1055,"endTime":1145,
"kl":[{"id":71}],
"te":[{"id":41}],
"su":[{"id":19}],
"ro":[{"id":31}]},
...]}
I am always getting the error IndexOutOfRangeException,
but I am always telling it that it should not take the empty arrays, this is what I have tried:
JSONObject jsonResult = new JSONObject(s);
// Get the result object
JSONArray arr = jsonResult.getJSONArray("result");
for (int i = 0; i < arr.length(); i++) {
JSONObject c = arr.getJSONObject(i);
anfangStunde[i] = c.getString("startTime");
endeStunde[i] = c.getString("endTime");
// get the jsonarrays (kl, su, ro)
kl = c.getJSONArray("kl");
su = c.getJSONArray("su");
ro = c.getJSONArray("ro");
// check if kl is not null
if(kl != null){
klassenID[i] = kl.getJSONObject(0).getString("id");
}
if (klassenID[i] != null) {
klasse = webuntis.klassenMap.get(klassenID[i]);
Log.d("ID und Klasse=", "" + klassenID[i] + ";" + klasse);
}
// get th ids
fachID[i] = su.getJSONObject(0).getString("id");
if (fachID[i] != null) {
fach = webuntis.faecherMap.get(fachID[i]);
Log.d("ID und Fach=", "" + fachID[i] + ";" + fach);
}
// "Start;Ende;Klasse;Fach;Raum" store in arraylist
webuntis.stundenPlan.add(anfangStunde[i] + ";" + endeStunde[i] + ";" + klasse + ";" + fach);
// Write Data into a file for offline use:
}
Can anyone help me ?

If the array is defined in the file but is empty, like:
...
"kl":[]
...
Then getJSONArray("kl") will return an empty array, but the object is not null. Then, if you do this:
kl = c.getJSONArray("kl");
if(kl != null){
klassenID[i] = kl.getJSONObject(0).getString("id");
}
kl is not null and kl.getJSONObject(0) will throw an exception - there is no first element in the array.
Instead you can check the length(), e.g.:
kl = c.getJSONArray("kl");
if(kl != null && kl.length() > 0 ){
klassenID[i] = kl.getJSONObject(0).getString("id");
}

You can also use isEmpty() method, this is the method we use to check whether the list is empty or not. This method returns a Boolean value. It returns true if the list is empty otherwise it gives false. For example:
if (!k1.isEmpty()) {
klassenID[i] = kl.getJSONObject(0).getString("id");
}

You can use the regular length() method. It returns the size of JSONArray. If the array is empty, it will return 0. So, You can check whether it has elements or not. This also keeps you in track of total elements in the Array, You wont go out of Index.
if(k1 != null && k1.length != 0){
//Do something.
}

This is another way to do it...
call.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call,
Response<JsonObject> response) {
JSONObject jsonObject;
try {
jsonObject = new JSONObject(new Gson().toJson(response.body()));
JSONArray returnArray = jsonObject.getJSONArray("my_array");
// Do Work Only If Not Null
if (!returnArray.isNull(0)) {
for (int l = 0; l < returnArray.length(); l++) {
if (returnArray.length() > 0) {
// Get The Json Object
JSONObject returnJSONObject = returnArray.getJSONObject(l);
// Get Details
String imageUrl = returnJSONObject.optString("image");
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<JsonObject> call,
Throwable t) {
}
});

Related

2 object of same type returns true when != checked

I am using model.GetType().GetProperties() with foreach to compare properties of 2 object of same class.
like this
foreach (var item in kayit.GetType().GetProperties())
{
var g = item.GetValue(plu);
var b = item.GetValue(kayit);
if (g is string && b is string&& g!=b)
{
a += item.Name + "*";
}
else if (g is DateTime&& b is DateTime&& g!=b)
{
a += item.Name + "*";
}
}
But the problem is even if they have the same value g!=b returns a true all the time. I have used a break point to prove this and they are literally same thing. Actually I am taking the value putting it in textbox then creating another class after button click and comaring to see the changed properties. So even if I don't change anything it doesn't read the mas equals. Can someone help me about this please?
more info:
I get the plu from database and populate my control with it:
txtorder.Text = plu.OrderNo;
dtporder.Value = nulldate(plu.OrderDate);
dtp1fit.Value = nulldate(plu.FirstFitDate);
dtp1yorum.Value = nulldate(plu.FirstCritDate);
dtp2fit.Value = nulldate(plu.SecondFitDate);
dtp2yorum.Value = nulldate(plu.SecondCritDate);
dtpsizeset.Value = nulldate(plu.SizeSetDate);
dtpsizesetok.Value = nulldate(plu.SizeSetOkDate);
dtpkumasplan.Value = nulldate(plu.FabricOrderByPlan);
txtTedarikci.Text = plu.Fabric_Supplier;
dtpkumasFP.Value = nulldate(plu.FabricOrderByFD);
dtpfabarrive.Value = nulldate(plu.FabricArrive);
dtpbulk.Value = nulldate(plu.BulkFabricDate);
dtpbulkok.Value = nulldate(plu.BulkConfirmDate);
dtpaccessory.Value = nulldate(plu.AccessoriesDate);
dtpaccessoryarrive.Value = nulldate(plu.AccessoriesArriveDate);
dtpcutok.Value = nulldate(plu.ProductionStartConfirmation);
dtpcutstart.Value = nulldate(plu.ProductionStart);
dtpshipmentdate.Value = nulldate(plu.ShipmentDate);
dtpshipmentsample.Value = nulldate(plu.ShipmentSampleDate);
dtpshippedon.Value = nulldate(plu.Shippedon);
nulldate is just a method where I change null values to my default value.
And this is what I do after button click:
var kayit = new uretim();
kayit.OrderNo = txtorder.Text.ToUpper();
kayit.OrderDate = vdat(dtporder.Value);
kayit.FirstFitDate = vdat(dtp1fit.Value);
kayit.FirstCritDate = vdat(dtp1yorum.Value);
kayit.SecondFitDate = vdat(dtp2fit.Value);
kayit.SecondCritDate = vdat(dtp2yorum.Value);
kayit.SizeSetDate = vdat(dtpsizeset.Value);
kayit.SizeSetOkDate = vdat(dtpsizesetok.Value);
kayit.FabricOrderByPlan = vdat(dtpkumasplan.Value);
kayit.Fabric_Supplier = txtTedarikci.Text;
kayit.FabricOrderByFD = vdat(dtpkumasFP.Value);
kayit.FabricArrive = vdat(dtpfabarrive.Value);
kayit.BulkFabricDate = vdat(dtpbulk.Value);
kayit.BulkConfirmDate = vdat(dtpbulkok.Value);
kayit.AccessoriesDate = vdat(dtpaccessory.Value);
kayit.AccessoriesArriveDate = vdat(dtpaccessoryarrive.Value);
kayit.ProductionStartConfirmation = vdat(dtpcutok.Value);
kayit.ProductionStart = vdat(dtpcutstart.Value);
kayit.ShipmentDate = vdat(dtpshipmentdate.Value);
kayit.ShipmentSampleDate = vdat(dtpshipmentsample.Value);
kayit.Shippedon = vdat(dtpshippedon.Value);
kayit.Status = true;
kayit.WrittenDate = DateTime.Now;
kayit.GuidKey = plu.GuidKey != null ? plu.GuidKey : Guid.NewGuid().ToString("N");
I have proven by breakpoint that values are actually same. But the != check retruns a true.
When you are doing
g != b
compiler doesn't know that these objects are strings to compare so it compares their references. You can do:
g.Equals(b) //be carefull if one of them is null
or
g.ToString() != b.ToString()
EDIT
You can compare them after you check the type:
if (g is string && b is string)
{
if( g.ToString() != b.ToString() ){
}
}

Message.Payload is always null for all messages. How do I get this data?

It is returning the correct number of message, but the only fields that are populated are Id and ThreadId. Everything else is null
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
ListMessagesResponse response = service.Users.Messages.List(emailAddress).Execute();
IList<Google.Apis.Gmail.v1.Data.Message> messages = response.Messages;
Console.WriteLine("Messages:");
if (messages != null && messages.Count > 0)
{
foreach (var message in messages)
{
Console.WriteLine("{0}", message.Payload.Body);
Console.WriteLine();
}
}
else
{
Console.WriteLine("No Messages found.");
}
Messages.List() only returns message and thread ids. To retrieve message contents, you need to invoke Get() for each message you are interested in. Updated version of your foreach loop example:
foreach (var message in messages)
{
Message m = service.Users.Messages.Get("me", message.Id).Execute();
// m.Payload is populated now.
foreach (var part in m.Payload.Parts)
{
byte[] data = Convert.FromBase64String(part.Body.Data);
string decodedString = Encoding.UTF8.GetString(data);
Console.WriteLine(decodedString);
}
}
Note: You may need to run a string replace on the part.Body.Data string. See this post for instructions.

AngularJs, how to set empty string in URL

In the controller I have below function:
#RequestMapping(value = "administrator/listAuthor/{authorName}/{pageNo}", method = { RequestMethod.GET,
RequestMethod.POST }, produces = "application/json")
public List<Author> listAuthors(#PathVariable(value = "authorName") String authorName,
#PathVariable(value = "pageNo") Integer pageNo) {
try {
if (authorName == null) {
authorName = "";
}
if (pageNo == null) {
pageNo = 1;
}
return adminService.listAuthor(authorName, pageNo);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
This function fetches and returns data from mysql database based on "authorName" and "pageNo". For example, when "authorName = a" and "pageNo = 1" I have:
Data I get when "authorName = a" and "pageNo = 1"
Now I want to set "authorName" as ""(empty string), so that I can fetch all the data from mysql database (because the SQL statement "%+""+%" in backend will return all the data).
What can I do if I want to set authorName = empty string?
http://localhost:8080/spring/administrator/listAuthor/{empty string}/1
Thanks in advance!
I don't think that you can encode empty sting to url, what I suggest you to do is to declare some constant that will be your code to empty string - such as null.
Example:
administrator/listAuthor/null/90
Afterwards , on server side, check if authorName is null and set local parameter with empty stirng accordingly.

Get appointments from all Outlook calendars

I'm trying to read appointments from Outlook calendar using ExchangeServiceBinding but my solution takes appointments only from "default" outlook calendar and don't read from "sub calendars/custom calendars". Do you know how to define rest of the calendars or do you know better solution which contains all calendars?
Critical part is that solution shouldn't contain MAPI because of next use in web service.
My current code:
private static List<List<string>> ReadCalendarEvents(string email)
{
List<List<string>> calendarEvents = new List<List<string>>();
// Specify the request version.
esb.RequestServerVersionValue = new RequestServerVersion();
esb.RequestServerVersionValue.Version = ExchangeVersionType.Exchange2007;
// Form the FindItem request.
FindItemType findItemRequest = new FindItemType();
CalendarViewType calendarView = new CalendarViewType();
calendarView.StartDate = DateTime.Now.AddDays(-7);
calendarView.EndDate = DateTime.Now.AddDays(200);
calendarView.MaxEntriesReturned = 1000;
calendarView.MaxEntriesReturnedSpecified = true;
findItemRequest.Item = calendarView;
// Define which item properties are returned in the response.
ItemResponseShapeType itemProperties = new ItemResponseShapeType();
// Use the Default shape for the response.
//itemProperties.BaseShape = DefaultShapeNamesType.IdOnly;
itemProperties.BaseShape = DefaultShapeNamesType.AllProperties;
findItemRequest.ItemShape = itemProperties;
DistinguishedFolderIdType[] folderIDArray = new DistinguishedFolderIdType[1];
folderIDArray[0] = new DistinguishedFolderIdType();
folderIDArray[0].Id = DistinguishedFolderIdNameType.calendar;
//
folderIDArray[0].Mailbox = new EmailAddressType();
folderIDArray[0].Mailbox.EmailAddress = email;
findItemRequest.ParentFolderIds = folderIDArray;
// Define the traversal type.
findItemRequest.Traversal = ItemQueryTraversalType.Shallow;
try
{
// Send the FindItem request and get the response.
FindItemResponseType findItemResponse = esb.FindItem(findItemRequest);
// Access the response message.
ArrayOfResponseMessagesType responseMessages = findItemResponse.ResponseMessages;
ResponseMessageType[] rmta = responseMessages.Items;
int folderNumber = 0;
foreach (ResponseMessageType rmt in rmta)
{
// One FindItemResponseMessageType per folder searched.
FindItemResponseMessageType firmt = rmt as FindItemResponseMessageType;
if (firmt.RootFolder == null)
continue;
FindItemParentType fipt = firmt.RootFolder;
object obj = fipt.Item;
// FindItem contains an array of items.
if (obj is ArrayOfRealItemsType)
{
ArrayOfRealItemsType items =
(obj as ArrayOfRealItemsType);
if (items.Items == null)
{
folderNumber++;
}
else
{
foreach (ItemType it in items.Items)
{
if (it is CalendarItemType)
{
CalendarItemType cal = (CalendarItemType)it;
List<string> ce = new List<string>();
ce.Add(cal.Location);
ce.Add(cal.Start.ToShortDateString() + " " + cal.Start.ToShortTimeString());
ce.Add(cal.End.ToShortDateString() + " " + cal.End.ToShortTimeString());
ce.Add(cal.Subject);
if (cal.Organizer != null)
{
ce.Add(cal.Organizer.Item.Name);
}
calendarEvents.Add(ce);
Console.WriteLine(cal.Subject + " " + cal.Start.ToShortDateString() + " " + cal.Start.ToShortTimeString() + " " + cal.Location);
}
}
folderNumber++;
}
}
}
}
catch (Exception e)
{
throw;
}
finally
{
}
return calendarEvents;
}
In EWS you need to query one folder at a time, for non default folders you will first need to find the FolderId before you can then query the appointments (or items) within a Folder. To find all the Calendar folders in a Mailbox you need to use the FindFolder operation and create a restriction to limit the result to folder with a FolderClass of IPF.Appointment eg
// Create the request and specify the travesal type.
FindFolderType findFolderRequest = new FindFolderType();
findFolderRequest.Traversal = FolderQueryTraversalType.Deep;
// Define the properties that are returned in the response.
FolderResponseShapeType responseShape = new FolderResponseShapeType();
responseShape.BaseShape = DefaultShapeNamesType.Default;
findFolderRequest.FolderShape = responseShape;
// Identify which folders to search.
DistinguishedFolderIdType[] folderIDArray = new DistinguishedFolderIdType[1];
folderIDArray[0] = new DistinguishedFolderIdType();
folderIDArray[0].Id = DistinguishedFolderIdNameType.msgfolderroot;
IsEqualToType iet = new IsEqualToType();
PathToUnindexedFieldType FolderClass = new PathToUnindexedFieldType();
FolderClass.FieldURI = UnindexedFieldURIType.folderFolderClass;
iet.Item = FolderClass;
FieldURIOrConstantType constantType = new FieldURIOrConstantType();
ConstantValueType constantValueType = new ConstantValueType();
constantValueType.Value = "IPF.Appointment";
constantType.Item = constantValueType;
iet.FieldURIOrConstant = constantType;
// Add the folders to search to the request.
RestrictionType restriction = new RestrictionType();
restriction.Item = iet;
findFolderRequest.Restriction = restriction;
findFolderRequest.ParentFolderIds = folderIDArray;
try
{
// Send the request and get the response.
FindFolderResponseType findFolderResponse = esb.FindFolder(findFolderRequest);
// Get the response messages.
ResponseMessageType[] rmta = findFolderResponse.ResponseMessages.Items;
foreach (ResponseMessageType rmt in rmta)
{
// Cast to the correct response message type.
if (((FindFolderResponseMessageType)rmt).ResponseClass == ResponseClassType.Success) {
foreach (FolderType folder in ((FindFolderResponseMessageType)rmt).RootFolder.Folders) {
Console.WriteLine(folder.DisplayName);
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
You also might want to look at using the EWS Managed API which will save you greatly time and the amount of code you need to write
Cheers
Glen

morphline#flume - looking for regexp change and a hash function

Fluming data to Solr. Data get changed using morphline.
Looking for a couple of basic functions in morphline library:
create a hash value based on other attribute values (e.g. hash=("sha-1", timestamp,message,host,..)
change case of an attribute's string value (something more generic like regexp_replace would do as well).
Don't want yet to write a custom Java handler.. I think there is should be an easier way :)
(1) Non-generic solution for hash function as I wasn't able to find out-of-the-box morphline implementation, hard-coded SHA-1 (eg. no for loop, hard-coded 20 bytes):
{ java {
imports : "import java.security.*;"
code: """
try {
MessageDigest digest = MessageDigest.getInstance("SHA-1");
String value;
value = (String) record.getFirstValue("message");
if (value != null) { digest.update(value.getBytes("ISO-8859-1"), 0, value.length()); }
value = (String) record.getFirstValue("timestamp");
if (value != null) { digest.update(value.getBytes("ISO-8859-1"), 0, value.length()); }
value = (String) record.getFirstValue("hostname");
if (value != null) { digest.update(value.getBytes("ISO-8859-1"), 0, value.length()); }
byte[] a = digest.digest();
record.replaceValues("id"
, String.format("%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X"
,a[0] ,a[1] ,a[2] ,a[3] ,a[4] ,a[5] ,a[6] ,a[7] ,a[8] ,a[9] //SHA-1 has exactly 20 bytes
,a[10],a[11],a[12],a[13],a[14],a[15],a[16],a[17],a[18],a[19]) );
}
catch (java.security.NoSuchAlgorithmException e) { logger.error("hash to id: caught NoSuchAlgorithmException for SHA-1"); }
catch (java.io.UnsupportedEncodingException e) { logger.error("hash to id: caught UnsupportedEncodingException"); }
finally {
return child.process(record);
}
"""
}
}
(2) Non-generic implementaion for lower case transformation (I would hope morphline had just something like regexp_replace) :
java {
code: """
String program = (String) record.getFirstValue("program");
String program_lc = program.toLowerCase();
if (! program.equals(program_lc) )
{ record.replaceValues("program", program_lc); }
return child.process(record);
"""
}

Resources