Example usage for com.google.gson JsonElement getAsJsonObject

List of usage examples for com.google.gson JsonElement getAsJsonObject

Introduction

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

Prototype

public JsonObject getAsJsonObject() 

Source Link

Document

convenience method to get this element as a JsonObject .

Usage

From source file:com.devbury.mkremote.api.MacroListResponsePacketDeserializer.java

License:Open Source License

@Override
public MacroListResponsePacket deserialize(JsonElement json, Type t, JsonDeserializationContext context)
        throws JsonParseException {
    MacroListResponsePacket r = new MacroListResponsePacket();
    ArrayList<String> names = new ArrayList<String>();
    r.setMacroNames(names);//from w w  w  .j  a  v a 2s .c o m
    Iterator<JsonElement> it = json.getAsJsonObject().get("macroNames").getAsJsonArray().iterator();
    while (it.hasNext()) {
        names.add(it.next().getAsString());
    }
    return r;
}

From source file:com.devbury.mkremote.api.QuickLaunchListResponsePacketDeserializer.java

License:Open Source License

@Override
public QuickLaunchListResponsePacket deserialize(JsonElement json, Type t, JsonDeserializationContext context)
        throws JsonParseException {
    QuickLaunchListResponsePacket p = new QuickLaunchListResponsePacket();
    ArrayList<LaunchItem> items = new ArrayList<LaunchItem>();
    p.setItems(items);// w  ww  .j  ava 2  s.  c  o m
    Iterator<JsonElement> it = json.getAsJsonObject().get("items").getAsJsonArray().iterator();
    while (it.hasNext()) {
        items.add(buildLaunchItem(it.next()));
    }

    return p;
}

From source file:com.devbury.mkremote.api.QuickLaunchListResponsePacketDeserializer.java

License:Open Source License

protected LaunchItem buildLaunchItem(JsonElement json) {
    LaunchItem item = new LaunchItem();
    JsonObject o = json.getAsJsonObject();
    item.setName(o.get("name").getAsString());
    item.setPath(o.get("path").getAsString());
    item.setType(o.get("type").getAsInt());
    item.setIcon(o.get("icon").getAsString());
    return item;/* w  w  w. jav  a 2s  . co  m*/
}

From source file:com.devicehive.json.adapters.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }//from  w w w.j a  va 2s . c o  m

    final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<String, TypeAdapter<?>>();
    final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<Class<?>, TypeAdapter<?>>();
    for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
        TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue()));
        labelToDelegate.put(entry.getKey(), delegate);
        subtypeToDelegate.put(entry.getValue(), delegate);
    }

    return new TypeAdapter<R>() {
        @Override
        public R read(JsonReader in) throws IOException {
            JsonElement jsonElement = Streams.parse(in);
            //                JsonElement labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName);
            JsonElement labelJsonElement = jsonElement.getAsJsonObject().get(typeFieldName);
            if (labelJsonElement == null) {
                throw new JsonParseException("cannot deserialize " + baseType
                        + " because it does not define a field named " + typeFieldName);
            }
            String label = labelJsonElement.getAsString();
            @SuppressWarnings("unchecked") // registration requires that subtype extends T
            TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label);
            if (delegate == null) {
                throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label
                        + "; did you forget to register a subtype?");
            }
            return delegate.fromJsonTree(jsonElement);
        }

        @Override
        public void write(JsonWriter out, R value) throws IOException {
            Class<?> srcType = value.getClass();
            String label = subtypeToLabel.get(srcType);
            @SuppressWarnings("unchecked") // registration requires that subtype extends T
            TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType);
            if (delegate == null) {
                throw new JsonParseException(
                        "cannot serialize " + srcType.getName() + "; did you forget to register a subtype?");
            }
            JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject();
            //                if (jsonObject.has(typeFieldName)) {
            //                    throw new JsonParseException("cannot serialize " + srcType.getName()
            //                            + " because it already defines a field named " + typeFieldName);
            //                }
            //                JsonObject clone = new JsonObject();
            //                clone.add(typeFieldName, new JsonPrimitive(label));
            //                for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
            //                    clone.add(e.getKey(), e.getValue());
            //                }
            //                Streams.write(clone, out);
            Streams.write(jsonObject, out);
        }
    }.nullSafe();
}

From source file:com.dict.crawl.NewsNationalGeographicCrawler.java

