Example usage for org.json.simple JSONArray iterator

List of usage examples for org.json.simple JSONArray iterator

Introduction

In this page you can find the example usage for org.json.simple JSONArray iterator.

Prototype

public Iterator<E> iterator() 

Source Link

Document

Returns an iterator over the elements in this list in proper sequence.

Usage

From source file:org.esa.s3tbx.olci.radiometry.rayleigh.RayleighAux.java

static ArrayList<double[][][]> parseJSON3DimArray(JSONObject parse, String ray_coeff_matrix) {
    JSONArray theta = (JSONArray) parse.get(ray_coeff_matrix);
    Iterator<JSONArray> iterator1 = theta.iterator();

    double[][][] rayCooffA = new double[3][12][12];
    double[][][] rayCooffB = new double[3][12][12];
    double[][][] rayCooffC = new double[3][12][12];
    double[][][] rayCooffD = new double[3][12][12];

    int k = 0;//ww w.  ja va2 s . c  om
    while (iterator1.hasNext()) { //3
        JSONArray next = iterator1.next();
        Iterator<JSONArray> iterator2 = next.iterator();
        int i1 = 0;
        while (iterator2.hasNext()) {//12
            JSONArray iterator3 = iterator2.next();
            Iterator<JSONArray> iterator4 = iterator3.iterator();
            for (int j = 0; j < 12; j++) {//12
                JSONArray mainValue = iterator4.next();
                List<Double> collectedValues = (List<Double>) mainValue.stream().collect(Collectors.toList());
                rayCooffA[k][i1][j] = collectedValues.get(0);
                rayCooffB[k][i1][j] = collectedValues.get(1);
                rayCooffC[k][i1][j] = collectedValues.get(2);
                rayCooffD[k][i1][j] = collectedValues.get(3);
            }
            i1++;
        }
        k++;
    }
    ArrayList<double[][][]> rayCoefficient = new ArrayList();
    rayCoefficient.add(rayCooffA);
    rayCoefficient.add(rayCooffB);
    rayCoefficient.add(rayCooffC);
    rayCoefficient.add(rayCooffD);
    return rayCoefficient;

}

From source file:org.filteredpush.qc.sciname.services.GBIFService.java

public static List<NameUsage> parseAllNameUsagesFromJSON(String json) {
    boolean gotAll = true;
    ArrayList<NameUsage> result = new ArrayList<NameUsage>();
    JSONParser parser = new JSONParser();

    try {//from w  ww . j a v a 2s  .c om
        JSONArray array = new JSONArray();
        try {
            JSONObject o = (JSONObject) parser.parse(json);
            array = (JSONArray) o.get("results");
            //System.out.println(o.get("offset"));
            //System.out.println(o.get("limit"));
            //System.out.println(o.get("endOfRecords"));
            //System.out.println(o.get("count"));
            if (o.get("endOfRecords").equals("false")) {
                gotAll = false;
            }
        } catch (ClassCastException e) {
            array = (JSONArray) parser.parse(json);
        }

        Iterator i = array.iterator();
        while (i.hasNext()) {
            JSONObject obj = (JSONObject) i.next();
            NameUsage name = new NameUsage(obj);
            result.add(name);
        }

    } catch (ParseException e) {
        logger.error(e.getMessage());
    }
    // TODO: Report not getting all records.
    if (!gotAll) {
        logger.error("Incomplete Harvest");
        System.out.println("Incomplete Harvest");
    }

    return result;
}

From source file:org.filteredpush.qc.sciname.services.GBIFService.java

public static NameUsage parseNameUsageFromJSON(String targetName, String json) {
    JSONParser parser = new JSONParser();

    try {//w w w.  j a va 2  s. c  om
        JSONArray array = new JSONArray();
        try {
            JSONObject o = (JSONObject) parser.parse(json);
            if (o.get("results") != null) {
                array = (JSONArray) o.get("results");
            } else {
                // array = (JSONArray)parser.parse(json);
            }
        } catch (ClassCastException e) {
            logger.debug(e.getMessage(), e);
            array = (JSONArray) parser.parse(json);
        }

        Iterator<JSONObject> i = array.iterator();
        while (i.hasNext()) {
            JSONObject obj = i.next();
            // System.out.println(obj.toJSONString());
            NameUsage name = new NameUsage(obj);
            if (name.getCanonicalName().equals(targetName)) {
                return name;
            }
        }

    } catch (ParseException e) {
        logger.debug(e.getMessage(), e);
    }
    return null;
}

From source file:org.geotools.data.sfs.SFSDataStore.java

