Example usage for org.json.simple JSONArray get

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

Introduction

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

Prototype

public E get(int index) 

Source Link

Document

Returns the element at the specified position in this list.

Usage

From source file:at.uni_salzburg.cs.ckgroup.cpcc.mapper.algorithms.RandomTaskGenerator.java

private void mergeVehicleData(IVirtualVehicleInfo vehicleInfo)
        throws IOException, IllegalStateException, ParseException {

    String url = vehicleInfo.getEngineUrl() + "/json/vehicleDetails/" + vehicleInfo.getVehicleName();

    HttpGet httpGet = new HttpGet(url);
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = httpclient.execute(httpGet);

    HttpEntity entity = response.getEntity();
    if (entity != null) {
        JSONParser parser = new JSONParser();
        JSONObject vv = (JSONObject) parser.parse(new InputStreamReader(entity.getContent()));

        String vvId = (String) vv.get("vehicle.id");
        VirtualVehicleInfo info = vvInfo.get(vvId);
        if (info == null) {
            LOG.error("Virtual Vehicle " + vvId + " not known! URL=" + url);
            return;
        }/*from  ww  w.  ja  v  a 2  s  .  c  o  m*/

        JSONArray tasks = (JSONArray) vv.get("tasks");
        int k = 0;
        for (ActionPoint ap : info.actionPoints) {
            if (k >= tasks.size()) {
                break;
            }
            JSONObject actionPoint = (JSONObject) tasks.get(k++);
            JSONArray actions = (JSONArray) actionPoint.get("actions");

            long time = 0;
            for (int j = 0; j < actions.size(); ++j) {
                JSONObject a = (JSONObject) actions.get(j);
                Long newTime = (Long) a.get("time");
                if (newTime != null && newTime > time) {
                    time = newTime;
                }
            }

            if (time > 0) {
                ap.completedTime = time;
            }
        }
    }
}

From source file:com.orthancserver.DicomDecoder.java

private String[] SortSlicesBy3D(OrthancConnection c, JSONArray instances) throws IOException {
    ArrayList<Slice> slices = new ArrayList<Slice>();
    float normal[] = null;

    float minDistance = Float.POSITIVE_INFINITY;
    float maxDistance = Float.NEGATIVE_INFINITY;

    for (int i = 0; i < instances.size(); i++) {
        String uuid = (String) instances.get(i);
        JSONObject instance = (JSONObject) c.ReadJson("/instances/" + uuid + "/tags?simplify");
        if (!instance.containsKey("ImageOrientationPatient") || !instance.containsKey("ImagePositionPatient")) {
            return null;
        }/*from   www  .jav a2s.com*/

        if (i == 0) {
            String[] tokens = ((String) instance.get("ImageOrientationPatient")).split("\\\\");
            if (tokens.length != 6) {
                return null;
            }

            float cosines[] = new float[6];
            for (int j = 0; j < 6; j++) {
                cosines[j] = Float.parseFloat(tokens[j]);
            }

            normal = new float[] { cosines[1] * cosines[5] - cosines[2] * cosines[4],
                    cosines[2] * cosines[3] - cosines[0] * cosines[5],
                    cosines[0] * cosines[4] - cosines[1] * cosines[3] };
        }

        String[] tokens = ((String) instance.get("ImagePositionPatient")).split("\\\\");
        if (tokens.length != 3) {
            return null;
        }

        float distance = 0;
        for (int j = 0; j < 3; j++) {
            distance += normal[j] * Float.parseFloat(tokens[j]);
        }

        minDistance = Math.min(minDistance, distance);
        maxDistance = Math.max(minDistance, distance);
        slices.add(new Slice(distance, uuid));
    }

    if (maxDistance - minDistance < 0.001) {
        return null;
    }

    return SortSlices(slices);
}

From source file:com.theisleoffavalon.mcmanager.mobile.RestClient.java

