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:com.discord.bot.BingHandler.java

public String bingSearch(String searchQuery) {
    String link = "";
    try {/*from   w ww . j  a va 2 s . c  om*/
        final String bingUrlPattern = "https://api.datamarket.azure.com/Bing/Search/Image?Query=%%27%s%%27&$format=JSON&Adult=%%27Off%%27";

        final String query = URLEncoder.encode(searchQuery, StandardCharsets.UTF_8.name());
        final String bingUrl = String.format(bingUrlPattern, query);

        final String accountKeyEnc = Base64.getEncoder()
                .encodeToString((AuthVariables.ACCOUNTKEY + ":" + AuthVariables.ACCOUNTKEY).getBytes());

        final URL url = new URL(bingUrl);
        final URLConnection connection1 = url.openConnection();
        connection1.setRequestProperty("Authorization", "Basic " + accountKeyEnc);
        try (final BufferedReader in = new BufferedReader(
                new InputStreamReader(connection1.getInputStream()))) {
            String inputLine;
            final StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            try {
                JsonParser jsonParser = new JsonParser();
                int size = jsonParser.parse(response.toString()).getAsJsonObject().getAsJsonObject("d")
                        .getAsJsonObject().getAsJsonArray("results").size();

                if (size > 0) {
                    Random r = new Random();

                    int choice = r.nextInt(size);
                    JsonObject searchInfo = jsonParser.parse(response.toString()).getAsJsonObject()
                            .getAsJsonObject("d").getAsJsonObject().getAsJsonArray("results").get(choice)
                            .getAsJsonObject();

                    link = searchInfo.get("MediaUrl").getAsString();
                    link += " " + searchInfo.get("Title").getAsString();
                }

            } catch (JsonSyntaxException | java.lang.IndexOutOfBoundsException e) {
                return "";
            }
        }
    } catch (MalformedURLException ex) {
        Logger.getLogger(BingHandler.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException e) {
        Logger.getLogger(BingHandler.class.getName()).log(Level.SEVERE, null, e);
    }

    return link;
}

From source file:com.discord.bot.ImgurHandler.java

public String randomImgur() {
    String json = "";
    String message = "";
    try {/*  w w w  .  ja  va  2  s  .  c  om*/
        Random r = new Random();

        int randomPage = 1 + r.nextInt(4);

        ZonedDateTime timeNow = ZonedDateTime.now();
        if (lastImgurCall == null || lastImgurCall.compareTo(timeNow.minusMinutes(TIMELIMIT)) <= 0
                || randomImgurNumbers.size() >= IMGURLIMIT) {
            String url = "https://api.imgur.com/3/gallery/random/random/" + Integer.toString(randomPage);
            json = Bot.readAuthUrl(url);
            // There are 5 random imgur sites. For some reason, some of them are sometimes empty.
            // Lets get the first one thats not empty.
            for (int i = 0; json.isEmpty() || i == 5; i++) {
                randomPage = 1 + r.nextInt(4);
                url = "https://api.imgur.com/3/gallery/random/random/" + Integer.toString(randomPage);
                json = Bot.readAuthUrl(url);
            }
            lastImgurCall = ZonedDateTime.now();
            if (randomImgurNumbers.size() >= IMGURLIMIT) {
                randomImgurNumbers.clear();
            }
        }

        int choice = 1 + r.nextInt(49);

        while (randomImgurNumbers.contains(choice)) {
            choice = 1 + r.nextInt(49);
        }
        if (!randomImgurNumbers.contains(choice)) {
            randomImgurNumbers.add(choice);
        }

        JsonParser jsonParser = new JsonParser();
        JsonObject imgurInfo = jsonParser.parse(json).getAsJsonObject().getAsJsonArray("data").get(choice)
                .getAsJsonObject();

        String link = imgurInfo.get("link").getAsString();
        String title = imgurInfo.get("title").getAsString();

        message = link + " " + title;

    } catch (Exception ex) {
        Logger.getLogger(ImgurHandler.class.getName()).log(Level.SEVERE, null, ex);
    }
    return message;
}

From source file:com.discord.bot.ImgurHandler.java

public String randomSubredditImgur(String subreddit) {
    String json = "";
    String message = "";
    try {//from ww w.  ja  v  a  2  s  . c  o  m
        String url = "https://api.imgur.com/3/gallery/r/" + subreddit;
        json = Bot.readAuthUrl(url);

        if (!json.isEmpty()) {
            JsonParser jsonParser = new JsonParser();
            int size = jsonParser.parse(json).getAsJsonObject().getAsJsonArray("data").size();

            if (size > 0) {
                Random r = new Random();

                int randomPage = r.nextInt(size);

                JsonObject imgurInfo = jsonParser.parse(json).getAsJsonObject().getAsJsonArray("data")
                        .get(randomPage).getAsJsonObject();

                String link = "";
                if (imgurInfo.get("type").getAsString().equals("image/gif")) {
                    link = imgurInfo.get("gifv").getAsString();
                } else {
                    link = imgurInfo.get("link").getAsString();
                }
                String title = imgurInfo.get("title").getAsString();

                if (!link.isEmpty() && !title.isEmpty()) {
                    message = link + " " + title;
                } else if (!link.isEmpty()) {
                    message = link;
                }
            }

        }
    } catch (Exception ex) {
        Logger.getLogger(ImgurHandler.class.getName()).log(Level.SEVERE, null, ex);
    }
    return message;
}

From source file:com.distance.DistanceServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  ww w  .  j  a  v a  2 s  .c o  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");
    if (request.getParameter("zip1") != null && request.getParameter("zip2") != null) {

        try {
            String type = request.getParameter("type") == null ? "mi" : request.getParameter("type");

            URL url = new URL("http://api.geonames.org/postalCodeLookupJSON?postalcode="
                    + request.getParameter("zip1") + "&country=US&username=nailyusupov");
            URLConnection conn = url.openConnection();
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line = br.readLine();
            JsonElement jelement = new JsonParser().parse(line);
            JsonObject jobject = jelement.getAsJsonObject();
            jobject = jobject.getAsJsonArray("postalcodes").get(0).getAsJsonObject();
            String lng1 = jobject.get("lng").toString();
            String lat1 = jobject.get("lat").toString();

            url = new URL("http://api.geonames.org/postalCodeLookupJSON?postalcode="
                    + request.getParameter("zip2") + "&country=US&username=nailyusupov");
            conn = url.openConnection();
            br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            line = br.readLine();
            jelement = new JsonParser().parse(line);
            jobject = jelement.getAsJsonObject();
            jobject = jobject.getAsJsonArray("postalcodes").get(0).getAsJsonObject();
            String lng2 = jobject.get("lng").toString();
            String lat2 = jobject.get("lat").toString();
            br.close();

            response.getWriter()
                    .write(new Gson().toJson(String.format("%.2f",
                            haversine(Double.valueOf(lat1), Double.valueOf(lng1), Double.valueOf(lat2),
                                    Double.valueOf(lng2), type.equals("km") ? 6371 : 3959))));
        } catch (Exception e) {
            response.getWriter().write(new Gson().toJson("Invalid parameters"));
        }
    } else {
        response.getWriter().write(new Gson().toJson(
                "/distance?zip1=xxxxx&zip2=xxxxx\n\ndistance between zip codes is calculated in miles use type=km for kilometers"));
    }
}