/**
 * This method processes the JSON from the server and extracts layer names
 * and populates typeNames//  w w  w.j  a  v  a  2 s  .c o m
 * @param capabilitiesJSON
 * 
 */
final void processCapabilities(String capabilitiesJSON) throws IOException {
    JSONParser parser = new JSONParser();

    try {
        Object obj = parser.parse(capabilitiesJSON);
        JSONArray array = (JSONArray) obj;

        Iterator itr = array.iterator();
        while (itr.hasNext()) {
            Map tmpMap = (HashMap) itr.next();
            String strName = ((String) tmpMap.get("name")).trim();
            Name name = new NameImpl(namespaceURI, strName);

            boolean xyOrder = (!tmpMap.containsKey("axisorder")) ? true
                    : (tmpMap.get("axisorder").equals("xy"));

            String strCRS = null;
            CoordinateReferenceSystem crs = null;
            if (tmpMap.containsKey("crs")) {
                strCRS = ((String) tmpMap.get("crs")).trim();
                crs = SFSDataStoreUtil.decodeXY(strCRS);
            }

            Envelope envelope = null;
            if (tmpMap.containsKey("bbox")) {
                JSONArray boundingArray = (JSONArray) tmpMap.get("bbox");
                if (!xyOrder) {
                    SFSDataStoreUtil.flipYXInsideTheBoundingBox(boundingArray);
                }
                envelope = new Envelope(((Number) boundingArray.get(0)).doubleValue(),
                        ((Number) boundingArray.get(2)).doubleValue(),
                        ((Number) boundingArray.get(1)).doubleValue(),
                        ((Number) boundingArray.get(3)).doubleValue());
            }

            SFSLayer layer = new SFSLayer(name, xyOrder, strCRS, crs, envelope);
            layers.put(name, layer);
        }
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "Exception occurred while parsing the capabilities", e);
        throw (IOException) new IOException().initCause(e);
    }
}

From source file:org.imsglobal.lti2.LTI2Util.java

public static boolean mergeLTI2Parameters(Properties custom, String customstr) {
    if (customstr == null || customstr.length() < 1)
        return true;
    JSONArray json = null;
    try {//from w  ww  .jav a  2s .  c  o  m
        json = (JSONArray) JSONValue.parse(customstr.trim());
    } catch (Exception e) {
        M_log.warning("mergeLTI2Parameters could not parse\n" + customstr);
        M_log.warning(e.getLocalizedMessage());
        return false;
    }
    Iterator<?> parameters = json.iterator();
    while (parameters.hasNext()) {
        Object o = parameters.next();
        JSONObject parameter = null;
        try {
            parameter = (JSONObject) o;
        } catch (Exception e) {
            M_log.warning("mergeLTI2Parameters did not find list of objects\n" + customstr);
            M_log.warning(e.getLocalizedMessage());
            return false;
        }

        String name = (String) parameter.get("name");

        if (name == null)
            continue;
        if (custom.containsKey(name))
            continue;
        String fixed = (String) parameter.get("fixed");
        String variable = (String) parameter.get("variable");
        if (variable != null) {
            setProperty(custom, name, variable);
            continue;
        }
        if (fixed != null) {
            setProperty(custom, name, fixed);
        }
    }
    return true;
}

From source file:org.oneandone.qxwebdriver.ui.table.Table.java