License:Open Source License

public static void main(String[] args) throws Exception {
    /*string,crawlPath??crawlPath,
      ????crawlPath//w w w. j a v  a 2 s .  com
    */

    NewsNationalGeographicCrawler crawler = new NewsNationalGeographicCrawler("data/NewsNationalGeographic");
    crawler.setThreads(2);
    crawler.addSeed("http://ngm.nationalgeographic.com/");

    if (BaseCrawler.isNormalTime()) {

        crawler.addSeed("http://ngm.nationalgeographic.com/archives");
        crawler.addSeed("http://ngm.nationalgeographic.com/featurehub");
        //
        //}

        String jsonUrl = "http://news.nationalgeographic.com/bin/services/news/public/query/content.json?pageSize=20&page=0&contentTypes=news/components/pagetypes/article,news/components/pagetypes/simple-article,news/components/pagetypes/photo-gallery";

        URL urls = new URL(jsonUrl);
        HttpURLConnection urlConnection = (HttpURLConnection) urls.openConnection();
        InputStream is = urlConnection.getInputStream();
        Reader rd = new InputStreamReader(is, "utf-8");
        JsonArray json = new JsonParser().parse(rd).getAsJsonArray();
        for (JsonElement jOb : json) {
            String url = jOb.getAsJsonObject().get("page").getAsJsonObject().get("url").getAsString();
            if (url != null && !url.equals(""))
                crawler.addSeed(url);
        }

    }

    //        crawler.addSeed("http://news.nationalgeographic.com/2016/01/160118-mummies-world-bog-egypt-science/");
    //        List<Map<String, Object>> urls = crawler.jdbcTemplate.queryForList("SELECT id,title,url FROM parser_page where host like '%news.national%' ORDER by id desc;");
    //        for(int i = 0; i < urls.size(); i++) {
    //            String url = (String) urls.get(i).get("url");
    //            String title = (String) urls.get(i).get("title");
    ////            int id = (int) urls.get(i).get("id");
    //            crawler.addSeed(url);
    //        }

    //        Config
    Config.WAIT_THREAD_END_TIME = 1000 * 60 * 5;//???kill
    //        Config.TIMEOUT_CONNECT = 1000*10;
    //        Config.TIMEOUT_READ = 1000*30;
    Config.requestMaxInterval = 1000 * 60 * 20;//??-?>hung

    //requester??http??requester?http/socks?
    HttpRequesterImpl requester = (HttpRequesterImpl) crawler.getHttpRequester();
    AntiAntiSpiderHelper.defaultUserAgent(requester);

    //        requester.setUserAgent("Mozilla/5.0 (X11; Linux i686; rv:33.0) Gecko/20100101 Firefox/33.0");
    //        requester.setCookie("CNZZDATA1950488=cnzz_eid%3D739324831-1432460954-null%26ntime%3D1432460954; wdcid=44349d3f2aa96e51; vjuids=-53d395da8.14eca7eed44.0.f17be67e; CNZZDATA3473518=cnzz_eid%3D1882396923-1437965756-%26ntime%3D1440635510; pt_37a49e8b=uid=FuI4KYEfVz5xq7L4nzPd1w&nid=1&vid=r4AhSBmxisCiyeolr3V2Ow&vn=1&pvn=1&sact=1440639037916&to_flag=0&pl=t4NrgYqSK5M357L2nGEQCw*pt*1440639015734; _ga=GA1.3.1121158748.1437970841; __auc=c00a6ac114d85945f01d9c30128; CNZZDATA1975683=cnzz_eid%3D250014133-1432460541-null%26ntime%3D1440733997; CNZZDATA1254041250=2000695407-1442220871-%7C1442306691; pt_7f0a67e8=uid=6lmgYeZ3/jSObRMeK-t27A&nid=0&vid=lEKvEtZyZdd0UC264UyZnQ&vn=2&pvn=1&sact=1442306703728&to_flag=0&pl=7GB3sYS/PJDo1mY0qeu2cA*pt*1442306703728; 7NSx_98ef_saltkey=P05gN8zn; 7NSx_98ef_lastvisit=1444281282; IframeBodyHeight=256; NTVq_98ef_saltkey=j5PydYru; NTVq_98ef_lastvisit=1444282735; NTVq_98ef_atarget=1; NTVq_98ef_lastact=1444286377%09api.php%09js; 7NSx_98ef_sid=hZyDwc; __utmt=1; __utma=155578217.1121158748.1437970841.1443159326.1444285109.23; __utmb=155578217.57.10.1444285109; __utmc=155578217; __utmz=155578217.1439345650.3.2.utmcsr=travel.chinadaily.com.cn|utmccn=(referral)|utmcmd=referral|utmcct=/; CNZZDATA3089622=cnzz_eid%3D1722311508-1437912344-%26ntime%3D1444286009; wdlast=1444287704; vjlast=1437916393.1444285111.11; 7NSx_98ef_lastact=1444287477%09api.php%09chinadaily; pt_s_3bfec6ad=vt=1444287704638&cad=; pt_3bfec6ad=uid=bo87MAT/HC3hy12HDkBg1A&nid=0&vid=erwHQyFKxvwHXYc4-r6n-w&vn=28&pvn=2&sact=1444287708079&to_flag=0&pl=kkgvLoEHXsCD2gs4VJaWQg*pt*1444287704638; pt_t_3bfec6ad=?id=3bfec6ad.bo87MAT/HC3hy12HDkBg1A.erwHQyFKxvwHXYc4-r6n-w.kkgvLoEHXsCD2gs4VJaWQg.nZJ9Aj/bgfNDIKBXI5TwRQ&stat=167.132.1050.1076.1body%20div%3Aeq%288%29%20ul%3Aeq%280%29%20a%3Aeq%282%29.0.0.1595.3441.146.118&ptif=4");
    //?? Mozilla/5.0 (X11; Linux i686; rv:34.0) Gecko/20100101 Firefox/34.0
    //c requester.setProxy("
    /*
            
    //??
    RandomProxyGenerator proxyGenerator=new RandomProxyGenerator();
    proxyGenerator.addProxy("127.0.0.1",8080,Proxy.Type.SOCKS);
    requester.setProxyGenerator(proxyGenerator);
    */

    /*??*/
    //        crawler.setResumable(true);
    crawler.setResumable(false);

    crawler.start(2);
}

