Example usage for org.json JSONObject getJSONArray

List of usage examples for org.json JSONObject getJSONArray

Introduction

In this page you can find the example usage for org.json JSONObject getJSONArray.

Prototype

public JSONArray getJSONArray(String key) throws JSONException 

Source Link

Document

Get the JSONArray value associated with a key.

Usage

From source file:org.dasein.cloud.joyent.compute.Machine.java

private VirtualMachine toVirtualMachine(JSONObject ob) throws CloudException, InternalException {
    if (ob == null) {
        return null;
    }/*  ww w. j a v a  2  s .  c o m*/
    try {
        VirtualMachine vm = new VirtualMachine();

        vm.setClonable(false);
        vm.setImagable(false);
        vm.setLastPauseTimestamp(-1L);
        vm.setPersistent(true);
        vm.setProviderDataCenterId(provider.getContext().getRegionId() + "a");
        vm.setProviderOwnerId(provider.getContext().getAccountNumber());
        vm.setProviderRegionId(provider.getContext().getRegionId());
        vm.setTerminationTimestamp(-1L);

        if (ob.has("id")) {
            vm.setProviderVirtualMachineId(ob.getString("id"));
        }
        if (ob.has("name")) {
            vm.setName(ob.getString("name"));
        }
        if (ob.has("ips")) {
            JSONArray ips = ob.getJSONArray("ips");
            ArrayList<String> pubIp = new ArrayList<String>();
            ArrayList<String> privIp = new ArrayList<String>();

            for (int i = 0; i < ips.length(); i++) {
                String addr = ips.getString(i);
                boolean pub = false;

                if (!addr.startsWith("10.") && !addr.startsWith("192.168.")) {
                    if (addr.startsWith("172.")) {
                        String[] nums = addr.split("\\.");

                        if (nums.length != 4) {
                            pub = true;
                        } else {
                            try {
                                int x = Integer.parseInt(nums[1]);

                                if (x < 16 || x > 31) {
                                    pub = true;
                                }
                            } catch (NumberFormatException ignore) {
                                // ignore
                            }
                        }
                    } else {
                        pub = true;
                    }
                }
                if (pub) {
                    pubIp.add(addr);
                } else {
                    privIp.add(addr);
                }
            }
            if (!pubIp.isEmpty()) {
                vm.setPublicIpAddresses(pubIp.toArray(new String[pubIp.size()]));
            }
            if (!privIp.isEmpty()) {
                vm.setPrivateIpAddresses(privIp.toArray(new String[privIp.size()]));
            }
        }
        if (ob.has("metadata")) {
            JSONObject md = ob.getJSONObject("metadata");
            JSONArray names = md.names();

            if (names != null) {
                for (int i = 0; i < names.length(); i++) {
                    String name = names.getString(i);

                    if (name.equals("dsnDescription")) {
                        vm.setDescription(md.getString(name));
                    } else if (name.equals("dsnTrueImage")) {
                        vm.setProviderMachineImageId(md.getString(name));
                    } else if (name.equals("dsnTrueProduct")) {
                        vm.setProductId(md.getString(name));
                    } else {
                        vm.addTag(name, md.getString(name));
                    }
                }
            }
        }
        if (vm.getProviderMachineImageId() == null && ob.has("dataset")) {
            vm.setProviderMachineImageId(getImageIdFromUrn(ob.getString("dataset")));
        }
        if (ob.has("created")) {
            vm.setCreationTimestamp(provider.parseTimestamp(ob.getString("created")));
        }
        vm.setPausable(false); // can't ever pause/resume joyent vms
        vm.setRebootable(false);
        if (ob.has("state")) {
            vm.setCurrentState(toState(ob.getString("state")));

            if (VmState.RUNNING.equals(vm.getCurrentState())) {
                vm.setRebootable(true);
            } else if (VmState.STOPPED.equals(vm.getCurrentState())) {
                vm.setImagable(true);
            }
        }
        vm.setLastBootTimestamp(vm.getCreationTimestamp());
        if (vm.getName() == null) {
            vm.setName(vm.getProviderVirtualMachineId());
        }
        if (vm.getDescription() == null) {
            vm.setDescription(vm.getName());
        }
        discover(vm);
        boolean isVMSmartOs = (vm.getPlatform().equals(Platform.SMARTOS));
        if (vm.getProductId() == null) {
            VirtualMachineProduct d = null;
            int disk, ram;

            disk = ob.getInt("disk");
            ram = ob.getInt("memory");
            for (VirtualMachineProduct prd : listProducts(vm.getArchitecture())) {
                d = prd;
                boolean isProductSmartOs = prd.getName().contains("smartos");
                if (prd.getRootVolumeSize().convertTo(Storage.MEGABYTE).intValue() == disk
                        && prd.getRamSize().intValue() == ram) {
                    if (isVMSmartOs && !isProductSmartOs) {
                        continue;
                    }
                    if (!isVMSmartOs && isProductSmartOs) {
                        continue;
                    }
                    vm.setProductId(prd.getProviderProductId());
                    break;
                }
            }
            if (vm.getProductId() == null) {
                vm.setProductId(d.getProviderProductId());
            }
        }
        return vm;
    } catch (JSONException e) {
        throw new CloudException(e);
    }
}