public List<HashMap> getSelectedRanges() {
    String json = (String) jsRunner.runScript("getTableSelectedRanges", contentElement);
    JSONParser parser = new JSONParser();
    List<HashMap> ranges = null;

    Object obj;/*from w w w . ja  v  a2s.c  om*/
    try {
        obj = parser.parse(json);
        JSONArray array = (JSONArray) obj;
        ranges = new ArrayList<HashMap>();

        Iterator<JSONObject> itr = array.iterator();
        while (itr.hasNext()) {
            JSONObject rangeMap = itr.next();
            HashMap<String, Long> range = new HashMap<String, Long>();
            range.put("minIndex", (Long) rangeMap.get("minIndex"));
            range.put("maxIndex", (Long) rangeMap.get("maxIndex"));
            ranges.add(range);
        }

    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return ranges;
}

From source file:org.opencastproject.adminui.endpoint.TasksEndpoint.java

@POST
@Path("/new")
@RestQuery(name = "createNewTask", description = "Creates a new task by the given metadata as JSON", returnDescription = "The task identifiers", restParameters = {
        @RestParameter(name = "metadata", isRequired = true, description = "The metadata as JSON", type = RestParameter.Type.TEXT) }, reponses = {
                @RestResponse(responseCode = HttpServletResponse.SC_CREATED, description = "Task sucessfully added"),
                @RestResponse(responseCode = SC_NOT_FOUND, description = "If the workflow definition is not found"),
                @RestResponse(responseCode = SC_BAD_REQUEST, description = "If the metadata is not set or couldn't be parsed") })
public Response createNewTask(@FormParam("metadata") String metadata) throws NotFoundException {
    if (StringUtils.isBlank(metadata)) {
        logger.warn("No metadata set");
        return RestUtil.R.badRequest("No metadata set");
    }/*from w  w  w. ja  v  a 2  s .c o  m*/

    JSONObject metadataJson;
    try {
        metadataJson = (JSONObject) parser.parse(metadata);
    } catch (Exception e) {
        logger.warn("Unable to parse metadata {}", metadata);
        return RestUtil.R.badRequest("Unable to parse metadata");
    }

    String workflowId = (String) metadataJson.get("workflow");
    if (StringUtils.isBlank(workflowId))
        return RestUtil.R.badRequest("No workflow set");

    JSONArray eventIds = (JSONArray) metadataJson.get("eventIds");
    if (eventIds == null)
        return RestUtil.R.badRequest("No eventIds set");

    JSONObject configuration = (JSONObject) metadataJson.get("configuration");
    Stream<Entry<String, String>> options = Stream.empty();
    if (configuration != null) {
        try {
            options = options.append(JSONUtils
                    .toMap(new org.codehaus.jettison.json.JSONObject(configuration.toJSONString())).entrySet());
        } catch (JSONException e) {
            logger.warn("Unable to parse workflow options to map: {}", ExceptionUtils.getStackTrace(e));
            return RestUtil.R.badRequest("Unable to parse workflow options to map");
        }
    }

    Map<String, String> optionsMap = options.filter(new Fn<Map.Entry<String, String>, Boolean>() {
        @Override
        public Boolean ap(Entry<String, String> a) {
            if ("eventIds".equalsIgnoreCase(a.getKey()))
                return false;
            return true;
        }
    }).foldl(new HashMap<String, String>(), TasksEndpoint.<String, String>mapFold());

    WorkflowDefinition wfd;
    try {
        wfd = workflowService.getWorkflowDefinitionById(workflowId);
    } catch (WorkflowDatabaseException e) {
        logger.error("Unable to get workflow definition {}: {}", workflowId, ExceptionUtils.getStackTrace(e));
        return RestUtil.R.serverError();
    }

    List<WorkflowInstance> instances = archive.applyWorkflow(workflow(wfd, optionsMap),
            httpMediaPackageElementProvider.getUriRewriter(), IteratorUtils.toList(eventIds.iterator()));
    return Response.status(Status.CREATED)
            .entity(StringUtils.join(Stream.$(instances).map(getWorkflowIds).toList(), ",")).build();
}

From source file:org.opencastproject.inspection.ffmpeg.FFmpegAnalyzer.java

@Override
public MediaContainerMetadata analyze(File media) throws MediaAnalyzerException {

    if (binary == null)
        throw new IllegalStateException("Binary is not set");

    String[] command = new String[] { binary, "-show_format", "-show_streams", "-of", "json",
            media.getAbsolutePath().replaceAll(" ", "\\ ") };
    String commandline = StringUtils.join(command, " ");

    /* Execute ffprobe and obtain the result */
    logger.debug("Running {}", commandline);

    MediaContainerMetadata metadata = new MediaContainerMetadata();

    ProcessBuilder pbuilder = new ProcessBuilder(command);

    JSONParser parser = new JSONParser();

    try {//  w w  w .  jav a2s.co  m
        Process process = pbuilder.start();
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

        JSONObject jsonObject = (JSONObject) parser.parse(reader);
        Object obj;
        Double duration;

        /* Get format specific stuff */
        JSONObject jsonFormat = (JSONObject) jsonObject.get("format");

        /* File Name */
        obj = jsonFormat.get("filename");
        if (obj != null) {
            metadata.setFileName((String) obj);
        }

        /* Format */
        obj = jsonFormat.get("format_long_name");
        if (obj != null) {
            metadata.setFormat((String) obj);
        }

        /* Mediainfo does not return a duration if there is no stream but FFprobe
         * will return 0. For compatibility reasons, check if there are any
         * streams before reading the duration: */
        obj = jsonFormat.get("nb_streams");
        if (obj != null && (Long) obj > 0) {
            obj = jsonFormat.get("duration");
            if (obj != null) {
                duration = new Double((String) obj) * 1000;
                metadata.setDuration(duration.longValue());
            }
        }

        /* File Size */
        obj = jsonFormat.get("size");
        if (obj != null) {
            metadata.setSize(new Long((String) obj));
        }

        /* Bitrate */
        obj = jsonFormat.get("bit_rate");
        if (obj != null) {
            metadata.setBitRate(new Float((String) obj));
        }

        /* Loop through streams */
        /* FFprobe will return an empty stream array if there are no streams.
         * Thus we do not need to check. */
        JSONArray streams = (JSONArray) jsonObject.get("streams");
        Iterator<JSONObject> iterator = streams.iterator();
        while (iterator.hasNext()) {
            JSONObject stream = iterator.next();
            /* Check type of string */
            String codecType = (String) stream.get("codec_type");

            /* Handle audio streams ----------------------------- */

            if ("audio".equals(codecType)) {
                /* Extract audio stream metadata */
                AudioStreamMetadata aMetadata = new AudioStreamMetadata();

                /* Codec */
                obj = stream.get("codec_long_name");
                if (obj != null) {
                    aMetadata.setFormat((String) obj);
                }

                /* Duration */
                obj = stream.get("duration");
                if (obj != null) {
                    duration = new Double((String) obj) * 1000;
                    aMetadata.setDuration(duration.longValue());
                } else {
                    /* If no duration for this stream is specified assume the duration
                     * of the file for this as well. */
                    aMetadata.setDuration(metadata.getDuration());
                }

                /* Bitrate */
                obj = stream.get("bit_rate");
                if (obj != null) {
                    aMetadata.setBitRate(new Float((String) obj));
                }

                /* Channels */
                obj = stream.get("channels");
                if (obj != null) {
                    aMetadata.setChannels(((Long) obj).intValue());
                }

                /* Sample Rate */
                obj = stream.get("sample_rate");
                if (obj != null) {
                    aMetadata.setSamplingRate(Integer.parseInt((String) obj));
                }

                /* Add video stream metadata to overall metadata */
                metadata.getAudioStreamMetadata().add(aMetadata);

                /* Handle video streams ----------------------------- */

            } else if ("video".equals(codecType)) {
                /* Extract video stream metadata */
                VideoStreamMetadata vMetadata = new VideoStreamMetadata();

                /* Codec */
                obj = stream.get("codec_long_name");
                if (obj != null) {
                    vMetadata.setFormat((String) obj);
                }

                /* Duration */
                obj = stream.get("duration");
                if (obj != null) {
                    duration = new Double((String) obj) * 1000;
                    vMetadata.setDuration(duration.longValue());
                } else {
                    /* If no duration for this stream is specified assume the duration
                     * of the file for this as well. */
                    vMetadata.setDuration(metadata.getDuration());
                }

                /* Bitrate */
                obj = stream.get("bit_rate");
                if (obj != null) {
                    vMetadata.setBitRate(new Float((String) obj));
                }

                /* Width */
                obj = stream.get("width");
                if (obj != null) {
                    vMetadata.setFrameWidth(((Long) obj).intValue());
                }

                /* Height */
                obj = stream.get("height");
                if (obj != null) {
                    vMetadata.setFrameHeight(((Long) obj).intValue());
                }

                /* Profile */
                obj = stream.get("profile");
                if (obj != null) {
                    vMetadata.setFormatProfile((String) obj);
                }

                /* Aspect Ratio */
                obj = stream.get("sample_aspect_ratio");
                if (obj != null) {
                    vMetadata.setPixelAspectRatio(parseFloat((String) obj));
                }

                /* Frame Rate */
                obj = stream.get("avg_frame_rate");
                if (obj != null) {
                    vMetadata.setFrameRate(parseFloat((String) obj));
                }

                /* Add video stream metadata to overall metadata */
                metadata.getVideoStreamMetadata().add(vMetadata);
            }
        }

    } catch (IOException e) {
        logger.error("Error executing ffprobe: {}", e.getMessage());
    } catch (ParseException e) {
        logger.error("Error parsing ffprobe output: {}", e.getMessage());
    }

    return metadata;
}

From source file:org.opendaylight.atrium.routingservice.config.ConfigReaderTest.java

/**
 * Tests whether the bgp speakers are read properly from the config file
 *//*from w  ww.j  a  va2  s  . c o m*/
@Test
public void testGetBgpSpeakers() throws FileNotFoundException, IOException, ParseException {
    testInitialize();

    BgpSpeakers actualBgpSpeakers = null;
    BgpSpeakers expectedBgpSpeakers = null;

    BgpSpeakerBuilder bgpSpeakerBuilder = new BgpSpeakerBuilder();
    BgpSpeakersBuilder bgpSpeakersBuilder = new BgpSpeakersBuilder();
    InterfaceAddressesBuilder intfAddressBuilder = new InterfaceAddressesBuilder();
    List<InterfaceAddresses> intfAddressesList = new ArrayList<InterfaceAddresses>();
    List<BgpSpeaker> bgpSpeakerList = new ArrayList<BgpSpeaker>();

    JSONArray bgpSpeakers = (JSONArray) jsonObject.get("bgpSpeakers");
    Iterator<JSONObject> bgpIterator = bgpSpeakers.iterator();

    while (bgpIterator.hasNext()) {
        JSONObject bgp = (JSONObject) bgpIterator.next();
        bgpSpeakerBuilder.setSpeakerName((String) bgp.get("name"));
        String attachmentDpid = AtriumUtils.hexDpidStringToOpenFlowDpid((String) bgp.get("attachmentDpid"));
        bgpSpeakerBuilder.setAttachmentDpId(NodeId.getDefaultInstance(attachmentDpid));
        String attachmentPort = (String) bgp.get("attachmentPort");
        bgpSpeakerBuilder.setAttachmentPort(Long.valueOf(attachmentPort));
        String macAddress = (String) bgp.get("macAddress");
        bgpSpeakerBuilder.setMacAddress(MacAddress.getDefaultInstance(macAddress));
        JSONArray intfList = (JSONArray) bgp.get("interfaceAddresses");
        Iterator<JSONObject> intfIterator = intfList.iterator();

        while (intfIterator.hasNext()) {
            JSONObject intfAddress = (JSONObject) intfIterator.next();
            String ipAddress = (String) intfAddress.get("ipAddress");
            intfAddressBuilder.setIpAddress(new IpAddress(Ipv4Address.getDefaultInstance(ipAddress)));
            String interfaceDpid = AtriumUtils
                    .hexDpidStringToOpenFlowDpid((String) intfAddress.get("interfaceDpid"));
            String interfacePort = (String) intfAddress.get("interfacePort");
            NodeConnectorId ncId = NodeConnectorId.getDefaultInstance(interfaceDpid + ":" + interfacePort);
            intfAddressBuilder.setOfPortId(ncId);
            intfAddressBuilder.setKey(new InterfaceAddressesKey(ncId));
            intfAddressesList.add(intfAddressBuilder.build());
        }
        bgpSpeakerBuilder.setInterfaceAddresses(intfAddressesList);
        bgpSpeakerList.add(bgpSpeakerBuilder.build());
    }

    bgpSpeakersBuilder.setBgpSpeaker(bgpSpeakerList);

    expectedBgpSpeakers = bgpSpeakersBuilder.build();
    actualBgpSpeakers = ConfigReader.getBgpSpeakers();

    assertEquals(expectedBgpSpeakers, actualBgpSpeakers);
}

From source file:org.opendaylight.atrium.routingservice.config.ConfigReaderTest.java

/**
 * Tests whether the bgp peers are read properly from the config file
 *///from ww w.j  ava  2  s.c  o m
@Test
public void testGetBgpPeers() throws FileNotFoundException, IOException, ParseException {
    testInitialize();

    BgpPeers actualBgpPeers = null;
    BgpPeers expectedBgpPeers = null;

    List<BgpPeer> bgpPeerList = new ArrayList<BgpPeer>();
    BgpPeerBuilder bgpPeerBuilder = new BgpPeerBuilder();
    BgpPeersBuilder bgpPeersBuilder = new BgpPeersBuilder();

    JSONArray bgpPeers = (JSONArray) jsonObject.get("bgpPeers");
    Iterator<JSONObject> bgpIterator = bgpPeers.iterator();

    while (bgpIterator.hasNext()) {
        JSONObject bgpPeer = (JSONObject) bgpIterator.next();
        String dpId = AtriumUtils.hexDpidStringToOpenFlowDpid((String) bgpPeer.get("attachmentDpid"));
        bgpPeerBuilder.setPeerDpId(NodeId.getDefaultInstance(dpId));
        String attachmentPort = (String) bgpPeer.get("attachmentPort");
        bgpPeerBuilder.setPeerPort(Long.valueOf(attachmentPort));
        String ipAddress = (String) bgpPeer.get("ipAddress");
        IpAddress ip = new IpAddress(Ipv4Address.getDefaultInstance(ipAddress));
        bgpPeerBuilder.setPeerAddr(ip);
        bgpPeerBuilder.setKey(new BgpPeerKey(ip));
        bgpPeerList.add(bgpPeerBuilder.build());
    }

    bgpPeersBuilder.setBgpPeer(bgpPeerList);
    expectedBgpPeers = bgpPeersBuilder.build();

    actualBgpPeers = ConfigReader.getBgpPeer();

    assertEquals(expectedBgpPeers, actualBgpPeers);
}