From source file:com.diversityarrays.dalclient.DalUtil.java

License:Open Source License

/**
 * Parse the input json string  and return the parse result if it is a JsonObject.
 * This is because a valid DAL JSON response is always and only of that structure.
 * @param json/*from   www . j a va  2  s  .  c o  m*/
 * @return either JsonResult or null if the input cannot be parsed
 * @throws DalResponseFormatException
 */
public static JsonResult parseJson(String requestUrl, String json) throws DalResponseFormatException {
    JsonResult result = null;
    try {
        JsonElement jsonElement = new JsonParser().parse(json);
        if (!jsonElement.isJsonObject()) {
            throw new DalResponseFormatException(
                    String.format("input is not a JsonObject: %s", jsonElement.getClass().getName()));
        }
        result = new JsonResultImpl(requestUrl, (JsonObject) jsonElement);
    } catch (JsonSyntaxException e) {
        throw new DalResponseFormatException(e);
    }
    return result;
}

From source file:com.doitnext.swing.widgets.json.JSONEditPanel.java

License:Apache License

/**
 * Replaces the current tree structure in the contained JTree component
 * with a new structure built from the JSON string provided.
 * /*  w w  w.j ava  2s .  c  o m*/
 * @param json - the JSON to update the tree control with
 * @param updateType - if a node is selected when this method is called
 *    then the updateType indicates where the new json goes:
 *    REPLACE - replace current selected node with new JSON
 *    INSERT - place node before selected node
 *    APPEND - place node after selected node
 *    AS_CHILD - append to end of child nodes or insert new child node if no
 *            children present.  Selected node must be of type ARRAY or OBJECT
 */