From source file:com.openerp.addons.note.AddFollowerFragment.java

public Boolean getPartnersFromServer() {

    boolean loaded = true;
    if (!flag) {/*  www. j  a va  2  s. co m*/
        res_partners = new Res_PartnerDBHelper(scope.context());
        oe = res_partners.getOEInstance();
        try {
            ArrayList<Fields> cols = res_partners.getServerColumns();
            JSONObject fields = new JSONObject();
            for (Fields field : cols) {
                fields.accumulate("fields", field.getName());
            }
            JSONObject domain = new JSONObject();
            JSONArray ids = JSONDataHelper.intArrayToJSONArray(oe.getAllIds(res_partners));

            domain.accumulate("domain", new JSONArray("[[\"id\", \"not in\", " + ids.toString() + "]]"));

            JSONObject result = oe.search_read("res.partner", fields, domain, 0, 0, null, null);

            for (int i = 0; i < result.getInt("length"); i++) {
                JSONObject row = result.getJSONArray("records").getJSONObject(i);
                HashMap<String, Object> rowHash = new HashMap<String, Object>();
                @SuppressWarnings("unchecked")
                Iterator<String> keys = row.keys();

                while (keys.hasNext()) {
                    String key = keys.next();
                    rowHash.put(key, row.get(key));
                }
                final OEListViewRows listRow = new OEListViewRows(row.getInt("id"), rowHash);

                scope.context().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        listRows.add(listRow);
                        listAdapters.refresh(listRows);
                    }
                });
                flag = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        loaded = false;
    }
    return loaded;
}

From source file:org.upv.satrd.fic2.fe.connectors.citySDK.Fusion.java

