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.asakusafw.yaess.jobqueue.client.HttpJobClient.java

License:Apache License

private <T> T extractContent(Class<T> type, HttpUriRequest request, HttpResponse response) throws IOException {
    assert request != null;
    assert response != null;
    HttpEntity entity = response.getEntity();
    if (entity == null) {
        throw new IOException(MessageFormat.format("Response message was invalid (empty): {0} ({1})",
                request.getURI(), response.getStatusLine()));
    }//from www. j  a  v  a 2s.com

    try (Reader reader = new BufferedReader(new InputStreamReader(entity.getContent(), ENCODING));) {
        JsonParser parser = new JsonParser();
        JsonElement element = parser.parse(reader);
        if ((element instanceof JsonObject) == false) {
            throw new IOException(
                    MessageFormat.format("Response message was not a valid json object: {0} ({1})",
                            request.getURI(), response.getStatusLine()));
        }
        if (LOG.isTraceEnabled()) {
            LOG.trace("response: {}", new Object[] { element });
        }
        return GSON_BUILDER.create().fromJson(element, type);
    } catch (RuntimeException e) {
        throw new IOException(MessageFormat.format("Response message was invalid (not JSON): {0} ({1})",
                request.getURI(), response.getStatusLine()), e);
    }
}

From source file:com.auction.servlet.RequestServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   www.  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");
    response.addHeader("Access-Control-Allow-Origin", "*");
    Gson gson = new GsonBuilder().create();

    PrintWriter out = response.getWriter();
    try {
        request.setCharacterEncoding("UTF-8");

        JsonParser parser = new JsonParser();
        //JsonObject jsonObject = (JsonObject)parser.parse(request.getReader());
        JsonElement packetHeaderText = parser.parse(request.getParameter("packetHeader"));
        String packetBody = request.getParameter("packetBody");
        if (packetHeaderText == null) {
            ClientResponse cr = new ClientFailedResponse();
            cr.setMessage(ClientMessages.PACKET_HEADER_MISSING);
            out.println(gson.toJson(cr));
            return;
        }

        /* TODO output your page here. You may use following sample code. */
        IPacketHeader packetHeader = gson.fromJson(packetHeaderText, PacketHeaderImpl.class);

        IPacket packet = new RequestPacketImpl(packetHeader, packetBody, request.getRemoteAddr(),
                request.getRemotePort());
        ClientResponse clientResponse = (ClientResponse) ClientRequestHandler.getInstance()
                .executeRequest(packet);

        if (clientResponse != null) {
            out.println(gson.toJson(clientResponse));
        } else {
            ClientResponse cr = new ClientFailedResponse();
            cr.setMessage(ClientMessages.REQUEST_DID_NOT_PROCESSED_SUCCESSFULLY);
            out.println(gson.toJson(cr));
        }
    } catch (Throwable ex) {
        ex.printStackTrace();
        ClientResponse cr = new ClientFailedResponse();
        cr.setMessage(ClientMessages.REQUEST_DID_NOT_PROCESSED_SUCCESSFULLY);
        out.println(gson.toJson(cr));
    }
}

From source file:com.axlight.gbrain.server.GBrainServiceImpl.java

License:Apache License

public void fetchNeuron() throws IOException {
    URLFetchService ufs = URLFetchServiceFactory.getURLFetchService();
    JsonParser parser = new JsonParser();

    NeuronData[] targets = getTopNeurons();
    for (NeuronData n : targets) {
        String q = URLEncoder.encode(n.getContent(), "UTF-8");
        long parent = n.getId();
        int x = n.getX();
        int y = n.getY();
        int children = n.getChildren();

        HTTPResponse res = ufs/*from  w w  w  . j a  v  a 2 s  . com*/
                .fetch(new URL("http://search.twitter.com/search.json?q=" + q + "&result_type=recent"));
        JsonElement top = parser.parse(new String(res.getContent(), "UTF-8"));
        for (JsonElement ele : top.getAsJsonObject().get("results").getAsJsonArray()) {
            String content = ele.getAsJsonObject().get("text").getAsString();
            if (content.indexOf("http://") == -1) {
                continue;
            }
            if (alreadyExists(content)) {
                continue;
            }
            try {
                double deg = Math.random() * Math.PI * 2;
                int xx = x + (int) (Math.random() * PARAM_NEW_X * Math.cos(deg));
                int yy = y + (int) (Math.random() * PARAM_NEW_Y * Math.sin(deg));
                addNeuron(parent, content, xx, yy);
                children++;
            } catch (IllegalArgumentException e) {
                // ignored
            }
        }
    }
}

From source file:com.azure.webapi.LoginManager.java

License:Open Source License

/**
 * Invokes Windows Azure Mobile Services authentication using the specified
 * token//  www  . j  av a  2s  .  c  o  m
 * 
 * @param token
 *            The token used for authentication
 * @param url
 *            The URL used for the authentication process
 * @param callback
 *            Callback to invoke when the authentication process finishes
 */
