Example usage for com.google.gson JsonParser JsonParser

List of usage examples for com.google.gson JsonParser JsonParser

Introduction

In this page you can find the example usage for com.google.gson JsonParser JsonParser.

Prototype

@Deprecated
public JsonParser() 

Source Link

Usage

From source file:ProcessRequest.java

public JSONObject parseQuery(JSONObject requestObject, OutputStream os)
        throws JSONException, SQLException, IOException {
    String query = "";
    String tableName = "";

    JSONArray selectionColumns = requestObject.getJSONArray("selection");
    query += "SELECT " + selectionColumns.getString(0);
    for (int i = 1; i < selectionColumns.length(); i++) {
        query += "," + selectionColumns.getString(i);
    }/*from w  w w  .j  a v  a 2 s  . c  o m*/
    query += " FROM ";
    tableName = requestObject.getString("table");
    query += tableName;
    if (requestObject.has("where")) {
        query += " WHERE ";
        query += requestObject.getString("where");
    }
    query += ";";

    JSONObject responseObject = new JSONObject();
    JSONArray resultJSONArray;

    //System.out.println(query);
    if (os != null) {
        os.write(new String("{\"result_set\":[").getBytes());
        parseQueryResults(executeQuery(query), tableName, os, false);
    }

    resultJSONArray = parseQueryResults(executeQuery(query), tableName);
    //System.out.println(resultSet.toString(5));
    if (requestObject.has("join")) {
        JSONArray joinArray = requestObject.getJSONArray("join");
        List<String> tableList = new LinkedList<String>();
        tableList.add(tableName);
        for (int h = 0; h < joinArray.length(); h++) {
            //find the next link table
            JSONObject joinObject = null;
            for (int j = 0; j < joinArray.length(); j++) {
                for (int k = 0; k < tableList.size(); k++) {
                    if (joinArray.getJSONObject(j).getString("table").equals(tableList.get(k))) {
                        //break;   //this table has already been joined
                    } else if (joinArray.getJSONObject(j).getString("link_table").equals(tableList.get(k))) {
                        joinObject = joinArray.getJSONObject(j);
                    }
                }
            }
            if (joinObject == null) {
                throw new JSONException("join syntax was incorrect, no valid joins were found");
            }
            for (int i = 0; i < resultJSONArray.length(); i++) {
                //we now know the table to join, now search through the results looking for the link_table and query on each
                if (joinObject.getString("link_table").equals(
                        resultJSONArray.getJSONObject(i).getJSONObject("metadata").getString("table"))) {
                    //this result contains the correct link_table.  query against it's link_column value
                    JsonObject linkObject = new JsonParser().parse(resultJSONArray.getJSONObject(i).toString())
                            .getAsJsonObject();
                    JsonPrimitive linkValue = null;
                    if (linkObject.has(joinObject.getString("link_column"))) {
                        linkValue = linkObject.getAsJsonPrimitive(joinObject.getString("link_column"));
                    } else {
                        //just skip this result and notify the log console.
                        //however, this is most likely an error and should be fixed.
                        System.out.println("link column did not contain the following column (please fix): "
                                + joinObject.get("link_column"));
                    }

                    String predicate = "1=1";
                    if (linkValue.isBoolean()) {
                        if (linkValue.getAsBoolean() == true) {
                            predicate = joinObject.getString("column") + "=1";
                        } else {
                            predicate = joinObject.getString("column") + "=0";
                        }
                    }
                    if (linkValue.isNumber()) {
                        predicate = joinObject.getString("column") + "=" + linkValue.getAsString();
                    }
                    if (linkValue.isString()) {
                        predicate = joinObject.getString("column") + "='" + linkValue.getAsString() + "'";
                    }
                    String joinQuery = "";
                    if (joinObject.has("selection")) {
                        JSONArray joinSelectionColumns = joinObject.getJSONArray("selection");
                        joinQuery += "SELECT " + joinSelectionColumns.getString(0);
                        for (int k = 1; k < joinSelectionColumns.length(); k++) {
                            joinQuery += "," + joinSelectionColumns.getString(k);
                        }
                    } else {
                        joinQuery += "SELECT *";
                    }
                    //build and execute query, adding it to the result set
                    joinQuery += " FROM " + joinObject.getString("table") + " WHERE " + predicate;
                    if (joinObject.has("where")) {
                        String whereClause = joinObject.getString("where");
                        joinQuery += " AND " + whereClause;
                    }
                    joinQuery += ";";
                    //System.out.println("join query: "+joinQuery);
                    //JSONArray parsedResult = parseQueryResults(executeQuery(joinQuery), joinObject.getString("table"));
                    //System.out.println("join parsed result: "+parsedResult.toString(5));
                    if (os != null)
                        parseQueryResults(executeQuery(query), joinObject.getString("table"), os, true);
                    else
                        concatArray(resultJSONArray,
                                parseQueryResults(executeQuery(query), joinObject.getString("table")));
                }
            }
            tableList.add(joinObject.getString("table"));
        }
    }
    if (os != null)
        os.write(new String("]}\n").getBytes());
    responseObject.put("result_set", resultJSONArray);
    //System.out.println(responseObject.toString(5));
    return responseObject;
}