public static FusionResult fusion(JSONObject poi1, JSONObject poi2, FusionRule fr, Logger log) {

    FusionResult fusionresult = null;/*from ww  w  .ja v a2  s  . c  o m*/
    String name_source = "";
    if (log == null)
        log = Fusion.log;

    try {

        int namePos1 = CommonUtils.getPropertyPos(poi1, "name", log);
        String source1 = poi1.getJSONArray("label").getJSONObject(namePos1).getString("base");
        int namePos2 = CommonUtils.getPropertyPos(poi2, "name", log);
        String source2 = poi2.getJSONArray("label").getJSONObject(namePos2).getString("base");

        //Fusion label tag
        JSONArray object1 = poi1.getJSONArray("label");
        JSONArray object2 = poi2.getJSONArray("label");

        JSONArray object3 = new JSONArray();
        int i = 0;

        //TODO we are not combining the location.address element of both POIs. Now we just take the first one (the one that conditions position)   

        //////////////////////
        //Add name. We take the one that first appears in the name ArrayList
        //////////////////////
        for (int j = 0; j < fr.getName().size(); j++) {
            if (fr.getName().get(j).equals(source1)) {
                int namePos = CommonUtils.getPropertyPos(poi1, "name", log);
                object3.put(i, poi1.getJSONArray("label").getJSONObject(namePos));
                i++;
                log.info("Fusion.fusion(). Fusioning. Inserting name from source: " + source1);
                name_source = source1;
                break;
            }
            if (fr.getName().get(j).equals(source2)) {
                int namePos = CommonUtils.getPropertyPos(poi2, "name", log);
                object3.put(i, poi2.getJSONArray("label").getJSONObject(namePos));
                log.info("Fusion.fusion(). Fusioning. Inserting name from source: " + source2);
                name_source = source2;
                i++;
                break;
            }
        }

        ////////////////////
        //Add other labels
        ////////////////////
        ArrayList<String> allObjects = new ArrayList<String>();

        for (int j = 0; j < object1.length(); j++) {
            //If is not name
            if (!poi1.getJSONArray("label").getJSONObject(j).get("term").equals("name")) {
                String value = (String) poi1.getJSONArray("label").getJSONObject(j).get("value");
                //If is not repeated
                if (!allObjects.contains(value)) {
                    object3.put(i, poi1.getJSONArray("label").getJSONObject(j));
                    allObjects.add(value);
                    i++;
                }
            }

        }
        for (int j = 0; j < object2.length(); j++) {
            //If is not name
            if (!poi2.getJSONArray("label").getJSONObject(j).get("term").equals("name")) {
                String value = (String) poi2.getJSONArray("label").getJSONObject(j).get("value");
                //If is not repeated
                if (!allObjects.contains(value)) {
                    object3.put(i, poi2.getJSONArray("label").getJSONObject(j));
                    allObjects.add(value);
                    i++;
                }
            }
        }

        //We'll store the final POI in poi1. We preserve the structure and override step by step. Up to now only label
        poi1.put("label", object3);

        ///////////////////////////////////
        //Fusion description tag. It is possible that this tag does not appear in some POIs, so we must be careful 
        //////////////////////////////////
        try {
            object1 = poi1.getJSONArray("description");
        } catch (JSONException e) {
            object1 = null;
            log.warn("Fusion.fusion(). Fusioning. POI object from source " + source1
                    + " does not have description. We'll take the description from the other POI independently of the FusionRule");
        }
        try {
            object2 = poi2.getJSONArray("description");
        } catch (JSONException e) {
            object2 = null;
            log.warn("Fusion.fusion(). Fusioning. POI object from source " + source2
                    + " does not have description. We'll take the description from the other POI independently of the FusionRule");
        }

        object3 = new JSONArray();
        i = 0;

        if (object1 == null) {
            object3.put(i, poi2.getJSONArray("description").getJSONObject(i));
        } else {
            if (object2 == null) {
                object3.put(i, poi1.getJSONArray("description").getJSONObject(i));
            } else {

                for (int j = 0; j < fr.getDescription().size(); j++) {
                    if (fr.getDescription().get(j).equals(source1)) {
                        if (poi1.getJSONArray("description").length() > 0) {
                            object3.put(i, poi1.getJSONArray("description").getJSONObject(i));
                            log.info("Fusion.fusion(). Fusioning. Inserting description from source: "
                                    + source1);
                            break;
                        }
                    }
                    if (fr.getDescription().get(j).equals(source2)) {
                        if (poi2.getJSONArray("description").length() > 0) {
                            object3.put(i, poi2.getJSONArray("description").getJSONObject(i));
                            log.info(
                                    "Fusion.fusion().Fusioning. Inserting description from source: " + source2);
                            break;
                        }
                    }
                }
            }
        }

        //Override description field
        poi1.put("description", object3);

        //////////////////////////
        //Fusion category tag
        /////////////////////////
        try {
            object1 = poi1.getJSONArray("category");
        } catch (JSONException e) {
            object1 = null;
            log.warn("Fusion.fusion(). Fusioning. POI object from source " + source1
                    + " does not have category.");
        }
        try {
            object2 = poi2.getJSONArray("category");
        } catch (JSONException e) {
            object1 = null;
            log.warn("Fusion.fusion(). Fusioning. POI object from source " + source2
                    + " does not have category.");
        }

        allObjects = new ArrayList<String>(); //We don't need it as we will add all categories, we'll not check if they are repeated   
        object3 = new JSONArray();
        i = 0;

        if (object1 == null) {
            object3.put(i, poi2.getJSONArray("category").getJSONObject(i));
        } else {
            if (object2 == null) {
                object3.put(i, poi1.getJSONArray("category").getJSONObject(i));
            } else {

                for (int j = 0; j < object1.length(); j++) {
                    String value = (String) object1.getJSONObject(j).get("value");

                    object3.put(i, object1.getJSONObject(j));
                    allObjects.add(value);
                    i++;
                }
                for (int j = 0; j < object2.length(); j++) {
                    String value = (String) object2.getJSONObject(j).get("value");

                    object3.put(i, object2.getJSONObject(j));
                    allObjects.add(value);
                    i++;
                }

            }
        }

        //Override category
        poi1.put("category", object3);

        ///////////////////////////
        //Fusion link tag
        ///////////////////////////
        try {
            object1 = poi1.getJSONArray("link");
        } catch (JSONException e) {
            object1 = null;
            log.warn("Fusion.fusion().Fusioning. POI object from source " + source1 + " does not have link.");
        }
        try {
            object2 = poi2.getJSONArray("link");

        } catch (JSONException e) {
            object2 = null;
            log.warn("Fusion.fusion().Fusioning. POI object from source " + source2 + " does not have link.");
        }

        allObjects = new ArrayList<String>();

        object3 = new JSONArray();
        i = 0;

        if (object1 != null) {
            for (int j = 0; j < object1.length(); j++) {
                String value = (String) object1.getJSONObject(j).get("value");
                //If is not repeated
                if (!allObjects.contains(value)) {
                    object3.put(i, object1.getJSONObject(j));
                    allObjects.add(value);
                    i++;
                }
            }
        }

        if (object2 != null) {
            for (int j = 0; j < object2.length(); j++) {
                String value = (String) object2.getJSONObject(j).get("value");
                //If is not repeated
                if (!allObjects.contains(value)) {
                    object3.put(i, object2.getJSONObject(j));
                    allObjects.add(value);
                    i++;
                }
            }
        }

        //Override link
        poi1.put("link", object3);

        //Finally we should override the publisher part to say 'Fusion Engine'. Anyway we can set it up during the storage of the POI in the database

        //Create the FusionResult return object
        fusionresult = new FusionResult(poi1, name_source);

    } catch (Exception e) {
        System.out.println("Error.Fusion.fusion(): " + e.getMessage());
        log.error("Error.Fusion.fusion(): " + e.getMessage());
    }

    return fusionresult;

}