private void authenticateWithToken(String token, String url, final UserAuthenticationCallback callback) {
    if (token == null) {
        throw new IllegalArgumentException("token can not be null");
    }

    if (url == null) {
        throw new IllegalArgumentException("url can not be null");
    }

    // Create a request
    final ServiceFilterRequest request = new ServiceFilterRequestImpl(new HttpPost(url));
    request.addHeader(HTTP.CONTENT_TYPE, MobileServiceConnection.JSON_CONTENTTYPE);

    try {
        // Set request's content with the token
        request.setContent(token);
    } catch (Exception e) {
        // this should never happen
    }
    final MobileServiceConnection connection = mClient.createConnection();

    // Create the AsyncTask that will execute the request
    new RequestAsyncTask(request, connection) {
        @Override
        protected void onPostExecute(ServiceFilterResponse response) {
            if (callback != null) {

                if (mTaskException == null && response != null) {
                    MobileServiceUser user = null;
                    try {
                        // Get the user from the response and create a
                        // MobileServiceUser object from the JSON
                        String content = response.getContent();
                        user = createUserFromJSON((JsonObject) new JsonParser().parse((content.trim())));

                    } catch (Exception e) {
                        // Something went wrong, call onCompleted method
                        // with exception
                        callback.onCompleted(null,
                                new MobileServiceException("Error while authenticating user.", e), response);
                        return;
                    }

                    // Call onCompleted method
                    callback.onCompleted(user, null, response);
                } else {
                    // Something went wrong, call onCompleted method with
                    // exception
                    callback.onCompleted(null,
                            new MobileServiceException("Error while authenticating user.", mTaskException),
                            response);
                }
            }
        }
    }.execute();
}

From source file:com.azure.webapi.MobileServiceClient.java

License:Open Source License

/**
 * Invokes a custom API/*from   w w  w . j  a v  a 2s.  c o  m*/
 * 
 * @param apiName
 *            The API name
 * @param body
 *            The json element to send as the request body
 * @param httpMethod
 *            The HTTP Method used to invoke the API
 * @param parameters
 *            The query string parameters sent in the request
 * @param callback
 *            The callback to invoke after the API execution
 */
public void invokeApi(String apiName, JsonElement body, String httpMethod,
        List<Pair<String, String>> parameters, final ApiJsonOperationCallback callback) {

    byte[] content = null;
    if (body != null) {
        try {
            content = body.toString().getBytes(UTF8_ENCODING);
        } catch (UnsupportedEncodingException e) {
            if (callback != null) {
                callback.onCompleted(null, e, null);
            }
            return;
        }
    }

    List<Pair<String, String>> requestHeaders = new ArrayList<Pair<String, String>>();
    if (body != null) {
        requestHeaders
                .add(new Pair<String, String>(HTTP.CONTENT_TYPE, MobileServiceConnection.JSON_CONTENTTYPE));
    }

    invokeApi(apiName, content, httpMethod, requestHeaders, parameters, new ServiceFilterResponseCallback() {

        @Override
        public void onResponse(ServiceFilterResponse response, Exception exception) {
            if (callback != null) {
                if (exception == null) {
                    String content = response.getContent();
                    JsonElement json = new JsonParser().parse(content);

                    callback.onCompleted(json, null, response);
                } else {
                    callback.onCompleted(null, exception, response);
                }
            }
        }
    });
}

From source file:com.azure.webapi.MobileServiceJsonTable.java

License:Open Source License

/**
 * Executes the query against the table/*from ww w.  j a va 2 s  . c om*/
 * 
 * @param request
 *            Request to execute
 * @param callback
 *            Callback to invoke when the operation is completed
 */
private void executeTableOperation(ServiceFilterRequest request, final TableJsonOperationCallback callback) {
    // Create AsyncTask to execute the operation
    new RequestAsyncTask(request, mClient.createConnection()) {
        @Override
        protected void onPostExecute(ServiceFilterResponse result) {
            if (callback != null) {
                JsonObject newEntityJson = null;
                if (mTaskException == null && result != null) {
                    String content = null;
                    content = result.getContent();

                    // put and delete operations are not supposed to return entity for WEBAPI
                    JsonElement element = new JsonParser().parse(content);
                    if (element != null && element != JsonNull.INSTANCE) {
                        newEntityJson = element.getAsJsonObject();
                    }

                    callback.onCompleted(newEntityJson, null, result);

                } else {
                    callback.onCompleted(null, mTaskException, result);
                }
            }
        }
    }.execute();
}

From source file:com.azure.webapi.MobileServiceJsonTable.java

License:Open Source License

/**
 * Retrieves a set of rows from using the specified URL
 * /*from   w  w w .j  a  va  2s .co  m*/
 * @param query
 *            The URL used to retrieve the rows
 * @param callback
 *            Callback to invoke when the operation is completed
 */