@SuppressWarnings("unchecked")
public void setJson(String json, UpdateType updateType) {
    TreePath selection = jTree.getSelectionPath();
    if (selection == null) {
        if (updateType == UpdateType.REPLACE) {
            JsonElement root = new JsonParser().parse(json);
            JSONJTreeNode rootNode = new JSONJTreeNode(null, -1, root);
            jTree.setModel(new DefaultTreeModel(rootNode));
        } else {
            JOptionPane.showMessageDialog(this,
                    "Only replace JSON and get JSON are supported when no node is selected.", "Notice",
                    JOptionPane.INFORMATION_MESSAGE);
        }
    } else {
        JSONJTreeNode selectedNode = (JSONJTreeNode) selection.getLastPathComponent();
        JSONJTreeNode parent = (JSONJTreeNode) selectedNode.getParent();
        switch (updateType) {
        case REPLACE: {
            if (parent == null) {
                JsonElement root = new JsonParser().parse(json);
                JSONJTreeNode rootNode = new JSONJTreeNode(null, -1, root);
                jTree.setModel(new DefaultTreeModel(rootNode));
                return;
            }
            JsonElement root = new JsonParser().parse(json);
            JSONJTreeNode replacementNode = new JSONJTreeNode(selectedNode.fieldName, selectedNode.index, root);
            int index = selectedNode.getParent().getIndex(selectedNode);
            selectedNode.removeFromParent();
            parent.insert(replacementNode, index);
            ((DefaultTreeModel) jTree.getModel()).reload(parent);
        }
            break;
        case INSERT:
        case APPEND: {
            if (parent == null) {
                JOptionPane.showMessageDialog(this, "You cannot append to the root element.", "Notice",
                        JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            JsonElement root = new JsonParser().parse(json);
            JSONJTreeNode replacementNode = new JSONJTreeNode(selectedNode.fieldName, selectedNode.index, root);
            int index = selectedNode.getParent().getIndex(selectedNode);
            if (updateType.equals(UpdateType.APPEND))
                index++;
            parent.insert(replacementNode, index);
            ((DefaultTreeModel) jTree.getModel()).reload(parent);
        }
            break;
        case AS_CHILD: {
            JsonElement root = new JsonParser().parse(json);
            String fieldName = null;
            int arrayIndex = -1;
            if (selectedNode.dataType.equals(JSONJTreeNode.DataType.ARRAY)) {
                Enumeration en = selectedNode.children();
                int count = 0;
                while (en.hasMoreElements()) {
                    en.nextElement();
                    count++;
                }
                arrayIndex = count;
            } else if (selectedNode.dataType.equals(JSONJTreeNode.DataType.OBJECT))
                fieldName = "new-field";
            else {
                JOptionPane.showMessageDialog(this, "Vaue type entities can not have children.", "Notice",
                        JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            JSONJTreeNode newNode = new JSONJTreeNode(fieldName, arrayIndex, root);
            selectedNode.add(newNode);
            ((DefaultTreeModel) jTree.getModel()).reload(selectedNode);
        }
            break;
        }
    }
}

From source file:com.doitnext.swing.widgets.json.JSONJTreeNode.java

License:Apache License

public JsonElement asJsonElement() {
    StringBuilder sb = new StringBuilder();
    buildJsonString(sb);/*from w  w  w. j a  v  a  2  s .  c o m*/
    String json = sb.toString().trim();
    if (json.startsWith("{") || json.startsWith("["))
        return new JsonParser().parse(sb.toString());
    else {
        // Safety check the JSON, if it is of a named value object
        // We cheat a little if it is an orphan name value pair then
        // if we wrap it in {} chars it will parse if it isn't the parse
        // fails.         
        String testValue = "{" + json + "}";
        try {
            JsonElement wrapperElt = new JsonParser().parse(testValue);
            JsonObject obj = (JsonObject) wrapperElt;
            Iterator<Entry<String, JsonElement>> it = obj.entrySet().iterator();
            Entry<String, JsonElement> entry = it.next();
            return entry.getValue();
        } catch (JsonSyntaxException jse) {
            JsonElement rawElement = new JsonParser().parse(json);
            return rawElement;
        }
    }
}

From source file:com.doitnext.swing.widgets.json.JSONJTreeNode.java

License:Apache License

@SuppressWarnings("unchecked")
private void buildJsonString(StringBuilder sb) {
    if (!StringUtils.isEmpty(this.fieldName)) {
        sb.append("\"" + this.fieldName + "\":");
    }//from   w w  w  . ja  v  a2 s .  com
    Enumeration children;
    switch (dataType) {
    case ARRAY:
        sb.append("[");
        children = this.children();
        while (children.hasMoreElements()) {
            JSONJTreeNode child = (JSONJTreeNode) children.nextElement();
            child.buildJsonString(sb);
            if (children.hasMoreElements())
                sb.append(",");
        }
        sb.append("]");
        break;
    case OBJECT:
        sb.append("{");
        children = this.children();
        while (children.hasMoreElements()) {
            JSONJTreeNode child = (JSONJTreeNode) children.nextElement();
            child.buildJsonString(sb);
            if (children.hasMoreElements())
                sb.append(",");
        }
        sb.append("}");
        break;
    default: {
        // Use the JSON parser to parse the value for safety
        JsonElement elt = new JsonParser().parse(this.value);
        sb.append(elt.toString());
    }
    }
}

From source file:com.dozersoftware.snap.PosRepProcessor.java

License:Open Source License

public Message http(Message message) throws ActionProcessingException {

    System.out.println("&&&&&&&&&&&&&&&& PosRepProcessor &&&&&&&&&&&&&&&&&&&&&");
    System.out.println("");
    System.out.println("Service: " + service);
    System.out.println("");
    // System.out.println("------------Http Request Info (XStream Encoded)-------------------");
    // HttpRequest requestInfo = HttpRequest.getRequest(message);
    // String requestInfoXML;

    // XStream xstream = new XStream();
    // requestInfoXML = xstream.toXML(requestInfo);

    // System.out.println(requestInfoXML);

    System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");

    try {/*from   w  w w  .j ava 2 s  . c  o m*/
        StringWriter sw = new StringWriter();
        final Kml kml = new Kml();
        Map<URI, Message> msgs = messageStore.getAllMessages("PosRep");
        Iterator<URI> it = msgs.keySet().iterator();
        System.out.println("Tracking for :" + msgs.size() + " records");
        while (it.hasNext()) {
            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
            String raw = (String) msgs.get(it.next()).getBody().get();

            Document doc = dBuilder.parse(new ByteArrayInputStream(raw.getBytes()));

            doc.getDocumentElement().normalize();
            NodeList body = doc.getElementsByTagName("BODY");
            String handle = doc.getDocumentElement().getAttribute("sender");
            Node e = body.item(0);
            System.out.println("SNAP: " + handle + "'s PosRep -> " + e.getTextContent());
            JsonElement jse = new JsonParser().parse(e.getTextContent());
            if (jse.isJsonObject()) {
                System.out.println("We got the right thing: " + jse.toString());
                JsonArray ja = jse.getAsJsonObject().getAsJsonArray("POSREP");
                // {"POSREP":
                // [16,"Aug 17, 2010 3:11:00 AM","31.74","-111.11"]}
                Double lat = ja.get(2).getAsDouble();
                Double lng = ja.get(3).getAsDouble();

                kml.createAndSetPlacemark().withName(handle).withOpen(Boolean.TRUE).createAndSetPoint()
                        .addToCoordinates(lng, lat);
            } else {
                System.out.println("Not an Array!");
            }

        }

        System.out.println("Processed all positions...");
        kml.marshal(sw);

        message.getBody().add(sw.toString());
    } catch (DOMException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JsonParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MessageStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return message;

}

From source file:com.drguildo.bm.BookmarksManager.java

License:Open Source License

public static Bookmarks load() throws IOException {
    StringBuilder stringBuilder = new StringBuilder();

    if (!Files.exists(bookmarkPath)) {
        return bookmarks;
    }/*from  w  ww .j av  a 2 s .c  o m*/

    try {
        BufferedReader bufferedReader = new BufferedReader(new FileReader(bookmarkFile));
        String string = bufferedReader.readLine();

        while (string != null) {
            stringBuilder.append(string);
            string = bufferedReader.readLine();
        }

        bufferedReader.close();
    } catch (IOException e) {
        e.printStackTrace();
        throw new IOException(e);
    }

    if (stringBuilder.length() == 0) {
        return bookmarks;
    }

    String json = stringBuilder.toString();

    JsonParser parser = new JsonParser();
    JsonArray array = parser.parse(json).getAsJsonArray();

    for (JsonElement element : array) {
        JsonObject jsonObject = element.getAsJsonObject();

        URL url = new URL(jsonObject.get("url").getAsString());

        Tags tags = new Tags();
        for (JsonElement tagElement : jsonObject.get("tags").getAsJsonArray()) {
            tags.add(tagElement.getAsString());
        }

        Date date = new Date(jsonObject.get("added").getAsLong());

        bookmarks.add(new Bookmark(url, tags, date));
    }

    return bookmarks;
}