From source file:org.upv.satrd.fic2.fe.connectors.citySDK.Fusion.java

public static int save(Connection con, JSONObject poi, String category, String name_sourceName,
        String position_sourceName, ArrayList<POISource> poisourceArray, Logger log) {

    Integer poiid = -1;//w  w w  .j  av a2  s.  c o  m
    if (log == null)
        log = Fusion.log;

    try {
        //Generate the POI object

        Double lat = new Double(CommonUtils.getLatitude(poi, log));
        Double lon = new Double(CommonUtils.getLongitude(poi, log));
        String name = CommonUtils.getName(poi, log);
        Date date = CommonUtils.getFormatedDateAsDate();

        POI poi_object = new POI(name, lat, lon, date);

        poiid = POI.savePOI(con, poi_object, log);

        if (poiid != null) {

            //This is just visual output of pois being inserted. You may comment/remove these two lines
            System.out.println("poiid: " + poiid);
            System.out.println(poi.toString());

            JSONArray object;
            JSONObject aux;
            String type, value, source, language, license;
            Date updated = null;
            Integer licenseId = null;
            Integer typeId = null;
            Integer sourceId = null;

            //Insert category in POICategory table. We need to get previously the category_id                
            Category cat = Category.getCategoryClassByName(con, category, log);
            POICategory poicategory = new POICategory(poiid, cat.getId());
            POICategory.savePOICategory(con, poicategory, log);

            //We need to fill the POISource table
            for (int p = 0; p < poisourceArray.size(); p++) {

                org.upv.satrd.fic2.fe.db.POISource poisource = poisourceArray.get(p);
                poisource.setPOiId(poiid);
                org.upv.satrd.fic2.fe.db.POISource.savePOISource(con, poisource, log);
            }

            //Insert the address value
            String address = CommonUtils.getAddress(poi, log);
            if (address != null) {

                type = "address";

                LabelType labeltype = LabelType.getLabelTypeClassByName(con, type, log);

                if (labeltype == null) {
                    //the ' address' LabelType has not yet been inserted (probably it should during initialization). Create it
                    labeltype = new LabelType(type);
                    typeId = LabelType.saveLabelType(con, labeltype, log);
                } else {
                    typeId = labeltype.getId();
                }

                //value
                value = address;

                //'source' is the one we have used for the position
                sourceId = Source.getSourceClassByName(con, position_sourceName, log).getId();

                language = "";

                license = "";

                updated = CommonUtils.getFormatedDateAsDate();

                POILabel poilabel = new POILabel(poiid, typeId, value, sourceId, language, licenseId, updated);
                POILabel.savePOILabel(con, poilabel, log);

            }

            //Insert description in the POILabel table
            try {
                object = poi.getJSONArray("description");
            } catch (JSONException e) {
                object = null;
                log.debug(
                        "Fusion.save(). Saving POI. The POI does not have any description. No label to insert in the POILabel table");
            }

            if (object != null) {

                aux = object.getJSONObject(0);

                //'term' should always be there. It should say 'description'
                type = (String) aux.get("term");

                LabelType labeltype = LabelType.getLabelTypeClassByName(con, type, log);

                if (labeltype == null) {
                    //the ' description' LabelType has not yet been inserted (probably it should during initialization). Create it
                    labeltype = new LabelType(type);
                    typeId = LabelType.saveLabelType(con, labeltype, log);
                } else {
                    typeId = labeltype.getId();
                }

                //'value' should always be there. However some POIS do not have a value field in the description object,
                // so we need to catch this potential Exception 
                try {
                    value = (String) aux.get("value");
                } catch (JSONException e) {
                    value = " ";
                    log.debug(
                            "Fusion.save().Saving POI. The POI has description, but no value field. It will be empty");
                }

                //'source' should always be there
                source = (String) aux.get("base");
                sourceId = Source.getSourceClassByName(con, source, log).getId();

                try {
                    language = (String) aux.get("lang");
                } catch (JSONException e) {
                    language = "";
                    //log.debug("Saving POI. The 'description' field does not have a 'lang' subfield" );
                }

                try {
                    license = (String) aux.get("license");
                    licenseId = License.getLicenseClassByName(con, license, log).getId();
                } catch (JSONException e) {
                    license = "";
                    //log.debug("Saving POI. The 'description' field does not have a 'license' subfield" );
                }

                // FIXME: we should use updated = (String)aux.get("updated");
                updated = CommonUtils.getFormatedDateAsDate();

                POILabel poilabel = new POILabel(poiid, typeId, value, sourceId, language, licenseId, updated);
                POILabel.savePOILabel(con, poilabel, log);

            }

            //Generate poilabel for 'name' and 'position' in the POI table. So we can know from which source 'name' and 'position' comes from.
            //In these cases the 'value' field does not make sense, so we insert "-1" instead of null 
            //name
            LabelType labeltype = LabelType.getLabelTypeClassByName(con, "name", log);
            Integer name_labeltypeid;
            if (labeltype == null) {
                //the ' name' LabelType has not yet been inserted (probably it should during initialization). Create it
                labeltype = new LabelType("name");
                name_labeltypeid = LabelType.saveLabelType(con, labeltype, log);
            } else {
                name_labeltypeid = labeltype.getId();
            }
            sourceId = Source.getSourceClassByName(con, name_sourceName, log).getId();
            POILabel poilabel_aux = new POILabel(poiid, name_labeltypeid, name_sourceName, sourceId, null, null,
                    updated);
            POILabel.savePOILabel(con, poilabel_aux, log);
            //position. Here we do not need to save the position (analog as with name)
            labeltype = LabelType.getLabelTypeClassByName(con, "position", log);
            Integer position_labeltypeid;
            if (labeltype == null) {
                //the ' position' LabelType has not yet been inserted (probably it should during initialization). Create it
                labeltype = new LabelType("position");
                position_labeltypeid = LabelType.saveLabelType(con, labeltype, log);
            } else {
                position_labeltypeid = labeltype.getId();
            }
            sourceId = Source.getSourceClassByName(con, position_sourceName, log).getId();
            poilabel_aux = new POILabel(poiid, position_labeltypeid, position_sourceName, sourceId, null, null,
                    updated);
            POILabel.savePOILabel(con, poilabel_aux, log);

            //Insert link in the POILabel table. The link field has as term values: web, url               
            try {
                object = poi.getJSONArray("link");
            } catch (JSONException e) {
                object = null;
                log.debug(
                        "Fusion.save(). Saving POI. Fusion object does not have any link. No label to insert in the POILabel table");
            }
            if (object != null) {

                for (int i = 0; i < object.length(); i++) {
                    aux = object.getJSONObject(i);

                    //'term' should always be there
                    //type = (String)aux.get("term"); We do not use this as we may find 'web' in poiproxy and 'url' in dbpedia
                    type = "link";
                    labeltype = LabelType.getLabelTypeClassByName(con, type, log);
                    if (labeltype == null) {
                        labeltype = new LabelType(type);
                        typeId = LabelType.saveLabelType(con, labeltype, log);
                    } else {
                        typeId = LabelType.getLabelTypeClassByName(con, type, log).getId();
                    }

                    //'value' should always be there
                    value = (String) aux.get("value");

                    //'source' should always be there
                    source = (String) aux.get("base");
                    sourceId = Source.getSourceClassByName(con, source, log).getId();

                    try {
                        language = (String) aux.get("lang");
                    } catch (JSONException e) {
                        language = "";
                        //og.debug("Saving POI. The 'link' field does not have a 'lang' subfield" );
                    }

                    try {
                        license = (String) aux.get("license");
                        licenseId = License.getLicenseClassByName(con, license, log).getId();
                    } catch (JSONException e) {
                        licenseId = null;
                        //log.debug("Saving POI. The 'link' field does not have a 'license' subfield" );
                    }

                    // FIXME: we should use updated = (String)aux.get("updated");
                    updated = CommonUtils.getFormatedDateAsDate();

                    POILabel poilabel = new POILabel(poiid, typeId, value, sourceId, language, licenseId,
                            updated);
                    POILabel.savePOILabel(con, poilabel, log);

                }
            }

            //Insert all additional labels in the POILabel table.             
            try {
                object = poi.getJSONArray("label");
            } catch (JSONException e) {
                object = null;
                log.debug(
                        "Fusion.save(). Saving POI. Fusion object does not have any labels. No label to insert in the POILabel table");
            }
            if (object != null) {
                for (int i = 0; i < object.length(); i++) {

                    aux = object.getJSONObject(i);

                    //'term' should always be there
                    type = (String) aux.get("term");
                    labeltype = LabelType.getLabelTypeClassByName(con, type, log);
                    if (labeltype == null) {
                        labeltype = new LabelType(type);
                        typeId = LabelType.saveLabelType(con, labeltype, log);
                    } else {
                        typeId = LabelType.getLabelTypeClassByName(con, type, log).getId();
                    }

                    //Skip id term. It will be translated in the POISource table
                    if (!type.equalsIgnoreCase("id")) {

                        //'value' should always be there. However some POIS do not have a value field in the description object,
                        // so we need to catch this potential Exception 
                        try {
                            value = (String) aux.get("value");
                        } catch (JSONException e) {
                            value = " ";
                            log.debug(
                                    "Fusion.save(). Saving POI. The POI has a label, but no value field. It will be empty");
                        }

                        //'source' should always be there
                        source = (String) aux.get("base");
                        sourceId = Source.getSourceClassByName(con, source, log).getId();

                        try {
                            language = (String) aux.get("lang");
                        } catch (JSONException e) {
                            language = "";
                            //log.debug("Saving POI. This 'label' field does not have a 'lang' subfield" );
                        }

                        try {
                            license = (String) aux.get("license");
                            License license_aux = License.getLicenseClassByName(con, license, log);
                            if (license_aux == null)
                                licenseId = null;
                            else
                                licenseId = license_aux.getId();

                        } catch (Exception e) {
                            licenseId = null;
                            //log.debug("Saving POI. This 'label' field does not have a 'license' subfield" );                            
                        }

                        // FIXME: we should use updated = (String)aux.get("updated");
                        updated = CommonUtils.getFormatedDateAsDate();

                        POILabel poilabel = new POILabel(poiid, typeId, value, sourceId, language, licenseId,
                                updated);
                        POILabel.savePOILabel(con, poilabel, log);

                    }
                }
            }

        }

    } catch (Exception e) {
        System.out.println("Error.Fusion. save(): " + e.getMessage());
        log.error("Error.Fusion.save(): " + e.getMessage());
    }
    return poiid;
}