/**
 * Gets all available Minecraft commands on the server
 * //w w  w.java  2s.c  o  m
 * @return A list of Minecraft commands
 * @throws IOException
 *             If an error is encountered
 */
public Map<String, MinecraftCommand> getAllMinecraftCommands() throws IOException {
    Map<String, MinecraftCommand> cmds = new HashMap<String, MinecraftCommand>();
    JSONObject request = createJSONRPCObject("getAllCommands");
    JSONObject response = sendJSONRPC(request);
    checkJSONResponse(response, request);

    // Parse result
    @SuppressWarnings("unchecked")
    Map<String, JSONObject> commands = (Map<String, JSONObject>) response.get("result");
    for (String name : commands.keySet()) {
        JSONObject paramObj = commands.get(name);
        JSONArray jparams = (JSONArray) paramObj.get("params");
        JSONArray jparamTypes = (JSONArray) paramObj.get("paramTypes");

        Map<String, ArgType> params = new HashMap<String, ArgType>();
        for (int i = 0; i < jparams.size(); i++) {
            params.put((String) jparams.get(i), ArgType.getArgTypeFromString((String) jparamTypes.get(i)));
        }
        cmds.put(name, new MinecraftCommand(name, params));
    }
    return cmds;
}

From source file:org.opencastproject.workingfilerepository.remote.WorkingFileRepositoryRemoteImpl.java

/**
 * {@inheritDoc}/* w  ww .  j a  v  a  2 s  . co  m*/
 * 
 * @see org.opencastproject.workingfilerepository.api.WorkingFileRepository#getCollectionContents(java.lang.String)
 */
@Override
public URI[] getCollectionContents(String collectionId) throws NotFoundException {
    String urlSuffix = UrlSupport.concat(new String[] { "list", collectionId + ".json" });
    HttpGet get = new HttpGet(urlSuffix);
    HttpResponse response = getResponse(get, SC_OK, SC_NOT_FOUND);
    try {
        if (response != null) {
            if (SC_NOT_FOUND == response.getStatusLine().getStatusCode()) {
                throw new NotFoundException();
            } else {
                String json = EntityUtils.toString(response.getEntity());
                JSONArray jsonArray = (JSONArray) JSONValue.parse(json);
                URI[] uris = new URI[jsonArray.size()];
                for (int i = 0; i < jsonArray.size(); i++) {
                    uris[i] = new URI((String) jsonArray.get(i));
                }
                return uris;
            }
        }
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException();
    } finally {
        closeConnection(response);
    }
    throw new RuntimeException("Error getting collection contents");
}

From source file:eu.juniper.MonitoringLib.java

private ArrayList<String> parseJsonByTag(ArrayList<String> elementsList, String json, String tag)
        throws FileNotFoundException, IOException, ParseException {
    //PrintWriter writer = new PrintWriter(filepath + "json2txt-" + tag + ".txt", "UTF-8");
    JSONParser parser = new JSONParser();
    Object obj = null;/*from w  w w . j  a  va2s.co  m*/
    try {
        obj = parser.parse(json);
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonArray = (JSONArray) obj;
        for (int i = 0; i < jsonArray.size(); i++) {
            jsonObject = (JSONObject) jsonArray.get(i);
            elementsList = readJson(elementsList, jsonObject, null /*writer*/, tag);
        }

    } catch (Exception e) {
        System.out.println("Invalid JSON String data: " + e.toString());
        return elementsList;
    }

    //writer.close();
    return elementsList;
}

From source file:mml.test.Editor.java

/**
 * Add a single option-group to the styles menu
 * @param select the selct element/*from  w w w  .  ja  va 2s.  c  o m*/
 * @param dObj the dialect JSON object
 * @param name the name of the format collection in dObj
 * @param label the name of the optgroup to appear in menu
 */