private void executeGetRecords(final String url, final TableJsonQueryCallback callback) {
    ServiceFilterRequest request = new ServiceFilterRequestImpl(new HttpGet(url));

    MobileServiceConnection conn = mClient.createConnection();
    // Create AsyncTask to execute the request and parse the results
    new RequestAsyncTask(request, conn) {
        @Override
        protected void onPostExecute(ServiceFilterResponse response) {
            if (callback != null) {
                if (mTaskException == null && response != null) {
                    JsonElement results = null;

                    int count = 0;

                    try {
                        // Parse the results using the given Entity class
                        String content = response.getContent();
                        JsonElement json = new JsonParser().parse(content);

                        if (json.isJsonObject()) {
                            JsonObject jsonObject = json.getAsJsonObject();
                            // If the response has count property, store its
                            // value
                            if (jsonObject.has("results") && jsonObject.has("count")) { // inlinecount
                                // result
                                count = jsonObject.get("count").getAsInt();
                                results = jsonObject.get("results");
                            } else {
                                results = json;
                            }
                        } else {
                            results = json;
                        }
                    } catch (Exception e) {
                        callback.onCompleted(null, 0,
                                new MobileServiceException("Error while retrieving data from response.", e),
                                response);
                        return;
                    }

                    callback.onCompleted(results, count, null, response);

                } else {
                    callback.onCompleted(null, 0, mTaskException, response);
                }
            }
        }
    }.execute();
}

From source file:com.azure.webapi.MobileServiceTableBase.java

License:Open Source License

/**
 * Patches the original entity with the one returned in the response after
 * executing the operation/*from w w  w  .j  av a  2 s .c o m*/
 * 
 * @param originalEntity
 *            The original entity
 * @param newEntity
 *            The entity obtained after executing the operation
 * @return
 */
protected JsonObject patchOriginalEntityWithResponseEntity(JsonObject originalEntity, JsonObject newEntity) {
    // Patch the object to return with the new values
    JsonObject patchedEntityJson = (JsonObject) new JsonParser().parse(originalEntity.toString());

    for (Map.Entry<String, JsonElement> entry : newEntity.entrySet()) {
        patchedEntityJson.add(entry.getKey(), entry.getValue());
    }

    return patchedEntityJson;
}

From source file:com.baidao.realm_gridviewexample.GridViewExampleActivity.java

License:Apache License

private List<City> loadCities() {
    // In this case we're loading from local assets.
    // NOTE: could alternatively easily load from network
    InputStream stream;//ww w  .  j a v  a 2s.  c o  m
    try {
        stream = getAssets().open("cities.json");
    } catch (IOException e) {
        return null;
    }

    Gson gson = new GsonBuilder().create();

    JsonElement json = new JsonParser().parse(new InputStreamReader(stream));
    List<City> cities = gson.fromJson(json, new TypeToken<List<City>>() {
    }.getType());

    // Open a transaction to store items into the realm
    // Use copyToRealm() to convert the objects into proper RealmObjects managed by Realm.
    realm.beginTransaction();
    Collection<City> realmCities = realm.copyToRealm(cities);
    realm.commitTransaction();

    return new ArrayList<City>(realmCities);
}

From source file:com.baidu.cc.configuration.service.impl.VersionServiceImpl.java

License:Apache License

/**
 * ??./*from  w w  w  .  j  a v  a 2s  .com*/
 * 
 * @param file
 *            
 * @param versionId
 *            the version id
 * @throws IOException
 *             ?
 */
@Override
public void importFromFile(File file, Long versionId) throws IOException {
    byte[] byteArray = FileUtils.readFileToByteArray(file);

    Hex encoder = new Hex();
    try {
        byteArray = encoder.decode(byteArray);
    } catch (DecoderException e) {
        throw new IOException(e.getMessage());
    }
    String json = new String(byteArray, SysUtils.UTF_8);

    // parse from gson
    JsonParser jsonParser = new JsonParser();
    JsonElement je = jsonParser.parse(json);

    if (!je.isJsonArray()) {
        throw new RuntimeException("illegal json string. must be json array.");
    }

    JsonArray jsonArray = je.getAsJsonArray();

    int size = jsonArray.size();
    Version version = new Version();
    List<ConfigGroup> groups = new ArrayList<ConfigGroup>();
    ConfigGroup group;
    List<ConfigItem> items;
    ConfigItem item;

    for (int i = 0; i < size; i++) {
        JsonObject jo = jsonArray.get(i).getAsJsonObject();
        group = gson.fromJson(jo, ConfigGroup.class);

        // get sub configuration item
        JsonArray subItemsJson = jo.get(CONFIG_ITEMS_ELE).getAsJsonArray();

        int subSize = subItemsJson.size();
        items = new ArrayList<ConfigItem>();
        for (int j = 0; j < subSize; j++) {
            item = gson.fromJson(subItemsJson.get(j), ConfigItem.class);
            items.add(item);
        }

        group.setConfigItems(items);
        groups.add(group);
    }

    version.setConfigGroups(groups);
    configCopyService.copyConfigItemsFromVersion(version, versionId);
}