From source file:PacketSnifferPlugin.java

License:Apache License

public void initializeMainPanel() {
    try {//  w  ww . j a  v a2s.c o m

        bstart = new JButton("Start");
        breset = new JButton("Reset");

        JPanel panel1 = new JPanel();
        panel1.setLayout(null);

        panel1.setMaximumSize(new Dimension(1150, 700));
        panel1.setMinimumSize(new Dimension(1150, 700));
        panel1.setPreferredSize(new Dimension(1150, 700));

        InputStream in = getClass().getResourceAsStream("Sniff0.png");
        Image im = ImageIO.read(in);
        button0 = new ImageIcon(im);
        in = getClass().getResourceAsStream("Sniff1.png");
        im = ImageIO.read(in);
        final ImageIcon button1 = new ImageIcon(im);
        in = getClass().getResourceAsStream("Stop1.png");
        im = ImageIO.read(in);
        final ImageIcon button2 = new ImageIcon(im);
        in = getClass().getResourceAsStream("Stop0.png");
        im = ImageIO.read(in);
        button3 = new ImageIcon(im);
        in = getClass().getResourceAsStream("Reset1.png");
        im = ImageIO.read(in);
        final ImageIcon button5 = new ImageIcon(im);
        in = getClass().getResourceAsStream("Save.png");
        im = ImageIO.read(in);
        ImageIcon save = new ImageIcon(im);

        breset.setBounds(515, 635, 120, 30);
        panel1.add(breset);
        breset.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                try {
                    String resp = client
                            .execute("runPlugin",
                                    new Object[] { variables.get("user"), getName(), "command=reset" })
                            .toString();
                    ((DefaultTableModel) jTable1.getModel()).setNumRows(0);
                    index = "0";
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        bstart = new JButton("Start");
        bstart.setBounds(385, 635, 120, 30);
        panel1.add(bstart);
        bstart.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (start == 1) {
                    bstart.setText("Start");
                    start = 0;
                    try {
                        String resp = client
                                .execute("runPlugin",
                                        new Object[] { variables.get("user"), getName(), "command=pause" })
                                .toString();
                        System.out.println("resp: " + resp);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                } else {
                    bstart.setText("Stop");
                    start = 1;
                    try {
                        String resp = client
                                .execute("runPlugin",
                                        new Object[] { variables.get("user"), getName(), "command=resume" })
                                .toString();
                        System.out.println("resp: " + resp);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }
        });

        jTable1 = new JTable();
        jTable1.getTableHeader().setReorderingAllowed(false);
        jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        jTable1.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent arg0) {
                if (!arg0.getValueIsAdjusting()) {
                    if (jTable1.getSelectedRow() == -1) {
                        content.setText("");
                        return;
                    }
                    String pac = null;
                    try {
                        String id = jTable1.getValueAt(jTable1.getSelectedRow(), 7).toString();
                        System.out.println("requested id: " + id);
                        pac = client.execute("runPlugin", new Object[] { variables.get("user"), getName(),
                                "command=querypkt&data=" + id }).toString();
                        JsonElement el = new JsonParser().parse(pac);
                        JsonObject jobject = el.getAsJsonObject();
                        Gson gson = new GsonBuilder().setPrettyPrinting().create();
                        String json = gson.toJson(jobject);
                        json = json.replaceAll("\"", "");
                        json = json.replaceAll("\\\\n", "\n");
                        content.setText(json);
                    } catch (Exception e) {
                        System.out.println("Server response: " + pac.toString());
                        e.printStackTrace();

                    }
                }
            }
        });

        JScrollPane pane = new JScrollPane(jTable1);
        pane.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
        pane.setBounds(25, 70, 1100, 300);

        jTable1.setModel(new DefaultTableModel(new Object[][] {}, new String[] { "Protocol", "SRC IP",
                "SRC Mac", "SRC Port", "DST IP", "DST Mac", "DST Port", "" }) {
            private static final long serialVersionUID = 1L;

            public boolean isCellEditable(int row, int col) {
                return false;
            }
        });
        TableRowSorter sorter = new TableRowSorter(jTable1.getModel());
        jTable1.setRowSorter(sorter);
        TableColumn c = jTable1.getColumnModel().getColumn(7);
        c.setMinWidth(0);
        c.setMaxWidth(0);
        c.setWidth(0);
        c.setPreferredWidth(0);
        panel1.add(pane);

        content = new JTextArea();
        content.setEditable(false);
        JScrollPane sc = new JScrollPane(content);
        sc.setBounds(25, 380, 1100, 250);
        panel1.add(sc);

        JPanel top = new JPanel();
        top.setBounds(25, 0, 1100, 35);
        panel1.add(top);

        JPanel top2 = new JPanel();
        top2.setBounds(25, 35, 1100, 30);
        panel1.add(top2);

        JLabel filter = new JLabel("View Filter:");
        panel1.add(top);
        top.add(filter);
        final JTextField search = new JTextField();
        search.setMinimumSize(new Dimension(130, 20));
        search.setPreferredSize(new Dimension(130, 20));
        search.addKeyListener(new KeyAdapter() {
            public void keyReleased(KeyEvent ev) {
                if (ev.getKeyCode() == KeyEvent.VK_ENTER) {
                    filter(search.getText());
                }
            }
        });
        top.add(search);
        JButton apply = new JButton("Apply");
        apply.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                filter(search.getText());
            }
        });
        top.add(apply);
        JButton clear = new JButton("Clear");
        clear.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                search.setText("");
                filter("");
            }
        });
        top.add(clear);

        filter = new JLabel("Start Options:");
        top.add(filter);
        final JTextField search2 = new JTextField();
        search2.setMinimumSize(new Dimension(130, 20));
        search2.setPreferredSize(new Dimension(130, 20));
        search2.addKeyListener(new KeyAdapter() {
            public void keyReleased(KeyEvent ev) {
                if (ev.getKeyCode() == KeyEvent.VK_ENTER) {
                    setRemoteFilter(search2.getText());
                }
            }
        });
        try {
            HashMap<String, String> filters = (HashMap<String, String>) client.execute("runPlugin",
                    new Object[] { variables.get("user"), getName(), "command=getfilters" });
            Iterator<Entry<String, String>> iter = filters.entrySet().iterator();
            StringBuilder sb = new StringBuilder();
            Entry<String, String> en;
            while (iter.hasNext()) {
                en = iter.next();
                sb.append(en.getKey());
                sb.append(" ");
                sb.append(en.getValue());
                sb.append(" ");
            }
            System.out.println("Filter:" + sb.toString());
            search2.setText(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        top.add(search2);
        JButton apply2 = new JButton("Apply");
        apply2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                setRemoteFilter(search2.getText());
            }
        });
        top.add(apply2);
        JButton clear2 = new JButton("Clear");
        clear2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                search2.setText("");
                setRemoteFilter("");

            }
        });
        top.add(clear2);

        pro = new JCheckBox("Protocol");
        pro.setSelected(true);
        pro.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                if (pro.isSelected()) {
                    jTable1.addColumn(columns[0]);
                    jTable1.moveColumn(jTable1.getColumnCount() - 1, 0);
                } else {
                    int index = findColumn("Protocol");
                    columns[0] = jTable1.getColumnModel().getColumn(index);
                    jTable1.removeColumn(columns[0]);
                }
            }
        });
        top2.add(pro);
        srcip = new JCheckBox("SRC IP");
        srcip.setSelected(true);
        srcip.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                if (srcip.isSelected()) {
                    int index = findColumn("Protocol");
                    if (index == -1) {
                        jTable1.addColumn(columns[1]);
                        jTable1.moveColumn(jTable1.getColumnCount() - 1, 0);
                    } else {
                        jTable1.addColumn(columns[1]);
                        jTable1.moveColumn(jTable1.getColumnCount() - 1, 1);
                    }
                } else {
                    int index = findColumn("SRC IP");
                    columns[1] = jTable1.getColumnModel().getColumn(index);
                    jTable1.removeColumn(columns[1]);
                }
            }
        });
        top2.add(srcip);
        srcmac = new JCheckBox("SRC Mac");
        srcmac.setSelected(true);
        srcmac.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                if (srcmac.isSelected()) {
                    jTable1.addColumn(columns[2]);
                    int index = findColumn("SRC IP");
                    if (index != -1) {
                        jTable1.moveColumn(jTable1.getColumnCount() - 1, index + 1);
                    } else if (findColumn("Protocol") != -1) {
                        jTable1.moveColumn(jTable1.getColumnCount() - 1, 1);
                    } else {
                        jTable1.moveColumn(jTable1.getColumnCount() - 1, 0);
                    }
                } else {
                    int index = findColumn("SRC Mac");
                    columns[2] = jTable1.getColumnModel().getColumn(index);
                    jTable1.removeColumn(columns[2]);
                }
            }
        });
        top2.add(srcmac);
        srcport = new JCheckBox("SRC Port");
        srcport.setSelected(true);
        srcport.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                if (srcport.isSelected()) {
                    jTable1.addColumn(columns[3]);
                    int index = findColumn("SRC Mac");
                    if (index != -1) {
                        jTable1.moveColumn(jTable1.getColumnCount() - 1, index + 1);
                    } else {
                        index = findColumn("SRC IP");
                        if (index != -1) {
                            jTable1.moveColumn(jTable1.getColumnCount() - 1, index + 1);
                        } else if (findColumn("Protocol") != -1) {
                            jTable1.moveColumn(jTable1.getColumnCount() - 1, 1);
                        } else {
                            jTable1.moveColumn(jTable1.getColumnCount() - 1, 0);
                        }
                    }
                } else {
                    int index = findColumn("SRC Port");
                    columns[3] = jTable1.getColumnModel().getColumn(index);
                    jTable1.removeColumn(columns[3]);
                }
            }
        });
        top2.add(srcport);
        dstip = new JCheckBox("DST IP");
        dstip.setSelected(true);
        dstip.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                if (dstip.isSelected()) {
                    jTable1.addColumn(columns[4]);
                    int index = findColumn("DST Mac");
                    if (index != -1) {
                        jTable1.moveColumn(jTable1.getColumnCount() - 1, index);
                    } else {
                        index = findColumn("DST Port");
                        if (index != -1) {
                            jTable1.moveColumn(jTable1.getColumnCount() - 1, index);
                        }
                    }
                } else {
                    int index = findColumn("DST IP");
                    columns[4] = jTable1.getColumnModel().getColumn(index);
                    jTable1.removeColumn(columns[4]);
                }
            }
        });
        top2.add(dstip);
        dstmac = new JCheckBox("DST Mac");
        dstmac.setSelected(true);
        dstmac.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                if (dstmac.isSelected()) {
                    jTable1.addColumn(columns[5]);
                    int index = findColumn("DST Port");
                    if (index != -1) {
                        jTable1.moveColumn(jTable1.getColumnCount() - 1, index);
                    }
                } else {
                    int index = findColumn("DST Mac");
                    columns[5] = jTable1.getColumnModel().getColumn(index);
                    jTable1.removeColumn(columns[5]);
                }
            }
        });
        top2.add(dstmac);
        dstport = new JCheckBox("DST Port");
        dstport.setSelected(true);
        dstport.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                if (dstport.isSelected()) {
                    jTable1.addColumn(columns[6]);
                } else {
                    int index = findColumn("DST Port");
                    columns[6] = jTable1.getColumnModel().getColumn(index);
                    jTable1.removeColumn(columns[6]);
                }
            }
        });
        top2.add(dstport);
        JButton bsave = new JButton(save);
        bsave.setToolTipText("Save as libpcap");
        bsave.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                saveFile();
            }
        });
        bsave.setBounds(645, 635, 120, 30);
        panel1.add(bsave);
        p.add(new JScrollPane(panel1));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:PacketSnifferPlugin.java