private void addOptGroup(Element select, JSONObject dObj, String name, String label) {
    JSONArray items = (JSONArray) dObj.get(name);
    if (items != null) {
        Element group = new Element("optgroup");
        group.addAttribute("label", label);
        for (int i = 0; i < items.size(); i++) {
            JSONObject item = (JSONObject) items.get(i);
            Element option = new Element("option");
            item.put("type", name);
            String value = item.toJSONString();
            value = escape(value);
            option.addAttribute("value", value);
            String text = (String) item.get("prop");
            //System.out.println(text);
            option.addText(text);
            group.addChild(option);
        }
        select.addChild(group);
    }
}

From source file:com.orthancserver.SelectImageDialog.java

public void Unserialize(String s) {
    if (s.length() == 0) {
        // Add default Orthanc server
        AddOrthancServer(new OrthancConnection());
    } else {/*from  w  ww. j av  a  2 s.  c  o  m*/
        String decoded = new String(DatatypeConverter.parseBase64Binary(s));
        JSONArray config = (JSONArray) JSONValue.parse(decoded);
        if (config != null) {
            for (int i = 0; i < config.size(); i++) {
                AddOrthancServer(OrthancConnection.Unserialize((JSONObject) config.get(i)));
            }
        }
    }
}

From source file:co.mcme.animations.animations.MCMEAnimation.java