From source file:test.TestJSON.java

public static void main(String[] args) {
    try {//www .  j  a va  2s  . c o m
        String origin = "{\n" + "    \"retCode\": 1,\n" + "    \"retDesc\": \"?\",\n"
                + "    \"clerkInfo\": {\n" + "        \"MemberID\": \"\",\n"
                + "        \"StatusCode\": \"2011\",\n" + "        \"StatusText\": \"??\",\n"
                + "        \"MemberText\": \"\",\n" + "        \"MemberPhone\": \"\",\n"
                + "        \"MemberName\": \"\",\n" + "        \"IntegralName\": \"\",\n"
                + "        \"TradingType\": \"\",\n" + "        \"ResidualIntegral\": \"\",\n"
                + "        \"CardType\": \"\"\n" + "    }\n" + "}";

        JSONObject jsonObj = new JSONObject(origin);
        String clerkInfo = jsonObj.getString("clerkInfo");
        JSONObject jsonObjArray = new JSONObject(clerkInfo);
        JSONArray jsonArray = jsonObjArray.getJSONArray(clerkInfo);
        System.out.println(clerkInfo);
    } catch (JSONException ex) {
        System.out.println(ex.getMessage());
    }
}

From source file:com.hp.mqm.atrf.octane.services.OctaneEntityService.java