License:Apache License

public void updateTable(String command) {
    HashMap<String, HashMap> hash = null;
    try {/* w  ww  .  ja  va2  s  . co m*/
        DefaultTableModel model = ((DefaultTableModel) jTable1.getModel());
        Object obj = client.execute("runPlugin",
                new Object[] { variables.get("user"), getName(), "command=query&data=" + index });
        //System.out.println("Response: "+obj.toString());

        hash = (HashMap<String, HashMap>) obj;
        //hash = (HashMap<String, HashMap>) client.execute("runPlugin",
        //      new Object[] { variables.get("user"), getName(),
        //            "command=query&data=" + index });
        HashMap hash2 = hash.get("data");
        if (hash2.isEmpty()) {
            return;
        }
        index = hash2.get("id").toString();
        //System.out.println("index: "+index);
        Object[] hash3 = (Object[]) hash2.get("packets");
        //System.out.println("packets length: "+hash3.length);

        String protocol, sip, smac, sport, dip, dmac, dport, id = null;
        for (Object ob : hash3) {
            try {
                JsonElement el = new JsonParser().parse(ob.toString());
                JsonObject jobject = el.getAsJsonObject();

                el = jobject.get("packet_head");
                jobject = el.getAsJsonObject();

                JsonElement source = jobject.get("source");
                jobject = source.getAsJsonObject();
                source = jobject.get("ip");
                sip = source.toString();
                sip = sip.substring(1, sip.length() - 1);
                source = jobject.get("mac");
                smac = source.toString();
                smac = smac.substring(1, smac.length() - 1);
                source = jobject.get("port");
                sport = source.toString();
                jobject = el.getAsJsonObject();
                source = jobject.get("destination");
                jobject = source.getAsJsonObject();
                source = jobject.get("ip");
                dip = source.toString();
                dip = dip.substring(1, dip.length() - 1);
                source = jobject.get("mac");
                dmac = source.toString();
                dmac = dmac.substring(1, dmac.length() - 1);
                source = jobject.get("port");
                dport = source.toString();
                jobject = el.getAsJsonObject();
                source = jobject.get("protocol");
                protocol = source.toString();
                protocol = protocol.substring(1, protocol.length() - 1);
                source = jobject.get("id");
                id = source.toString();
                id = id.substring(1, id.length() - 1);
                model.addRow(new Object[] { protocol, sip, smac, sport, dip, dmac, dport, id });
            } catch (Exception e) {
                System.out.println("Server response: " + hash.toString());
                e.printStackTrace();
            }
        }
        if (model.getRowCount() > length) {
            int delete = model.getRowCount() - length;
            for (int i = 0; i < delete; i++) {
                //System.out.println("delete");
                model.removeRow(0);
            }
        }
    } catch (Exception e) {
        System.out.println("Server response: " + hash.toString());
        e.printStackTrace();
    }

}