public void loadConfiguration() {
    JSONParser parser = new JSONParser();
    try {/*w  w  w  .  j av  a  2s .  com*/
        Object obj = parser.parse(new FileReader(configFile));

        animationConfiguration = (JSONObject) obj;

        animationName = (String) animationConfiguration.get("name");
        schematicBaseName = animationName;

        localWorldName = (String) animationConfiguration.get("world-index");

        JSONArray JSONFrames = (JSONArray) animationConfiguration.get("frames");
        JSONArray JSONDurations = (JSONArray) animationConfiguration.get("durations");

        for (int i = 0; i < JSONFrames.size(); i++) {
            MCMEAnimationFrame frame = new MCMEAnimationFrame((String) JSONFrames.get(i),
                    (Long) JSONDurations.get(i));
            frames.add(frame);
        }

        JSONArray JSONOrigin = (JSONArray) animationConfiguration.get("origin");
        origin = new Location(MCMEAnimations.WEPlugin.getServer().getWorlds().get(0), (Long) JSONOrigin.get(0),
                (Long) JSONOrigin.get(1), (Long) JSONOrigin.get(2));

        try {
            animationDescription = (String) animationConfiguration.get("description");
        } catch (Exception ex) {
            //Failed to load description.
            //Put in a try-catch block for backward compatibility
        }

        loadTriggers();

        loadActions();

    } catch (IOException ex) {
        Logger.getLogger(OneTimeAnimation.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParseException ex) {
        Logger.getLogger(OneTimeAnimation.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.shuffle.mock.MockCoin.java

public static MockCoin fromJSON(Reader jsonObject) throws IllegalArgumentException {

    JSONObject json = null;// www .j a  v a2 s .  c  o m
    JSONArray outputs = null;
    JSONArray transactions = null;
    try {
        json = (JSONObject) JSONValue.parse(jsonObject);
        if (json == null) {
            throw new IllegalArgumentException("could not parse json object.");
        }

        outputs = (JSONArray) json.get("outputs");
        if (outputs == null) {
            throw new IllegalArgumentException("Missing field \"outputs\".");
        }

        transactions = (JSONArray) json.get("transactions");
        if (transactions == null) {
            throw new IllegalArgumentException("Missing field \"transactions\".");
        }
    } catch (ClassCastException e) {
        throw new IllegalArgumentException("could not parse json object.");
    }

    MockCoin mock = new MockCoin();

    Map<Long, Output> outList = new HashMap<>();
    for (int i = 1; i <= outputs.size(); i++) {
        JSONObject o = null;
        try {
            o = (JSONObject) outputs.get(i - 1);
        } catch (ClassCastException e) {
            throw new IllegalArgumentException("Could not read " + outputs.get(i - 1) + " as json object.");
        }

        Object address = o.get("address");
        Long amount = (Long) o.get("amount");
        if (address == null) {
            throw new IllegalArgumentException("Output missing field \"address\".");
        }
        if (amount == null) {
            throw new IllegalArgumentException("Output missing field \"amount\".");
        }

        Output bo = null;
        if (address instanceof String) {
            bo = new Output(new MockAddress((String) address), amount);
        } else if (address instanceof Long) {
            bo = new Output(new MockAddress((Long) address), amount);
        } else {
            throw new IllegalArgumentException("Could not read " + address + " as address");
        }

        outList.put((long) i, bo);
        mock.blockchain.put(bo.address, bo);
    }

    for (Object t : transactions) {

        JSONObject trans = (JSONObject) t;
        JSONArray in = (JSONArray) trans.get("inputs");
        JSONArray out = (JSONArray) trans.get("outputs");
        List<Output> tout = new LinkedList<>();
        List<Output> tin = new LinkedList<>();

        for (Object i : in) {
            Output o = outList.get(i);
            if (o == null) {
                throw new IllegalArgumentException("Missing output " + o);
            }
            tin.add(outList.get(i));
        }

        for (Object i : out) {
            Output o = outList.get(i);
            if (o == null) {
                throw new IllegalArgumentException("Missing output " + o);
            }
            tout.add(outList.get(i));
        }

        MockTransaction tr;
        Long z = null;
        Object zz = trans.get("z");
        try {

            if (zz == null) {
                tr = new MockTransaction(tin, tout, mock);
            } else {
                z = (Long) zz;
                tr = new MockTransaction(tin, tout, z.intValue(), mock, new HashMap<Output, VerificationKey>());
            }
        } catch (ClassCastException e) {
            throw new IllegalArgumentException("Could not read z value " + zz + " as long.");
        }
    }

    return mock;
}

From source file:com.orthancserver.DicomDecoder.java

public DicomDecoder(final OrthancConnection c, boolean isInstance, String uuid)
        throws IOException, InterruptedException, ExecutionException {
    ImageStack stack = null;/* w  w  w .jav a2s.  com*/
    JSONObject tags = null;
    String tagsUri, name;

    if (isInstance) {
        name = "Instance " + uuid;
        tags = (JSONObject) c.ReadJson("/instances/" + uuid + "/tags");
        stack = AddSlice(stack, c, uuid);
    } else {
        name = "Series " + uuid;

        JSONObject series = (JSONObject) c.ReadJson("/series/" + uuid);
        JSONArray instances = (JSONArray) series.get("Instances");

        try {
            tags = (JSONObject) c.ReadJson("/series/" + uuid + "/shared-tags");
        } catch (Exception e) {
            // Fallback for old versions of Orthanc, without "shared-tags"
            tags = (JSONObject) c.ReadJson("/instances/" + (String) instances.get(0) + "/tags");
        }

        final String[] slices = GetSlices(c, instances);
        final ProgressDialog progress = new ProgressDialog(slices.length);

        try {
            progress.setVisible(true);
            SwingWorker<ImageStack, Float> worker = new SwingWorker<ImageStack, Float>() {
                @Override
                protected ImageStack doInBackground() {
                    try {
                        ImageStack stack = null;

                        for (int i = 0; i < slices.length; i++) {
                            if (progress.IsCanceled()) {
                                return null;
                            }

                            progress.SetProgress(i);
                            stack = AddSlice(stack, c, slices[i]);
                        }

                        return stack;
                    } catch (IOException e) {
                        return null;
                    }
                }
            };

            worker.execute();
            stack = worker.get();
        } finally {
            progress.setVisible(false);
        }
    }

    image_ = new ImagePlus(name, stack);

    ExtractCalibration(image_, tags);
    ExtractPixelSpacing(image_, tags);
    ExtractDicomInfo(image_, tags);
}