private OctaneEntityCollection parseCollection(JSONObject jsonObj) {
    OctaneEntityCollection coll = new OctaneEntityCollection();

    int total = jsonObj.getInt("total_count");
    coll.setTotalCount(total);/*from ww w  .ja v a 2 s . c o  m*/

    if (jsonObj.has("exceeds_total_count")) {
        boolean exceedsTotalCount = jsonObj.getBoolean("exceeds_total_count");
        coll.setExceedsTotalCount(exceedsTotalCount);
    }

    JSONArray entitiesJArr = jsonObj.getJSONArray("data");
    for (int i = 0; i < entitiesJArr.length(); i++) {

        JSONObject entObj = entitiesJArr.getJSONObject(i);
        OctaneEntity entity = parseEntity(entObj);

        coll.getData().add(entity);
    }

    return coll;
}

From source file:org.schedulesdirect.grabber.ScheduleTask.java

protected void fetchStations(Map<String, Collection<String>> ids) {
    if (ids == null || ids.size() == 0) {
        LOG.info("No stale schedules identified; skipping schedule download!");
        return;/* w w w  .  ja  v  a 2 s  .c o  m*/
    }
    DefaultJsonRequest req = factory.get(DefaultJsonRequest.Action.POST, RestNouns.SCHEDULES, clnt.getHash(),
            clnt.getUserAgent(), clnt.getBaseUrl());
    JSONArray data = new JSONArray();
    Iterator<String> idItr = ids.keySet().iterator();
    while (idItr.hasNext()) {
        String id = idItr.next();
        JSONObject o = new JSONObject();
        o.put("stationID", id);
        Collection<String> dates = new ArrayList<>();
        for (String date : ids.get(id))
            dates.add(date);
        o.put("date", dates);
        data.put(o);
    }
    try {
        JSONArray resp = Config.get().getObjectMapper().readValue(req.submitForJson(data), JSONArray.class);
        for (int i = 0; i < resp.length(); ++i) {
            JSONObject o = resp.getJSONObject(i);
            if (!JsonResponseUtils.isErrorResponse(o)) {
                JSONArray sched = o.getJSONArray("programs");
                String schedId = o.getString("stationID");
                Date expiry = new Date(System.currentTimeMillis() - Grabber.MAX_AIRING_AGE);
                for (int j = 0; j < sched.length(); ++j) {
                    try {
                        JSONObject airing = sched.getJSONObject(j);
                        Date end = AiringUtils.getEndDate(airing);
                        String progId = airing.getString("programID");
                        if (!end.before(expiry)) {
                            String md5 = airing.getString("md5");
                            cache.markIfDirty(progId, md5);
                        } else
                            LOG.debug(String.format("Expired airing discovered and ignored! [%s; %s; %s]",
                                    progId, o.getString("stationID"), end));
                        synchronized (ScheduleTask.class) {
                            List<JSONObject> objs = FULL_SCHEDS.get(schedId);
                            if (objs == null) {
                                objs = new ArrayList<JSONObject>();
                                FULL_SCHEDS.put(schedId, objs);
                            }
                            objs.add(airing);
                        }
                    } catch (JSONException e) {
                        LOG.warn(String.format("JSONException [%s]", o.optString("stationID", "unknown")), e);
                    }
                }
            } else if (JsonResponseUtils.getErrorCode(o) == ApiResponse.SCHEDULE_QUEUED)
                LOG.warn(String.format(
                        "StationID %s is queued server side and will be downloaded on next EPG update!",
                        o.getString("stationID")));
            else
                throw new InvalidJsonObjectException("Error received for schedule", o.toString(3));
        }
    } catch (JSONException | JsonParseException e) {
        Grabber.failedTask = true;
        LOG.fatal("Fatal JSON error!", e);
        throw new RuntimeException(e);
    } catch (IOException e) {
        Grabber.failedTask = true;
        LOG.error("IOError receiving schedule data! Filling cache with empty schedules!", e);
        try {
            JSONArray schedIds = this.req;
            for (int i = 0; i < schedIds.length(); ++i) {
                String id = schedIds.getString(i);
                Path p = vfs.getPath("schedules", String.format("%s.txt", id));
                if (!Files.exists(p)) {
                    JSONObject emptySched = new JSONObject();
                    emptySched.put("stationID", id);
                    emptySched.put("programs", new JSONArray());
                    Files.write(p, emptySched.toString(3).getBytes(ZipEpgClient.ZIP_CHARSET));
                }
            }
        } catch (Exception x) {
            LOG.error("Unexpected error!", x);
            throw new RuntimeException(x);
        }
    }
}