From source file:$.$.java

License:Apache License

  private String parseArg(String arguments, ResourceOperation operation, PropertyValue value,
    String object) {//from w  ww  . j  a  va 2 s  . c  om
  // parse the argument string and get the "value" parameter
  JsonObject args;
  String val = null;
  JsonElement jsonElem = null;
  Boolean passed = true;

  // check for parameters from the command
  if (arguments != null) {
    args = new JsonParser().parse(arguments).getAsJsonObject();
    jsonElem = args.get(object);
  }

  // if the parameter is passed from the command, use it, otherwise treat parameter
  // as the default
  if (jsonElem == null || jsonElem.toString().equals("null")) {
    val = operation.getParameter();
    passed = false;
  } else {
    val = jsonElem.toString().replace("\"", "");
  }

  // if no value is specified by argument or parameter, take the object default from the profile
  if (val == null) {
    val = value.getDefaultValue();
    passed = false;
  }

  // if a mapping translation has been specified in the profile, use it
  Map<String,String> mappings = operation.getMappings();
  if (mappings != null && mappings.containsKey(val)) {
    val = mappings.get(val);
    passed = false;
  }

  if (!value.mask().equals(BigInteger.ZERO) && passed) {
    val = transform.format(value, val);
  }

  return val;
}

From source file:accessControl.AuthAPIService.java

