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:com.gdf.ejb.singleton.PopulateDBBean.java

/**
 * Return the region who match with the zip code 
 * @param code zip cpde// ww  w. ja  va2  s.  com
 * @return the region
 */
@Override
public String getRegion(String code) {

    service = client.resource(UriBuilder.fromUri("http://api.zippopotam.us/fr/").build());

    String response;

    try {
        response = service.path(code).get(String.class);
    } catch (UniformInterfaceException ue) {
        return null; // if the postal code is null, it doesn't exist dans erro will be display to the customer
    }

    String region = "";
    JSONParser parser = new JSONParser();
    Object obj;

    try {

        obj = parser.parse(response);
        JSONObject jsonObject = (JSONObject) obj;
        JSONArray list = (JSONArray) jsonObject.get("places");
        JSONObject regionJSON = (JSONObject) list.get(0);
        region = (String) regionJSON.get("state");

    } catch (ParseException ex) {
        return null;
    }

    return region;

}

From source file:net.emotivecloud.scheduler.drp4ost.DRP4OST.java

/**
 * Returns the private IPs associated to the server ID
 *
 * @param vmID//from   w  w w  .ja  va2  s .  c  o  m
 * @return
 */
public String[] getIPs(String serverID) {

    ArrayList<String> ips = new ArrayList<String>();
    String serverDetails = null;
    String status = "UNKNOWN";

    // Until VM has ACTIVE status, no IP is assigned
    while (!status.equals("ACTIVE")) {
        serverDetails = oStackClient.getServer(serverID);
        status = oStackClient.getVMStatus(serverID);
        System.out.println("DRP4OST>DRP4OST.getIPs(), VM has status=" + status);
        try {
            Thread.sleep(5000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // Parsing the JSON response to get all the images
    JSONObject allFlavors = (JSONObject) JSONValue.parse(serverDetails);
    JSONObject jsonServer = (JSONObject) allFlavors.get("server");
    JSONObject jsonAddresses = (JSONObject) jsonServer.get("addresses");
    JSONArray jsonPrivate = (JSONArray) jsonAddresses.get("private");

    for (int i = 0; i < jsonPrivate.size(); ++i) {
        JSONObject addr = (JSONObject) jsonPrivate.get(i);
        String tmpAddr = addr.get("addr").toString();
        ips.add(tmpAddr);
        System.out.println("DRP4OST>DRP4OST.getIPs(), VM has ip=" + tmpAddr);
    }

    String[] ipsArray = ips.toArray(new String[ips.size()]);
    return ipsArray;

}

From source file:com.google.android.gcm.server.SenderTest.java

private void assertRequestJsonBody(String... expectedRegIds) throws Exception {
    ArgumentCaptor<String> capturedBody = ArgumentCaptor.forClass(String.class);
    verify(sender).post(eq(Constants.GCM_SEND_ENDPOINT), eq("application/json"), capturedBody.capture());
    // parse body
    String body = capturedBody.getValue();
    JSONObject json = (JSONObject) jsonParser.parse(body);
    assertEquals(ttl, ((Long) json.get("time_to_live")).intValue());
    assertEquals(collapseKey, json.get("collapse_key"));
    assertEquals(delayWhileIdle, json.get("delay_while_idle"));
    @SuppressWarnings("unchecked")
    Map<String, Object> payload = (Map<String, Object>) json.get("data");
    assertNotNull("no payload", payload);
    assertEquals("wrong payload size", 3, payload.size());
    assertEquals("v1", payload.get("k1"));
    assertEquals("v2", payload.get("k2"));
    assertEquals("v3", payload.get("k3"));
    JSONArray actualRegIds = (JSONArray) json.get("registration_ids");
    assertEquals("Wrong number of regIds", expectedRegIds.length, actualRegIds.size());
    for (int i = 0; i < expectedRegIds.length; i++) {
        String expectedRegId = expectedRegIds[i];
        String actualRegId = (String) actualRegIds.get(i);
        assertEquals("invalid regId at index " + i, expectedRegId, actualRegId);
    }/* w  ww.j a  v  a2  s . c  o m*/
}

From source file:de.fhg.fokus.odp.middleware.ckan.CKANGatewayUtil.java

/**
 * The function returns all meta data sets filtered according to the
 * maintainer email. The function returns a HashMap with key=metadataSetId
 * and value=HashMap(with Key = MetaDataEntryKey and value =
 * MetaDataEntryValue)./*from ww  w  .jav  a  2s.  co  m*/
 * 
 * @param maintainerEmail
 *            the maintainer email.
 * @param fileFormat
 *            the file format to filter for.
 * 
 * @return the the hash map as described in the general comments of the
 *         method or null if anything has gone wrong.
 */
@SuppressWarnings("rawtypes")
public static HashMap<String, HashMap> viewDataSets(String maintainerEmail, String fileFormat) {

    // check the input parameters
    if (maintainerEmail == null || maintainerEmail.equals("") || fileFormat == null
            || fileFormat.trim().equals("")) {
        return null;
    }

    // prepare the REST API call
    String RESTcall = API_URI + "?maintainer_email=";
    maintainerEmail = maintainerEmail.replaceAll("@", "%40;");
    RESTcall += maintainerEmail;

    // the variable to return
    HashMap<String, HashMap> toreturn = new HashMap<String, HashMap>();

    try {
        // run the REST call to obtain all packages
        String packageListString = connectorInstance.restCall(RESTcall);
        if (packageListString == null) {
            log.log(Level.SEVERE, "Failed to realize api call \"" + url + RESTcall + "\" !!!");
            return null;
        }

        // parse the JSON string and obtain an array of JSON objects
        Object obj = JSONValue.parse(packageListString);
        Map m = (Map) obj;
        JSONArray array = (JSONArray) (m.get("results"));
        if (array == null) {
            return null;
        }

        // move over the JSON array
        for (int i = 0; i < array.size(); i++) {

            // get details for each single package
            String RESTcallPackage = API_URI + "/" + array.get(i);
            String packageStr = connectorInstance.restCall(RESTcallPackage);

            if (packageStr == null) {
                log.log(Level.SEVERE, "Failed to obtain details for package \"" + packageStr + "\"");
                continue;
            }

            // parse the string for the package
            Object packageObj = JSONValue.parse(packageStr);
            HashMap helpMap = (HashMap) packageObj;

            // check whether at least one of the given resources matches the
            // required file format
            boolean matchesFormat = false;
            JSONArray arr = (JSONArray) (helpMap.get("resources"));
            for (int j = 0; j < arr.size(); j++) {
                HashMap rMap = (HashMap) arr.get(j);
                String format = (String) rMap.get("format");
                if (format == null) {
                    format = "";
                }
                format = format.trim();
                if (format.equals(fileFormat)) {
                    matchesFormat = true;
                }
            }

            if (matchesFormat == false) {
                continue;
            }

            // if all filters passed --> add to the hashmap to return
            toreturn.put((String) array.get(i), helpMap);
        }
    } catch (MalformedURLException e) {
        log.log(Level.SEVERE, "Failed to realize api call \"" + url + RESTcall + "\" !!!");
        return null;
    } catch (IOException e) {
        return null;
    }

    return toreturn;
}

From source file:de.fhg.fokus.odp.middleware.unittest.xTestCKANGateway.java

/**
 * Test the getDataSetUpdates method./*from   w w  w. java2 s  . c  om*/
 */
@Test
public void testGetTagsData() {
    JSONArray arr = ckanGW.getTagsData();
    log.fine("########## GET TAGS #########");
    log.fine("arr: " + arr);
    boolean test = false, unittest = false;
    boolean soccer = false, basketball = false;

    for (int i = 0; i < arr.size(); i++) {

        String str = (String) arr.get(i);

        if (str.equals("test")) {
            test = true;
        }
        if (str.equals("unittest")) {
            unittest = true;
        }
    }

    assertEquals(true, test);
    assertEquals(true, unittest);

    assertEquals(false, soccer);
    assertEquals(false, basketball);
}

From source file:com.kdao.cmpe235_project.UploadActivity.java

/**
 * Private function to populate comments
 * @method populateTrees//www .  j  a v a2  s  . c  o m
 */
private void populateTrees(JSONArray arrayObj) {
    //System.out.println(arrayObj.size());
    for (int i = 0; i < arrayObj.size(); i++) {
        try {
            JSONObject object = (JSONObject) arrayObj.get(i);
            Location location = new Location(Double.parseDouble(object.get("longitude").toString()),
                    Double.parseDouble(object.get("latitude").toString()), object.get("address").toString(),
                    object.get("title").toString());
            Sensor sensor = new Sensor();
            trees.add(new Tree(object.get("id").toString(), object.get("description").toString(), "",
                    object.get("youtubeId").toString(), location, sensor));
        } catch (Exception e) {
            System.out.println(e);
        }
    }
    if (arrayObj.size() > 0) { //get treeId on initial load
        treeId = trees.get(0).getId();
        APIurl = "/tree/" + treeId + "/photo";
    }
}

From source file:Display.java

@SuppressWarnings("unchecked")
Display() {/*from  w  w  w.jav  a  2s  . c o m*/
    super(Reference.NAME);
    cardLayout = new CardLayout();
    panel.setLayout(cardLayout);
    final int java7Update = Utils.Validators.java7Update.check();
    final int java8Update = Utils.Validators.java8Update.check();
    try {
        URL host = new URL(Reference.PROTOCOL, Reference.SOURCE_HOST, Reference.PORT, Reference.JSON_ARRAY);
        JSONParser parser = new JSONParser();
        Object json = parser.parse(new URLReader(host));
        final JSONArray array = (JSONArray) json;
        JSONObject nameObject1 = (JSONObject) array.get(0);
        XPackInstaller.selected_url = nameObject1.get("url").toString();
        XPackInstaller.javaVersion = Integer.parseInt(nameObject1.get("version").toString());
        XPackInstaller.profile = nameObject1.get("profile").toString();
        XPackInstaller.canAcceptOptional = Boolean
                .parseBoolean(nameObject1.get("canAcceptOptional").toString());
        if (!XPackInstaller.canAcceptOptional) {
            checkOptifine.setEnabled(false);
            checkOptifine.setSelected(false);
            zainstalujMoCreaturesCheckBox.setEnabled(false);
            zainstalujMoCreaturesCheckBox.setSelected(false);
            optionalText.setEnabled(false);
        } else {
            checkOptifine.setEnabled(true);
            zainstalujMoCreaturesCheckBox.setEnabled(true);
            optionalText.setEnabled(true);
        }
        for (Object anArray : array) {
            comboBox1.addItem(new JSONObject((JSONObject) anArray).get("name"));
        }
        comboBox1.addActionListener(e -> {
            int i = 0;
            while (true) {
                JSONObject nameObject = (JSONObject) array.get(i);
                String name1 = nameObject.get("name").toString();
                if (name1 == comboBox1.getSelectedItem()) {
                    XPackInstaller.canAcceptOptional = Boolean
                            .parseBoolean(nameObject.get("canAcceptOptional").toString());
                    XPackInstaller.selected_url = nameObject.get("url").toString();
                    XPackInstaller.javaVersion = Integer.parseInt(nameObject.get("version").toString());
                    XPackInstaller.profile = nameObject.get("profile").toString();
                    if (!XPackInstaller.canAcceptOptional) {
                        checkOptifine.setEnabled(false);
                        checkOptifine.setSelected(false);
                        zainstalujMoCreaturesCheckBox.setEnabled(false);
                        zainstalujMoCreaturesCheckBox.setSelected(false);
                        optionalText.setEnabled(false);
                    } else {
                        checkOptifine.setEnabled(true);
                        zainstalujMoCreaturesCheckBox.setEnabled(true);
                        optionalText.setEnabled(true);
                    }
                    break;
                }
                i++;
            }
            int javaStatus;
            if (XPackInstaller.javaVersion == 8) {
                javaStatus = java8Update;
            } else {
                javaStatus = java7Update;
            }
            if (javaStatus == 0) {
                javaversion.setText("TAK");
                javaversion.setForeground(Reference.COLOR_DARK_GREEN);
            } else if (javaStatus == 1) {
                javaversion.setText("NIE");
                javaversion.setForeground(Reference.COLOR_DARK_ORANGE);
            } else if (javaStatus == 2) {
                if (XPackInstaller.javaVersion == 8) {
                    javaversion.setText("Nie posiadasz JRE8 w wersji 25 lub nowszej!");
                } else {
                    javaversion.setText("Nie posiadasz najnowszej wersji JRE7!");
                }
                javaversion.setForeground(Color.RED);
            }
            if (osarch.getText().equals("TAK") && Ram.getText().equals("TAK")
                    && javaarch.getText().equals("TAK")
                    && (javaversion.getText().equals("TAK") || javaversion.getText().equals("NIE"))) {
                XPackInstaller.canGoForward = true;
                button2.setText("Dalej");
            } else {
                XPackInstaller.canGoForward = false;
                button2.setText("Anuluj");
            }
        });
    } catch (FileNotFoundException | ParseException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(panel, "Brak poczenia z Internetem!", "Bd",
                JOptionPane.ERROR_MESSAGE);
        System.exit(0);
    }

    pobierzOryginalnyLauncherMCCheckBox.addActionListener(e -> {
        if (pobierzOryginalnyLauncherMCCheckBox.isSelected()) {
            PathLauncherLabel.setEnabled(true);
            textField1.setEnabled(true);
            button3.setEnabled(true);
            XPackInstaller.installLauncher = true;
            labelLauncher.setEnabled(true);
            progressBar3.setEnabled(true);
        } else {
            PathLauncherLabel.setEnabled(false);
            textField1.setEnabled(false);
            button3.setEnabled(false);
            XPackInstaller.installLauncher = false;
            labelLauncher.setEnabled(false);
            progressBar3.setEnabled(false);
        }
    });
    button3.addActionListener(e -> {
        JFileChooser chooser = new JFileChooser(System.getProperty("user.home"));
        chooser.setApproveButtonText("Wybierz");
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        chooser.setMultiSelectionEnabled(false);
        chooser.setDialogTitle("Wybierz ciek");
        int returnValue = chooser.showOpenDialog(getContentPane());
        if (returnValue == JFileChooser.APPROVE_OPTION) {
            try {
                XPackInstaller.launcher_path = chooser.getSelectedFile().getCanonicalPath();
            } catch (IOException x) {
                x.printStackTrace();
            }
            textField1.setText(XPackInstaller.launcher_path);
        }
    });
    slider1.setMaximum(Utils.Utils.humanReadableRAM() - 2);
    slider1.addChangeListener(e -> XPackInstaller.allocatedRAM = slider1.getValue());
    button1.addActionListener(e -> {
        if (pobierzOryginalnyLauncherMCCheckBox.isSelected()) {
            File launcher = new File(XPackInstaller.launcher_path + File.separator + "Minecraft.exe");
            if (textField1.getText().equals("")) {
                JOptionPane.showMessageDialog(panel, "Nie wybrae cieki instalacji Launcher'a!",
                        "Bd", JOptionPane.ERROR_MESSAGE);
            } else if (launcher.exists()) {
                JOptionPane.showMessageDialog(panel,
                        "W podanym katalogu istanieje ju plik o nazwie 'Minecraft.exe'!", "Bad",
                        JOptionPane.ERROR_MESSAGE);
            } else {
                cardLayout.next(panel);
            }
        } else {
            cardLayout.next(panel);
            if (osarch.getText().equals("NIE") && Ram.getText().equals("TAK")
                    && javaarch.getText().equals("NIE")
                    && (javaversion.getText().equals("TAK") || javaversion.getText().equals("NIE"))) {
                XPackInstaller.canGoForward = false;
                button2.setText("Anuluj");
                JOptionPane.showMessageDialog(gui,
                        "Prosimy sprawdzi\u0107 czy na komputerze nie ma zainstalowanych dw\u00f3ch \u015brodowisk Java: w wersji 32-bitowej i 64-bitowej.\nJe\u015bli zainstalowane s\u0105 obie wersje prosimy o odinstalowanie wersji 32-bitowej. To rozwi\u0105\u017ce problem.",
                        "B\u0142\u0105d konfiguracji Javy", JOptionPane.ERROR_MESSAGE);
            }
        }
    });

    if (Utils.Validators.systemArchitecture.check()) {
        osarch.setText("TAK");
        osarch.setForeground(Reference.COLOR_DARK_GREEN);
    } else {
        osarch.setText("NIE");
        osarch.setForeground(Color.RED);
    }
    if (Utils.Validators.ramAmount.check()) {
        Ram.setText("TAK");
        Ram.setForeground(Reference.COLOR_DARK_GREEN);
    } else {
        Ram.setText("NIE");
        Ram.setForeground(Color.RED);
    }
    if (Utils.Validators.javaArchitecture.check()) {
        javaarch.setText("TAK");
        javaarch.setForeground(Reference.COLOR_DARK_GREEN);
    } else {
        javaarch.setText("NIE");
        javaarch.setForeground(Color.RED);
    }
    int javaStatus;

    if (XPackInstaller.javaVersion == 8) {
        javaStatus = java8Update;
    } else {
        javaStatus = java7Update;
    }

    if (javaStatus == 0) {
        javaversion.setText("TAK");
        javaversion.setForeground(Reference.COLOR_DARK_GREEN);
    } else if (javaStatus == 1) {
        javaversion.setText("NIE");
        javaversion.setForeground(Reference.COLOR_DARK_ORANGE);
    } else if (javaStatus == 2) {
        javaversion.setText("Nie posiadasz najnowszej wersji JRE!");
        javaversion.setForeground(Color.RED);
    }
    if (osarch.getText().equals("TAK") && Ram.getText().equals("TAK") && javaarch.getText().equals("TAK")
            && (javaversion.getText().equals("TAK") || javaversion.getText().equals("NIE"))) {
        XPackInstaller.canGoForward = true;
        button2.setText("Dalej");
    } else {
        XPackInstaller.canGoForward = false;
        button2.setText("Anuluj");
    }
    button2.addActionListener(e -> {
        if (XPackInstaller.canGoForward) {
            cardLayout.next(panel);
        } else {
            System.exit(1);
        }
    });
    wsteczButton.addActionListener(e -> cardLayout.previous(panel));
    try {
        editorPane1.setPage("http://xpack.pl/licencja.html");
    } catch (IOException e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(panel, "Brak poczenia z Internetem!", "Bd",
                JOptionPane.ERROR_MESSAGE);
        System.exit(0);
    }
    licenseC.addActionListener(e -> {
        if (licenseC.isSelected()) {
            dalejButton.setEnabled(true);
        } else {
            dalejButton.setEnabled(false);
        }
    });
    try {
        File mainDir = new File(System.getenv("appdata") + File.separator + "XPackInstaller");
        if (mainDir.exists()) {
            FileUtils.deleteDirectory(mainDir);
            if (!mainDir.mkdir()) {
                JOptionPane.showMessageDialog(gui,
                        "Nie udao si utworzy katalogu, prosimy sprbowa ponownie!", "Bd",
                        JOptionPane.ERROR_MESSAGE);
                System.out.println("Nie udao si utworzy katalogu!");
                System.exit(1);
            }
        } else {
            if (!mainDir.mkdir()) {
                JOptionPane.showMessageDialog(gui,
                        "Nie udao si utworzy katalogu, prosimy sprbowa ponownie!", "Bd",
                        JOptionPane.ERROR_MESSAGE);
                System.out.println("Nie udao si utworzy katalogu!");
                System.exit(1);
            }
        }
        File optionalDir = new File(mainDir.getAbsolutePath() + File.separator + "OptionalMods");
        if (!optionalDir.mkdir()) {
            JOptionPane.showMessageDialog(gui,
                    "Nie udao si utworzy katalogu, prosimy sprbowa ponownie!", "Bd",
                    JOptionPane.ERROR_MESSAGE);
            System.out.println("Nie udao si utworzy katalogu!");
            System.exit(1);
        }
        dalejButton.addActionListener(e -> {
            cardLayout.next(panel);
            try {
                progressBar1.setValue(0);
                if (checkOptifine.isSelected() && zainstalujMoCreaturesCheckBox.isSelected()) {
                    DownloadTask task2 = new DownloadTask(gui, "mod", Reference.downloadOptifine,
                            optionalDir.getAbsolutePath());
                    task2.addPropertyChangeListener(evt -> {
                        if (evt.getPropertyName().equals("progress")) {
                            labelmodpack.setText("Pobieranie Optifine HD w toku...");
                            if (task2.isDone()) {
                                task3();
                            }
                            optifineProgress = (Integer) evt.getNewValue();
                            progressBar1.setValue(optifineProgress);
                        }
                    });
                    task2.execute();
                } else if (checkOptifine.isSelected()) {
                    DownloadTask task2 = new DownloadTask(gui, "mod", Reference.downloadOptifine,
                            optionalDir.getAbsolutePath());
                    task2.addPropertyChangeListener(evt -> {
                        if (evt.getPropertyName().equals("progress")) {
                            labelmodpack.setText("Pobieranie Optifine HD w toku...");
                            if (task2.isDone()) {
                                task();
                            }
                            optifineProgress = (Integer) evt.getNewValue();
                            progressBar1.setValue(optifineProgress);
                        }
                    });
                    task2.execute();
                } else if (zainstalujMoCreaturesCheckBox.isSelected()) {
                    task3();
                } else {
                    task();
                }
            } catch (Exception exx) {
                exx.printStackTrace();
            }
        });
    } catch (IOException e) {
        e.printStackTrace();
    }

    final JScrollBar bar = scrollPane1.getVerticalScrollBar();
    bar.addMouseListener(new MouseListener() {
        @Override
        public void mouseClicked(MouseEvent e) {
            int extent = bar.getModel().getExtent();
            int total = extent + bar.getValue();
            int max = bar.getMaximum();
            if (total == max) {
                licenseC.setEnabled(true);
            }
        }

        @Override
        public void mousePressed(MouseEvent e) {
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            int extent = bar.getModel().getExtent();
            int total = extent + bar.getValue();
            int max = bar.getMaximum();
            if (total == max) {
                licenseC.setEnabled(true);
            }
        }

        @Override
        public void mouseEntered(MouseEvent e) {
        }

        @Override
        public void mouseExited(MouseEvent e) {
        }
    });
    bar.addMouseWheelListener(e -> {
        int extent = bar.getModel().getExtent();
        int total = extent + bar.getValue();
        int max = bar.getMaximum();
        if (total == max) {
            licenseC.setEnabled(true);
        }
    });
    scrollPane1.setWheelScrollingEnabled(true);
    scrollPane1.addMouseWheelListener(e -> {
        int extent = bar.getModel().getExtent();
        int total = extent + bar.getValue();
        int max = bar.getMaximum();
        if (total == max) {
            licenseC.setEnabled(true);
        }
    });
    panel.add(panel3);
    panel.add(panel1);
    panel.add(panel2);
    panel.add(panel4);
    add(panel);
}

From source file:mml.handler.get.MMLGetMMLHandler.java

/**
 * Create the MMLtext using the invert index and the cortex and corcode
 * @param cortex the plain text version/*  ww  w  .  ja  v  a 2 s . c  om*/
 * @param ccDflt the default STIL markup for that plain text
 * @param ccPages the page-breaks or null
 * @param layer the number of the layer to build
 */
void createMML(ScratchVersion cortex, ScratchVersion ccDflt, ScratchVersion ccPages, int layer) {
    String text = cortex.getLayerString(layer);
    mml = new StringBuilder();
    String stilDflt = ccDflt.getLayerString(layer);
    String stilPages = (ccPages == null) ? null : ccPages.getLayerString(layer);
    JSONObject mDflt = (JSONObject) JSONValue.parse(stilDflt);
    if (stilPages != null) {
        JSONObject mPages = (JSONObject) JSONValue.parse(stilPages);
        mDflt = mergeCorcodes(mDflt, mPages);
    }
    JSONArray ranges = (JSONArray) mDflt.get("ranges");
    Stack<EndTag> stack = new Stack<EndTag>();
    int offset = 0;
    for (int i = 0; i < ranges.size(); i++) {
        JSONObject r = (JSONObject) ranges.get(i);
        Number len = (Number) r.get("len");
        Number relOff = (Number) r.get("reloff");
        String name = (String) r.get("name");
        if (invertIndex.containsKey(name)) {
            JSONObject def = invertIndex.get(name);
            String startTag = mmlStartTag(def, offset);
            String endTag = mmlEndTag(def, len.intValue());
            int start = offset + relOff.intValue();
            // 1. insert pending end-tags and text before current range
            int pos = offset;
            while (!stack.isEmpty() && stack.peek().offset <= start) {
                // check for NLs here if obj is of type lineformat
                int tagEnd = stack.peek().offset;
                boolean isLF = isLineFormat(stack);
                for (int j = pos; j < tagEnd; j++) {
                    char c = text.charAt(j);
                    if (c != '\n') {
                        if (globals.containsKey(c))
                            mml.append(globals.get(c));
                        else
                            mml.append(c);
                    } else if (isLF && j < tagEnd - 1)
                        startPreLine(stack);
                    else
                        mml.append(c);
                }
                pos = tagEnd;
                // newlines are not permitted before tag end
                while (mml.length() > 0 && mml.charAt(mml.length() - 1) == '\n')
                    mml.setLength(mml.length() - 1);
                mml.append(stack.pop().text);
            }
            // 2. insert intervening text
            boolean inPre = isLineFormat(stack);
            int nNLs = countTerminalNLs(mml);
            for (int j = pos; j < start; j++) {
                char c = text.charAt(j);
                if (c == '\n') {
                    if (mml.length() == 0 || nNLs == 0)
                        mml.append(c);
                    if (nNLs > 0)
                        nNLs--;
                    if (inPre)
                        startPreLine(stack);
                } else {
                    mml.append(c);
                    nNLs = 0;
                }
            }
            // 3. insert new start tag
            normaliseNewlines(startTag);
            mml.append(startTag);
            stack.push(new EndTag(start + len.intValue(), endTag, def));
        } else
            System.out.println("Ignoring tag " + name);
        offset += relOff.intValue();
    }
    //empty stack
    int pos = offset;
    while (!stack.isEmpty()) {
        int tagEnd = stack.peek().offset;
        boolean inPre = isLineFormat(stack);
        for (int j = pos; j < tagEnd; j++) {
            char c = text.charAt(j);
            mml.append(c);
            if (c == '\n' && inPre && j < tagEnd - 1)
                startPreLine(stack);
        }
        pos = tagEnd;
        // newlines are not permitted before tag end
        while (mml.length() > 0 && mml.charAt(mml.length() - 1) == '\n')
            mml.setLength(mml.length() - 1);
        mml.append(stack.pop().text);
    }
}

From source file:eu.juniper.MonitoringLib.java

private ArrayList<String> parseJsonMetrics(ArrayList<String> metricsList, String json)
        throws FileNotFoundException, IOException, ParseException {
    JSONParser parser = new JSONParser();
    Object obj = parser.parse(json);
    JSONArray jsonArray = new JSONArray();
    String metric;/*from  w ww. j a v  a2 s.c om*/

    if (obj.getClass() != jsonArray.getClass()) {
        System.out.println("Total number of metrics = 0");
        System.out.println("obj = " + obj.toString());
        return metricsList;
    }

    jsonArray = (JSONArray) obj;

    System.out.println("Total number of metrics = " + jsonArray.size());

    for (int i = 0; i < jsonArray.size(); i++) {
        metric = jsonArray.get(i).toString();
        metricsList.add(metric);
        System.out.println("metric # " + i + " = " + metric);

    }
    return metricsList;
}

From source file:com.boozallen.cognition.ingest.storm.bolt.geo.TwoFishesGeocodeBolt.java

/**
 * Submits a URL query string and builds a TwoFishesFeature for the result and all parents.
 *
 * @param query//w ww.  j  av  a2  s.  c  o  m
 * @return
 * @throws IOException
 * @throws ParseException
 */
private TwoFishesFeature[] submitQuery(String query) throws IOException, ParseException {
    URL url = new URL(query);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Accept", "application/json");
    if (conn.getResponseCode() != 200) {
        logger.error("Failed : HTTP error code : " + conn.getResponseCode() + ":" + url.toString());
        _failCount++;
        return null;
    }
    BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
    String jsonStr = br.readLine();
    br.close();
    conn.disconnect();

    JSONParser parser = new JSONParser();
    JSONObject jsonObject = (JSONObject) parser.parse(jsonStr);
    JSONArray interpretations = (JSONArray) jsonObject.get("interpretations");

    if (interpretations.size() == 0) {
        //logger.warn("Twofishes unable to resolve location " + unresolvedLocation);
        _failCount++;
        return null;
    } else {
        if (interpretations.size() > 1) {
            //lat-long searches have multiple interpretations, e.g. city, county, state, country. most specific is first, so still use it.
            logger.debug("Twofishes has more than one interpretation of " + query);
        }
        JSONObject interpretation0 = (JSONObject) interpretations.get(0);

        //ArrayList of main result and parents
        ArrayList<JSONObject> features = new ArrayList<JSONObject>();
        JSONObject feature = (JSONObject) interpretation0.get("feature");

        //save main result
        features.add(feature);

        JSONArray parents = (JSONArray) interpretation0.get("parents");
        //get parents as feature JSONObjects
        for (int i = 0; i < parents.size(); i++) {
            JSONObject parentFeature = (JSONObject) parents.get(i);
            features.add(parentFeature);
        }

        //parse features and return
        TwoFishesFeature[] results = new TwoFishesFeature[features.size()];

        for (int i = 0; i < features.size(); i++) {
            JSONObject f = features.get(i);
            TwoFishesFeature result = new TwoFishesFeature();
            result.name = (String) f.get("name");
            result.countryCode = (String) f.get(CC);
            result.woeType = (long) f.get("woeType");
            JSONObject geometry = (JSONObject) f.get("geometry");
            JSONObject center = (JSONObject) geometry.get("center");
            result.lat = String.valueOf(center.get(LAT));
            result.lng = String.valueOf(center.get(LNG));
            results[i] = result;
        }

        _successCount++;
        return results;
    }

}