From source file:com.github.caofangkun.bazelipse.command.IdeBuildInfo.java

/**
 * Construct an {@link IdeBuildInfo} object from a {@link JSONObject}.
 *//*from   w w  w.j a  v a 2  s . c om*/
IdeBuildInfo(JSONObject object) {
    jars = jsonToJarArray(object.getJSONArray("jars"));
    generatedJars = jsonToJarArray(object.getJSONArray("generated_jars"));
    location = object.getString("build_file_artifact_location");
    kind = object.getString("kind");
    label = object.getString("label");
    this.deps = jsonToStringArray(object.getJSONArray("dependencies"));
    this.sources = jsonToStringArray(object.getJSONArray("sources"));
}

From source file:com.foxykeep.datadroidpoc.data.factory.CityListJsonFactory.java

public static Bundle parseResult(String wsResponse) throws DataException {
    ArrayList<City> cityList = new ArrayList<City>();

    try {//w w  w  .j  ava2 s . c  o  m
        JSONObject parser = new JSONObject(wsResponse);
        JSONObject jsonRoot = parser.getJSONObject(JSONTag.CITY_LIST_ELEM_CITIES);
        JSONArray jsonPersonArray = jsonRoot.getJSONArray(JSONTag.CITY_LIST_ELEM_CITY);
        int size = jsonPersonArray.length();
        for (int i = 0; i < size; i++) {
            JSONObject jsonPerson = jsonPersonArray.getJSONObject(i);
            City city = new City();

            city.name = jsonPerson.getString(JSONTag.CITY_LIST_ELEM_CITY_NAME);
            city.postalCode = jsonPerson.getString(JSONTag.CITY_LIST_ELEM_CITY_POSTAL_CODE);
            city.state = jsonPerson.getString(JSONTag.CITY_LIST_ELEM_CITY_STATE);
            city.country = jsonPerson.getString(JSONTag.CITY_LIST_ELEM_CITY_COUNTRY);

            cityList.add(city);
        }
    } catch (JSONException e) {
        Log.e(TAG, "JSONException", e);
        throw new DataException(e);
    }

    Bundle bundle = new Bundle();
    bundle.putParcelableArrayList(PoCRequestFactory.BUNDLE_EXTRA_CITY_LIST, cityList);
    return bundle;
}

From source file:org.openmrs.mobile.listeners.findPatients.FindPatientListener.java

@Override
public void onResponse(JSONObject response) {
    List<Patient> patientsList = new ArrayList<Patient>();
    mLogger.d(response.toString());/*from w  w w . j  a v  a2s .c o  m*/

    try {
        JSONArray patientsJSONList = response.getJSONArray(BaseManager.RESULTS_KEY);
        for (int i = 0; i < patientsJSONList.length(); i++) {
            patientsList.add(PatientMapper.map(patientsJSONList.getJSONObject(i)));
        }

        mActivityCaller.updatePatientsData(mSearchId, patientsList);

    } catch (JSONException e) {
        mLogger.d(e.toString());
    }
}