License:Open Source License

public ArrayList<Path> getAvailablePaths(String subjectInfo, boolean isCertificate) {

    HttpURLConnection connection = null;
    try {// ww w .  ja v  a 2  s .  com
        //Create connection
        String finalURL = authServiceURI + "?getPaths=true";
        logger.debug("Sending request. URI:" + finalURL);
        URL url = new URL(finalURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");

        if (!isCertificate)
            connection.setRequestProperty("Cookie", subjectInfo);

        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.connect();

        if (isCertificate) {
            DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
            wr.writeBytes(subjectInfo);
            wr.flush();
            wr.close();
        }

        //Get Response
        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        StringBuilder response = new StringBuilder(); // or StringBuffer if not Java 5+
        String line;
        while ((line = rd.readLine()) != null) {
            response.append(line);
        }
        rd.close();

        String response_result = response.toString();

        // If the whole tree is allowed (administrator mode)
        // We need this since the list of administrators is stored on AC side
        if (response_result.equalsIgnoreCase("true")) {
            ArrayList<Path> res = new ArrayList<>();
            res.add(new Path("all"));
            return res;
        } else if (response_result.equalsIgnoreCase("false"))
            return null;

        // Parse the paths and return them
        JsonObject paths = new JsonParser().parse(response_result).getAsJsonObject();
        JsonArray json_paths = paths.getAsJsonArray("paths");

        ArrayList<Path> finalPaths = new ArrayList<>(json_paths.size());

        logger.debug(json_paths.size() + " PATHS FOUND");

        for (int i = 0; i < json_paths.size(); i++) {
            String pathString = json_paths.get(i).getAsString();
            logger.debug(pathString);
            Path nextPath = new Path(pathString);
            finalPaths.add(nextPath);
        }

        return finalPaths;

    } catch (Exception e) {
        logger.error("During getAvailablePaths request", e);
        return null;
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:adams.data.conversion.JsonToString.java

License:Open Source License

/**
 * Performs the actual conversion.//  ww w .j av  a 2 s.c o  m
 *
 * @return      the converted data
 * @throws Exception   if something goes wrong with the conversion
 */
@Override
protected Object doConvert() throws Exception {
    String result;
    Gson gson;
    JsonParser jp;
    JsonElement je;

    result = ((JSONAware) m_Input).toJSONString();

    if (m_PrettyPrinting) {
        gson = new GsonBuilder().setPrettyPrinting().create();
        jp = new JsonParser();
        je = jp.parse(result);
        result = gson.toJson(je);
    }

    return result;
}

From source file:adams.data.io.output.ViaAnnotationsReportWriter.java

License:Open Source License

/**
 * Performs the actual writing./*www.  j a v a  2 s . c o m*/
 *
 * @param data   the data to write
 * @return      true if successfully written
 */
@Override
protected boolean writeData(Report data) {
    LocatedObjects objs;
    int n;
    LocatedObject obj;
    JSONObject all;
    JSONObject jrep;
    JSONObject jregions;
    JSONObject jregion;
    JSONObject jshape;
    JSONArray jpoints;
    JSONObject jatts;
    String name;
    Polygon polygon;
    int[] x;
    int[] y;
    int i;
    String content;
    Gson gson;
    JsonParser jp;
    JsonElement je;

    all = new JSONObject();
    jrep = new JSONObject();
    jrep.put("fileref", "");
    jrep.put("size", 0);
    jrep.put("base64_img_data", "");
    jrep.put("file_attributes", new JSONObject());
    jregions = new JSONObject();
    jrep.put("regions", jregions);

    // get filename
    name = m_Output.getName(); // fallback
    if (data.hasValue("Name"))
        name = data.getStringValue("Name");
    else if (data.hasValue("Filename"))
        name = data.getStringValue("Filename");
    jrep.put("filename", name);
    all.put(name, jrep);

    // iterate objects
    objs = m_Finder.findObjects(data);
    for (n = 0; n < objs.size(); n++) {
        obj = objs.get(n);
        jregion = new JSONObject();
        jregions.put("" + n, jregion);
        jshape = new JSONObject();
        jregion.put("shape_attributes", jshape);
        jatts = new JSONObject();
        jregion.put("region_attributes", jatts);
        if (!m_LabelKey.isEmpty() && (obj.getMetaData().get(m_LabelKey) != null))
            jatts.put("name", obj.getMetaData().get(m_LabelKey));
        jshape.put("name", "polygon");
        if (obj.hasPolygon()) {
            polygon = obj.getPolygon();
            // x
            jpoints = new JSONArray();
            x = polygon.xpoints;
            for (i = 0; i < x.length; i++)
                jpoints.add(x[i]);
            jshape.put("all_points_x", jpoints);
            // y
            jpoints = new JSONArray();
            y = polygon.ypoints;
            for (i = 0; i < y.length; i++)
                jpoints.add(y[i]);
            jshape.put("all_points_y", jpoints);
        } else {
            // x
            jpoints = new JSONArray();
            jpoints.add(obj.getX());
            jpoints.add(obj.getX() + obj.getWidth() - 1);
            jpoints.add(obj.getX() + obj.getWidth() - 1);
            jpoints.add(obj.getX());
            jshape.put("all_points_x", jpoints);
            // y
            jpoints = new JSONArray();
            jpoints.add(obj.getY());
            jpoints.add(obj.getY());
            jpoints.add(obj.getY() + obj.getHeight() - 1);
            jpoints.add(obj.getY() + obj.getHeight() - 1);
            jshape.put("all_points_y", jpoints);
        }
    }

    if (m_PrettyPrinting) {
        gson = new GsonBuilder().setPrettyPrinting().create();
        jp = new JsonParser();
        je = jp.parse(all.toString());
        content = gson.toJson(je);
    } else {
        content = all.toString();
    }

    return FileUtils.writeToFile(m_Output.getAbsolutePath(), content, false);
}

From source file:adams.data.report.ReportJsonUtils.java

License:Open Source License

/**
 * Creates a report from the reader, reading in JSON.
 *
 * @param reader   the reader to obtain the JSON from
 * @return      the report, null if failed to create or find data
 * @throws Exception   if reading/parsing fails
 *//*from   w  w  w.j  a v  a  2 s .  c o  m*/
public static Report fromJson(Reader reader) throws Exception {
    JsonParser jp;
    JsonElement je;

    jp = new JsonParser();
    je = jp.parse(reader);
    return ReportJsonUtils.fromJson(je.getAsJsonObject());
}

From source file:adams.flow.sink.JsonFileWriter.java

License:Open Source License

/**
 * Executes the flow item./*from www  .  j  av a  2  s  .  co  m*/
 *
 * @return      null if everything is fine, otherwise error message
 */
@Override
protected String doExecute() {
    String result;
    String content;
    Gson gson;
    JsonParser jp;
    JsonElement je;

    result = null;

    content = ((JSONAware) m_InputToken.getPayload()).toJSONString();

    if (m_PrettyPrinting) {
        gson = new GsonBuilder().setPrettyPrinting().create();
        jp = new JsonParser();
        je = jp.parse(content);
        content = gson.toJson(je);
    }

    if (!FileUtils.writeToFile(m_OutputFile.getAbsolutePath(), content, false))
        result = "Failed to write JSON file: " + m_OutputFile;

    return result;
}

From source file:adams.gui.tools.previewbrowser.JsonPrettyPrintHandler.java

License:Open Source License

/**
 * Creates the actual view./* w w w  .  jav a2 s  .c  o  m*/
 *
 * @param file   the file to create the view for
 * @return      the view
 */
@Override
protected PreviewPanel createPreview(File file) {
    PreviewPanel result;
    TextEditorPanel textPanel;
    FileReader freader;
    BufferedReader breader;
    Gson gson;
    JsonParser jp;
    JsonElement je;
    String content;

    freader = null;
    breader = null;
    try {
        freader = new FileReader(file.getAbsolutePath());
        breader = new BufferedReader(freader);
        gson = new GsonBuilder().setPrettyPrinting().create();
        jp = new JsonParser();
        je = jp.parse(breader);
        content = gson.toJson(je);
        textPanel = new TextEditorPanel();
        textPanel.setContent(content);
        textPanel.setEditable(false);
        result = new PreviewPanel(textPanel, textPanel.getTextArea());
    } catch (Exception e) {
        textPanel = new TextEditorPanel();
        textPanel.open(file);
        textPanel.setEditable(false);
        result = new PreviewPanel(textPanel, textPanel.getTextArea());
    } finally {
        FileUtils.closeQuietly(breader);
        FileUtils.closeQuietly(freader);
    }

    return result;
}