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.adobe.acs.commons.remoteassets.impl.RemoteAssetsNodeSyncImpl.java

License:Apache License

/**
 * Get {@link JsonObject} from URL response.
 *
 * @param path String/* ww  w.j a  va 2  s  .  c  o  m*/
 * @return JsonObject
 * @throws IOException exception
 */
private JsonObject getJsonFromUri(final String path) throws IOException {
    URI pathUri;
    try {
        pathUri = new URI(null, null, path, null);
    } catch (URISyntaxException e) {
        LOG.error("URI Syntax Exception", e);
        throw new IOException("Invalid URI", e);
    }

    // we want to traverse the JCR one level at a time, hence the '1' selector.
    String url = this.remoteAssetsConfig.getServer() + pathUri.toString() + ".1.json";
    Executor executor = this.remoteAssetsConfig.getRemoteAssetsHttpExecutor();
    String responseString = executor.execute(Request.Get(url)).returnContent().asString();

    try {
        JsonObject responseJson = new JsonParser().parse(responseString).getAsJsonObject();
        LOG.debug("JSON successfully fetched for URL '{}'.", url);
        return responseJson;
    } catch (JsonSyntaxException | IllegalStateException e) {
        LOG.error("Unable to grab JSON Object. Please ensure URL {} is valid. \nRaw Response: {}", url,
                responseString);
        throw new IOException("Invalid JSON response", e);
    }
}

From source file:com.adobe.acs.commons.workflow.bulk.execution.impl.servlets.StartServlet.java

License:Apache License