From source file:com.distance.DistanceServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w w  w .j a va  2  s.  c  om
 *
 * @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.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 {//  w  w w .j  a  v  a  2s.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.drakeet.rebase.api.tool.ResponseTypeAdapterFactory.java

License:Open Source License

@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    final TypeAdapter<T> delegateAdapter = gson.getDelegateAdapter(this, type);
    final TypeAdapter<JsonElement> jsonElementAdapter = gson.getAdapter(JsonElement.class);

    return new TypeAdapter<T>() {
        @Override/*w w  w.ja v a  2  s.  c o  m*/
        public void write(JsonWriter out, T value) throws IOException {
            delegateAdapter.write(out, value);
        }

        @Override
        @SuppressWarnings("PointlessBooleanExpression")
        public T read(JsonReader in) throws IOException {
            JsonElement jsonElement = jsonElementAdapter.read(in);
            if (jsonElement.isJsonObject()) {
                JsonObject jsonObject = jsonElement.getAsJsonObject();
                if (jsonObject.has(ERROR) && jsonObject.get(ERROR).getAsBoolean() == false) {
                    if (jsonObject.has(DATA) && isJson(jsonObject, DATA)) {
                        jsonElement = jsonObject.get(DATA);
                    }
                }
            }
            return delegateAdapter.fromJsonTree(jsonElement);
        }
    }.nullSafe();
}

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   www  . j  a v  a 2s  . co  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;
}

From source file:com.driver733.vkuploader.wallpost.attachment.support.strings.AttachmentStringsFromJson.java

License:Open Source License

@Override
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
public List<String> attachmentStrings() throws IOException {
    final List<String> list;
    try {//from   w  w  w. j a  va  2s  .c o  m
        if (this.root.isJsonArray()) {
            list = new ArrayList<>(this.root.getAsJsonArray().size());
            final JsonArray array = this.root.getAsJsonArray();
            for (final JsonElement element : array) {
                list.add(
                        new AttachmentStringFromJson(element.getAsJsonObject(), this.group).attachmentString());
            }
        } else {
            list = new ArrayList<>(1);
            list.add(new AttachmentStringFromJson(this.root, this.group).attachmentString());
        }
    } catch (final IOException ex) {
        throw new IOException("Could not extract attachment attachmentString.", ex);
    }
    return list;
}