@Override
@SuppressWarnings("squid:S1192")
protected final void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");

    try {//from  w w w  .j a  va  2s .  com
        final JsonObject params = new JsonParser().parse(request.getParameter("params")).getAsJsonObject();
        final ModifiableValueMap properties = request.getResource().adaptTo(ModifiableValueMap.class);

        properties.put("runnerType", getString(params, "runnerType"));
        properties.put("queryType", getString(params, "queryType"));
        properties.put("queryStatement", getString(params, "queryStatement"));
        properties.put("relativePath", StringUtils.removeStart(getString(params, "relativePath", ""), "/"));
        properties.put("workflowModel", getString(params, "workflowModelId"));
        properties.put("interval", getInteger(params, "interval", 10));
        properties.put("timeout", getInteger(params, "timeout", 30));
        properties.put("throttle", getInteger(params, "throttle", 10));
        properties.put("retryCount", getInteger(params, "retryCount", 0));
        properties.put("batchSize", getInteger(params, "batchSize", 10));
        String userEventData = getString(params, "userEventData");
        if (userEventData != null && !userEventData.isEmpty()) {
            properties.put("userEventData", userEventData);
        }

        properties.put("purgeWorkflow", getBoolean(params, "purgeWorkflow", false));
        properties.put("autoThrottle", getBoolean(params, "autoThrottle", true));

        if (AEMWorkflowRunnerImpl.class.getName().equals(properties.get("runnerType", String.class))
                && isTransient(request.getResourceResolver(), properties.get("workflowModel", String.class))) {
            properties.put("runnerType", AEMTransientWorkflowRunnerImpl.class.getName());
        }

        // If FAM retires are enabled, then force BatchSize to be 1
        if (FastActionManagerRunnerImpl.class.getName().equals(properties.get("runnerType", ""))
                && properties.get("retryCount", 0) > 0) {
            properties.put("batchSize", 1);
        }

        request.getResourceResolver().commit();

        Config config = request.getResource().adaptTo(Config.class);

        bulkWorkflowEngine.initialize(config);
        bulkWorkflowEngine.start(config);

        response.sendRedirect(
                request.getResourceResolver().map(request, request.getResource().getPath()) + ".status.json");

    } catch (RepositoryException e) {
        log.error("Could not initialize Bulk Workflow: {}", e);

        JSONErrorUtil.sendJSONError(response, SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Could not initialize Bulk Workflow.", e.getMessage());

    } catch (IllegalArgumentException e) {
        log.warn("Could not initialize Bulk Workflow due to invalid arguments: {}", e);

        JSONErrorUtil.sendJSONError(response, SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Could not initialize Bulk Workflow due to invalid arguments.", e.getMessage());

    } catch (Exception e) {
        log.error("Could not initialize Bulk Workflow due to unexpected error: {}", e);

        JSONErrorUtil.sendJSONError(response, SlingHttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Could not start Bulk Workflow.", e.getMessage());
    }
}

From source file:com.adobe.ags.curly.controller.DataImporterController.java

License:Apache License

private void openJson(File file) throws FileNotFoundException, IOException {
    FileReader fileReader = new FileReader(file);
    try (BufferedReader reader = new BufferedReader(fileReader)) {
        JsonParser parser = new JsonParser();
        JsonObject data = parser.parse(reader).getAsJsonObject();

        data.entrySet().stream().filter((entry) -> (entry.getValue().isJsonArray())).forEach((entry) -> {
            worksheetSelector.getItems().add(entry.getKey());
        });/*  w  w w.j  av a 2 s.c o  m*/

        sheetReader = (String node) -> readNodes(data.get(node).getAsJsonArray());
        skipFirstSelection.setValue(1);
        Platform.runLater(() -> worksheetSelector.getSelectionModel().selectFirst());
    }
}

From source file:com.adssets.api.Scout24.java

@Override
public String getApartments(String objectId) {
    try {/*  ww w  . j  av a2s  .com*/
        // Make an API call... it is required to sign each request (see below)  
        //1276
        //            URL url = new URL("http://rest.immobilienscout24.de/restapi/api/search/v1.0/search/region?realestatetype=apartmentbuy&geocodes=" + regionid );
        URL url = new URL("https://rest.immobilienscout24.de/restapi/api/search/v1.0/expose/" + objectId);
        HttpURLConnection requestUrl = null;
        requestUrl = (HttpURLConnection) url.openConnection();

        consumer.sign(requestUrl);

        //            System.out.println("Sending request...");
        requestUrl.connect();

        //            System.out.println("Expiration " + requestUrl.getExpiration());
        //
        //            System.out.println("Timeout " + requestUrl.getConnectTimeout());
        //
        //            System.out.println("URL " + requestUrl.getURL());
        //
        //            System.out.println("Method " + requestUrl.getRequestMethod());
        //
        //            System.out.println("Response: " + requestUrl.getResponseCode() + " " + requestUrl.getResponseMessage());
        BufferedReader br = new BufferedReader(new InputStreamReader(requestUrl.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;

        switch (requestUrl.getResponseCode()) {
        case 200:
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            br.close();

            try {

                JSONObject outObj = XML.toJSONObject(sb.toString());
                JsonParser parser = new JsonParser();

                Object objPrice = new Object();
                JsonObject objPriceJson = new JsonObject();
                //                        JSONObject objTitlePicture = new JSONObject();
                JSONArray objAllPictures = new JSONArray();
                JSONObject objAdPicture = new JSONObject();
                JSONObject objAddress = new JSONObject();
                Object objPricem2 = new Object();
                JsonObject objPricem2Json = new JsonObject();
                JSONObject objLivingspace = new JSONObject();
                JSONObject obj = new JSONObject();

                //                        System.out.println(outObj.toString());
                objPrice = outObj.getJSONObject("expose:expose").getJSONObject("realEstate")
                        .get("calculatedPrice"); //price

                objPriceJson = parser.parse(objPrice.toString()).getAsJsonObject();

                //                        objTitlePicture = outObj.getJSONObject("expose:expose").getJSONObject("realEstate").getJSONObject("titlePicture").getJSONObject("urls")
                //                                .getJSONArray("url").getJSONObject(1);
                objAllPictures = outObj.getJSONObject("expose:expose").getJSONObject("realEstate")
                        .getJSONObject("attachments").getJSONArray("attachment");
                objAdPicture = outObj.getJSONObject("expose:expose").getJSONObject("realEstate")
                        .getJSONObject("titlePicture").getJSONObject("urls").getJSONArray("url")
                        .getJSONObject(4);
                objAddress = outObj.getJSONObject("expose:expose").getJSONObject("realEstate")
                        .getJSONObject("address");

                objPricem2 = outObj.getJSONObject("expose:expose").getJSONObject("realEstate").get("price");
                objPricem2Json = parser.parse(objPricem2.toString()).getAsJsonObject();

                obj.put("price", objPrice);
                obj.put("allpictures", objAllPictures);
                obj.put("adpicture", objAdPicture);
                obj.put("address", objAddress);
                obj.put("livingspace",
                        (int) Math.round((Double.parseDouble(objPriceJson.get("value").getAsString())
                                / Double.parseDouble(objPricem2Json.get("value").getAsString()))));

                return obj.toString(); //obj
            } catch (JSONException je) {
                je.printStackTrace();
                return "{\"error\":2}";
            }
        case 201:
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            br.close();

            try {
                JSONObject outObj = XML.toJSONObject(sb.toString());
                return outObj.toString();
            } catch (JSONException je) {
                je.printStackTrace();
                return "{\"error\":2}";

            }
        }

    } catch (Exception e) {
        System.out.println("-------REMOVE OBJECT------");

        e.printStackTrace();
        return "{\"error\":1}";

    }

    return "{\"error\":1}";
}

From source file:com.adssets.api.Scout24.java

@Override
public String getLoans(String postalcode, String suburb) {
    try {//from   w  w w  .  j av a2 s . com
        // Make an API call... it is required to sign each request (see below)  
        Boolean getGeoCode = false;
        URL url;
        if (postalcode != null) {
            url = new URL(
                    "http://rest.immobilienscout24.de/restapi/api/financing/construction/v2/offer?postalcode="
                            + postalcode);
        } else if (suburb != null) {
            getGeoCode = true;
            suburb = suburb.replace("_", "*");
            url = new URL("https://rest.immobilienscout24.de/restapi/api/search/v1.0/region?q=" + suburb);
        } else {
            url = new URL("http://rest.immobilienscout24.de/restapi/api/financing/construction/v2/offer");
        }

        HttpURLConnection requestUrl = null;
        requestUrl = (HttpURLConnection) url.openConnection();
        consumer.sign(requestUrl);
        requestUrl.connect();

        BufferedReader br = new BufferedReader(new InputStreamReader(requestUrl.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;

        switch (requestUrl.getResponseCode()) {
        case 200:
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            br.close();

            try {
                JsonParser parser = new JsonParser();

                JsonObject outObj = parser.parse(sb.toString()).getAsJsonObject();
                //If a suburb is sent, get the geocode for that suburb
                if (getGeoCode) {
                    System.out.println("GETGEOCODE");
                    //Get geoCodeId
                    System.out.println(outObj.toString());
                    String geoCodeId = outObj.get("region.regions").getAsJsonArray().get(0).getAsJsonObject()
                            .get("region").getAsJsonArray().get(0).getAsJsonObject().get("geoCodeId")
                            .getAsString();

                    System.out.println(geoCodeId);
                    //1276003001003  1276003001 
                    url = new URL(
                            "http://rest.immobilienscout24.de/restapi/api/financing/construction/v2/offer?geocode="
                                    + geoCodeId);
                    requestUrl = null;
                    requestUrl = (HttpURLConnection) url.openConnection();
                    consumer.sign(requestUrl);
                    requestUrl.connect();
                    br = new BufferedReader(new InputStreamReader(requestUrl.getInputStream()));
                    sb = new StringBuilder();
                    while ((line = br.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    outObj = parser.parse(sb.toString()).getAsJsonObject();
                    return sortData(outObj);

                } else {

                    return sortData(outObj);
                }

            } catch (JSONException je) {
                je.printStackTrace();
                return "{\"error\":2}";
            }
        case 201:
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            br.close();

            try {
                JSONObject outObj = XML.toJSONObject(sb.toString());
                return outObj.toString();
            } catch (JSONException je) {
                je.printStackTrace();
                return "{\"error\":2}";

            }
        }

    } catch (Exception e) {

        e.printStackTrace();

    }

    return "{\"error\":1}";
}

From source file:com.adssets.ejb.DataAccess.java

@Override
public String createMarket(String obj) {
    JsonObject jsonObject = (new JsonParser()).parse(obj).getAsJsonObject();
    Market market = new Market();
    market.setName(jsonObject.get("name").getAsString());
    market.setDescription(jsonObject.get("description").getAsString());

    marketFacade.create(market);//from w w w .  j a  v  a2s.  c om

    JsonArray jsonArray = new JsonArray();
    JsonObject jsonObj = new JsonObject();
    jsonObj.addProperty("id", market.getId());
    jsonObj.addProperty("name", market.getName());
    jsonObj.addProperty("description", market.getDescription());
    jsonArray.add(jsonObj);
    return jsonArray.toString();
}

From source file:com.adssets.ejb.DataAccess.java

@Override
public String createFeed(String obj) {
    JsonObject jsonObject = (new JsonParser()).parse(obj).getAsJsonObject();

    Market marketId = marketFacade.find(jsonObject.get("marketId").getAsInt());

    //        Feed feedCheck = feedFacade.find(marketId);
    List<Feed> feeds = em.createNamedQuery("Feed.findByMarketId").setParameter("marketId", marketId)
            .getResultList();//from  www.  ja  va 2 s. c o m
    Integer feedCheck = null;

    if (feeds.size() > 0) {
        feedCheck = feeds.get(0).getId();
    }

    Feed feed = new Feed();
    feed.setIdmarket(marketId);
    feed.setJson(jsonObject.get("json").getAsJsonArray().toString());

    JsonArray jsonArray = new JsonArray();
    JsonObject jsonObj = new JsonObject();

    if (feedCheck == null) {
        feedFacade.create(feed);
        jsonObj.addProperty("id", feed.getId());
        jsonObj.addProperty("marketId", feed.getIdmarket().getId());
        jsonObj.addProperty("json", feed.getJson());
        jsonArray.add(jsonObj);
        return jsonArray.toString();
    } else {
        feed.setId(feedCheck);
        feedFacade.edit(feed);
        jsonObj.addProperty("id", feed.getId());
        jsonObj.addProperty("marketId", feed.getIdmarket().getId());
        jsonObj.addProperty("json", feed.getJson());
        jsonArray.add(jsonObj);
        return jsonArray.toString();
    }

}

From source file:com.adssets.ejb.DataAccess.java

@Override
public String buildFeedForMarket(String marketId, String lazyLoad) {
    JsonArray jsonArray = new JsonArray();
    JsonParser parser = new JsonParser();

    //        Feed feed = feedFacade.find(marketId);
    Market market = marketFacade.find(Integer.valueOf(marketId));

    List<Feed> feeds = em.createNamedQuery("Feed.findByMarketId").setParameter("marketId", market)
            .getResultList();//from w  ww . j  a v a 2 s  . c  o  m
    if (feeds.size() > 0) {
        for (Feed feed : feeds) {
            JsonObject obj = new JsonObject();
            obj.addProperty("id", feed.getId());
            obj.addProperty("marketId", feed.getIdmarket().getId());
            obj.addProperty("json", feed.getJson());
            jsonArray.add(obj);
        }

        JsonObject obj = jsonArray.get(0).getAsJsonObject();
        String objArray = obj.get("json").getAsString();

        JsonArray objArrayParsed = parser.parse(objArray).getAsJsonArray();
        JsonArray objData = new JsonArray();

        for (JsonElement objId : objArrayParsed) {
            JsonObject objElmParsed = parser.parse(objId.toString()).getAsJsonObject();
            System.out.println(objElmParsed);
            //            try{
            //            isInteger(objId.getAsString());
            String value = objElmParsed.get("type").getAsString();
            System.out.println(value);
            //CHANGE ADPICTURE TO THE PICTURE STORED IN THE DATABASE
            if (value.equals("object")) {
                String result = scout24.getApartments(objElmParsed.get("objectid").getAsString());
                if (!result.equals("{\"error\":1}")) {
                    JsonObject resultObj = parser.parse(result).getAsJsonObject();
                    String link = "{\"link\": \"https://www.immobilienscout24.de/expose/"
                            + objElmParsed.get("objectid").getAsInt() + "?referrer=\"}";
                    JsonObject clickLink = parser.parse(link).getAsJsonObject();
                    resultObj.add("clickLink", clickLink);
                    resultObj.add("objectId", objElmParsed.get("objectid"));
                    resultObj.add("marketId", parser.parse(marketId));
                    // Use the selected image as ad image
                    JsonObject objHref = new JsonObject();
                    objHref.add("href", objElmParsed.get("url"));
                    resultObj.add("adpicture", objHref);
                    //If lazyLoad = yes dont return "allpictures" LazyLoad=yes is the parameter the ad will send so it does not get unneccesary data
                    if (lazyLoad.equals("yes")) {
                        resultObj.remove("allpictures");
                    }

                    objData.add(resultObj);
                }

            } else {
                objData.add(objId);
            }
            //            }catch(UnsupportedOperationException ex){
            //            objData.add(objId);
            //            }

        }
        return objData.toString();
    } else {
        return new JsonArray().toString();
    }

}

From source file:com.adssets.servlet.MarketServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//  ww w.  j  ava  2s . com
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setHeader("Access-Control-Allow-Origin", "*");
    ;
    try (PrintWriter out = response.getWriter()) {
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null)
                sb.append(line);
        } catch (Exception e) {
            System.out.println(
                    "com.adssets.servlet.MarketServlet.processRequestPost()" + " Could not read POST body");
        }

        JsonObject jsonObject = (new JsonParser()).parse(sb.toString()).getAsJsonObject();

        if (jsonObject.has("name") && jsonObject.has("description")) {
            String res = data.createMarket(jsonObject.toString());
            out.println(res);
        } else {
            System.out.println(
                    "com.adssets.servlet.MarketServlet.processRequestPost()" + " Missing fields in body");

        }

    }

}

From source file:com.adssets.servlet.ObjectServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from ww  w  . j a  v  a2 s .  c  om*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setHeader("Access-Control-Allow-Origin", "*");
    try (PrintWriter out = response.getWriter()) {
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null)
                sb.append(line);
        } catch (Exception e) {
            System.out.println(
                    "com.adssets.servlet.ObjectServlet.processRequestPost()" + " Could not read POST body");
        }

        JsonObject jsonObject = (new JsonParser()).parse(sb.toString()).getAsJsonObject();

        if (jsonObject.has("marketId") && jsonObject.has("json")) {
            System.out.println(jsonObject.toString());
            String res = data.createFeed(jsonObject.toString());
            out.println(res);
        } else {
            System.out.println(
                    "com.adssets.servlet.ObjectServlet.processRequestPost()" + " Missing fields in body");

        }

    }
}