Example usage for com.google.gson JsonElement isJsonPrimitive

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

Introduction

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

Prototype

public boolean isJsonPrimitive() 

Source Link

Document

provides check for verifying if this element is a primitive or not.

Usage

From source file:org.cvasilak.jboss.mobile.admin.net.UploadToJBossServerTask.java

License:Open Source License

@Override
protected void onPostExecute(JsonElement reply) {
    super.onPostExecute(reply);

    progressDialog.dismiss();//from ww  w  .ja va2  s  .c  om

    isTaskFinished = true;

    if (callback == null)
        return;

    if (!reply.isJsonObject())
        callback.onFailure(new RuntimeException("Invalid Response from server!"));

    JsonObject jsonObj = (JsonObject) reply;

    if (!jsonObj.has("outcome"))
        callback.onFailure(new RuntimeException("Invalid Response from server!"));
    else {
        String outcome = jsonObj.get("outcome").getAsString();

        if (outcome.equals("success")) {
            callback.onSuccess(jsonObj.get("result"));
        } else {
            JsonElement elem = jsonObj.get("failure-description");

            if (elem.isJsonPrimitive()) {
                callback.onFailure(new RuntimeException(elem.getAsString()));
            } else if (elem.isJsonObject())
                callback.onFailure(new RuntimeException(
                        elem.getAsJsonObject().get("domain-failure-description").getAsString()));
        }
    }

}

From source file:org.cvasilak.jboss.mobile.app.net.TalkToJBossServerTask.java

License:Apache License

@Override
protected void onPostExecute(JsonElement reply) {
    super.onPostExecute(reply);

    if (callback == null)
        return;/*from w  w w . j  ava  2  s .c  om*/

    if (this.exception != null) {
        callback.onFailure(this.exception);
        return;
    }

    if (reply == null) {
        callback.onFailure(new RuntimeException(context.getString(R.string.empty_response)));
        return;
    }

    if (!reply.isJsonObject()) {
        callback.onFailure(new RuntimeException(context.getString(R.string.invalid_response)));
        return;
    }

    // return the full response if the shouldProcessRequest flag is not set
    if (!shouldProcessRequest) {
        callback.onSuccess(reply);
        return;
    }

    JsonObject jsonObj = (JsonObject) reply;

    if (!jsonObj.has("outcome"))
        callback.onFailure(new RuntimeException(context.getString(R.string.invalid_response)));
    else {
        String outcome = jsonObj.get("outcome").getAsString();

        if (outcome.equals("success")) {
            callback.onSuccess(jsonObj.get("result"));
        } else {
            JsonElement elem = jsonObj.get("failure-description");

            if (elem.isJsonPrimitive()) {
                callback.onFailure(new RuntimeException(elem.getAsString()));
            } else if (elem.isJsonObject())
                callback.onFailure(new RuntimeException(
                        elem.getAsJsonObject().get("domain-failure-description").toString()));
        }
    }
}

From source file:org.cvasilak.jboss.mobile.app.service.UploadToJBossServerService.java

License:Apache License

@Override
protected void onHandleIntent(Intent intent) {
    // initialize

    // extract details
    Server server = intent.getParcelableExtra("server");
    String directory = intent.getStringExtra("directory");
    String filename = intent.getStringExtra("filename");

    // get the json parser from the application
    JsonParser jsonParser = new JsonParser();

    // start the ball rolling...
    final NotificationManager mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

    builder.setTicker(String.format(getString(R.string.notif_ticker), filename))
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_stat_notif_large))
            .setSmallIcon(R.drawable.ic_stat_notif_small)
            .setContentTitle(String.format(getString(R.string.notif_title), filename))
            .setContentText(getString(R.string.notif_content_init))
            // to avoid NPE on android 2.x where content intent is required
            // set an empty content intent
            .setContentIntent(PendingIntent.getActivity(this, 0, new Intent(), 0)).setOngoing(true);

    // notify user that upload is starting
    mgr.notify(NOTIFICATION_ID, builder.build());

    // reset ticker for any subsequent notifications
    builder.setTicker(null);/*from  ww  w . java2s .  c o  m*/

    AbstractHttpClient client = CustomHTTPClient.getHttpClient();

    // enable digest authentication
    if (server.getUsername() != null && !server.getUsername().equals("")) {
        Credentials credentials = new UsernamePasswordCredentials(server.getUsername(), server.getPassword());

        client.getCredentialsProvider().setCredentials(
                new AuthScope(server.getHostname(), server.getPort(), AuthScope.ANY_REALM), credentials);
    }

    final File file = new File(directory, filename);
    final long length = file.length();

    try {
        CustomMultiPartEntity multipart = new CustomMultiPartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,
                new CustomMultiPartEntity.ProgressListener() {
                    @Override
                    public void transferred(long num) {
                        // calculate percentage

                        //System.out.println("transferred: " + num);

                        int progress = (int) ((num * 100) / length);

                        builder.setContentText(String.format(getString(R.string.notif_content), progress));

                        mgr.notify(NOTIFICATION_ID, builder.build());
                    }
                });

        multipart.addPart(file.getName(), new FileBody(file));

        HttpPost httpRequest = new HttpPost(server.getHostPort() + "/management/add-content");
        httpRequest.setEntity(multipart);

        HttpResponse serverResponse = client.execute(httpRequest);

        BasicResponseHandler handler = new BasicResponseHandler();
        JsonObject reply = jsonParser.parse(handler.handleResponse(serverResponse)).getAsJsonObject();

        if (!reply.has("outcome")) {
            throw new RuntimeException(getString(R.string.invalid_response));
        } else {
            // remove the 'upload in-progress' notification
            mgr.cancel(NOTIFICATION_ID);

            String outcome = reply.get("outcome").getAsString();

            if (outcome.equals("success")) {

                String BYTES_VALUE = reply.get("result").getAsJsonObject().get("BYTES_VALUE").getAsString();

                Intent resultIntent = new Intent(this, UploadCompletedActivity.class);
                // populate it
                resultIntent.putExtra("server", server);
                resultIntent.putExtra("BYTES_VALUE", BYTES_VALUE);
                resultIntent.putExtra("filename", filename);
                resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

                // the notification id for the 'completed upload' notification
                // each completed upload will have a different id
                int notifCompletedID = (int) System.currentTimeMillis();

                builder.setContentTitle(getString(R.string.notif_title_uploaded))
                        .setContentText(String.format(getString(R.string.notif_content_uploaded), filename))
                        .setContentIntent(
                                // we set the (2nd param request code to completedID)
                                // see http://tinyurl.com/kkcedju
                                PendingIntent.getActivity(this, notifCompletedID, resultIntent,
                                        PendingIntent.FLAG_UPDATE_CURRENT))
                        .setAutoCancel(true).setOngoing(false);

                mgr.notify(notifCompletedID, builder.build());

            } else {
                JsonElement elem = reply.get("failure-description");

                if (elem.isJsonPrimitive()) {
                    throw new RuntimeException(elem.getAsString());
                } else if (elem.isJsonObject())
                    throw new RuntimeException(
                            elem.getAsJsonObject().get("domain-failure-description").getAsString());
            }
        }

    } catch (Exception e) {
        builder.setContentText(e.getMessage()).setAutoCancel(true).setOngoing(false);

        mgr.notify(NOTIFICATION_ID, builder.build());
    }
}

From source file:org.dashbuilder.dataprovider.backend.elasticsearch.rest.client.impl.jest.ElasticSearchJestClient.java

License:Apache License

/**
 * Parses a given value (for a given column type) returned by response JSON query body from EL server.
 *
 * @param column       The data column definition.
 * @param valueElement The value element from JSON query response to format.
 * @return The formatted value for the given column type.
 *//* w ww  .j  a  v a2  s .c o  m*/
public static Object parseValue(ElasticSearchDataSetDef definition, ElasticSearchDataSetMetadata metadata,
        DataColumn column, JsonElement valueElement) {
    if (column == null || valueElement == null || valueElement.isJsonNull())
        return null;
    if (!valueElement.isJsonPrimitive())
        throw new RuntimeException("Not expected JsonElement type to parse from query response.");

    JsonPrimitive valuePrimitive = valueElement.getAsJsonPrimitive();

    ColumnType columnType = column.getColumnType();

    if (ColumnType.NUMBER.equals(columnType)) {

        return valueElement.getAsDouble();

    } else if (ColumnType.DATE.equals(columnType)) {

        // We can expect two return core types from EL server when handling dates:
        // 1.- String type, using the field pattern defined in the index' mappings, when it's result of a query without aggregations.
        // 2.- Numeric type, when it's result from a scalar function or a value pickup.

        if (valuePrimitive.isString()) {

            DateTimeFormatter formatter = null;
            String datePattern = metadata.getFieldPattern(column.getId());
            if (datePattern == null || datePattern.trim().length() == 0) {
                // If no custom pattern for date field, use the default by EL -> org.joda.time.format.ISODateTimeFormat#dateOptionalTimeParser
                formatter = ElasticSearchDataSetProvider.EL_DEFAULT_DATETIME_FORMATTER;
            } else {
                // Obtain the date value by parsing using the EL pattern specified for this field.
                formatter = DateTimeFormat.forPattern(datePattern);
            }

            DateTime dateTime = formatter.parseDateTime(valuePrimitive.getAsString());
            return dateTime.toDate();
        }

        if (valuePrimitive.isNumber()) {

            return new Date(valuePrimitive.getAsLong());

        }

        throw new UnsupportedOperationException(
                "Value core type not supported. Expecting string or number when using date core field types.");

    }

    // LABEL, TEXT or grouped DATE column types.
    String valueAsString = valueElement.getAsString();
    ColumnGroup columnGroup = column.getColumnGroup();

    // For FIXED date values, remove the unnecessary "0" at first character. (eg: replace month "01" to "1")
    if (columnGroup != null && GroupStrategy.FIXED.equals(columnGroup.getStrategy())
            && valueAsString.startsWith("0"))
        return valueAsString.substring(1);

    return valueAsString;
}

From source file:org.dashbuilder.dataprovider.backend.elasticsearch.rest.impl.jest.ElasticSearchJestClient.java

License:Apache License

/**
 * Parses a given value (for a given column type) returned by response JSON query body from EL server.
 *
 * @param column       The data column definition.
 * @param valueElement The value element from JSON query response to format.
 * @return The object value for the given column type.
 *//*from   www  . j a  va2 s.  c o  m*/
public Object parseValue(DataSetMetadata metadata, DataColumn column, JsonElement valueElement)
        throws ParseException {
    if (column == null || valueElement == null || valueElement.isJsonNull())
        return null;
    if (!valueElement.isJsonPrimitive())
        throw new RuntimeException("Not expected JsonElement type to parse from query response.");

    ElasticSearchDataSetDef def = (ElasticSearchDataSetDef) metadata.getDefinition();
    JsonPrimitive valuePrimitive = valueElement.getAsJsonPrimitive();
    ColumnType columnType = column.getColumnType();

    if (ColumnType.TEXT.equals(columnType)) {
        return typeMapper.parseText(def, column.getId(), valueElement.getAsString());
    } else if (ColumnType.LABEL.equals(columnType)) {
        boolean isColumnGroup = column.getColumnGroup() != null
                && column.getColumnGroup().getStrategy().equals(GroupStrategy.FIXED);
        return typeMapper.parseLabel(def, column.getId(), valueElement.getAsString(), isColumnGroup);

    } else if (ColumnType.NUMBER.equals(columnType)) {
        return typeMapper.parseNumeric(def, column.getId(), valueElement.getAsString());

    } else if (ColumnType.DATE.equals(columnType)) {

        // We can expect two return core types from EL server when handling dates:
        // 1.- String type, using the field pattern defined in the index' mappings, when it's result of a query without aggregations.
        // 2.- Numeric type, when it's result from a scalar function or a value pickup.

        if (valuePrimitive.isString()) {
            return typeMapper.parseDate(def, column.getId(), valuePrimitive.getAsString());
        }

        if (valuePrimitive.isNumber()) {
            return typeMapper.parseDate(def, column.getId(), valuePrimitive.getAsLong());
        }

    }

    throw new UnsupportedOperationException("Cannot parse value for column with id [" + column.getId()
            + "] (Data Set UUID [" + def.getUUID()
            + "]). Value core type not supported. Expecting string or number or date core field types.");

}

From source file:org.debux.webmotion.server.call.ClientSession.java

License:Open Source License

/**
 * Return only JsonElement use getAttribute and getAttributes with class as 
 * parameter to get a value.//  w  ww.  j a  v a  2s  .c  om
 */
@Override
public Object getAttribute(String name) {
    JsonElement value = attributes.get(name);
    if (value == null) {
        return value;

    } else if (value.isJsonPrimitive()) {
        JsonPrimitive primitive = value.getAsJsonPrimitive();
        if (primitive.isString()) {
            return primitive.getAsString();

        } else if (primitive.isBoolean()) {
            return primitive.getAsBoolean();

        } else if (primitive.isNumber()) {
            return primitive.getAsDouble();
        }

    } else if (value.isJsonArray()) {
        return value.getAsJsonArray();

    } else if (value.isJsonObject()) {
        return value.getAsJsonObject();

    } else if (value.isJsonNull()) {
        return value.getAsJsonNull();
    }
    return value;
}

From source file:org.devnexus.aerogear.ShadowStore.java

License:Apache License

private void saveElement(JsonObject serialized, String path, Serializable id) {
    String sql = String.format(
            "insert into shadow_%s_property (PROPERTY_NAME, PROPERTY_VALUE, PARENT_ID) values (?,?,?)",
            className);/*from  w  ww .ja  v a 2s  .  c  om*/
    Set<Map.Entry<String, JsonElement>> members = serialized.entrySet();
    String pathVar = path.isEmpty() ? "" : ".";
    for (Map.Entry<String, JsonElement> member : members) {
        JsonElement jsonValue = member.getValue();
        String propertyName = member.getKey();
        if (jsonValue.isJsonObject()) {
            saveElement((JsonObject) jsonValue, path + pathVar + propertyName, id);
        } else if (jsonValue.isJsonArray()) {
            JsonArray jsonArray = jsonValue.getAsJsonArray();
            for (int index = 0; index < jsonArray.size(); index++) {
                JsonElement arrayElement = jsonArray.get(index);
                if (arrayElement.isJsonPrimitive()) {
                    JsonPrimitive primitive = arrayElement.getAsJsonPrimitive();
                    if (primitive.isBoolean()) {
                        String value = primitive.getAsBoolean() ? "true" : "false";
                        getDatabase().execSQL(sql, new Object[] {
                                path + pathVar + propertyName + String.format("[%d]", index), value, id });
                    } else if (primitive.isNumber()) {
                        Number value = primitive.getAsNumber();
                        getDatabase().execSQL(sql, new Object[] {
                                path + pathVar + propertyName + String.format("[%d]", index), value, id });
                    } else if (primitive.isString()) {
                        String value = primitive.getAsString();
                        getDatabase().execSQL(sql, new Object[] {
                                path + pathVar + propertyName + String.format("[%d]", index), value, id });
                    } else {
                        throw new IllegalArgumentException(
                                arrayElement + " isn't a number, boolean, or string");
                    }

                } else {
                    saveElement(arrayElement.getAsJsonObject(),
                            path + pathVar + propertyName + String.format("[%d]", index), id);
                }

            }
        } else {
            if (jsonValue.isJsonPrimitive()) {
                JsonPrimitive primitive = jsonValue.getAsJsonPrimitive();
                if (primitive.isBoolean()) {
                    String value = primitive.getAsBoolean() ? "true" : "false";
                    getDatabase().execSQL(sql, new Object[] { path + pathVar + propertyName, value, id });
                } else if (primitive.isNumber()) {
                    Number value = primitive.getAsNumber();
                    getDatabase().execSQL(sql, new Object[] { path + pathVar + propertyName, value, id });
                } else if (primitive.isString()) {
                    String value = primitive.getAsString();
                    getDatabase().execSQL(sql, new Object[] { path + pathVar + propertyName, value, id });
                } else {
                    throw new IllegalArgumentException(jsonValue + " isn't a number, boolean, or string");
                }

            } else {
                throw new IllegalArgumentException(jsonValue + " isn't a JsonPrimitive");
            }

        }
    }
}

From source file:org.devnexus.aerogear.ShadowStore.java

License:Apache License

private void buildKeyValuePairs(JsonObject where, List<Pair<String, String>> keyValues, String parentPath) {
    Set<Map.Entry<String, JsonElement>> keys = where.entrySet();
    String pathVar = parentPath.isEmpty() ? "" : ".";//Set a dot if parent path is not empty
    for (Map.Entry<String, JsonElement> entry : keys) {
        String key = entry.getKey();
        String path = parentPath + pathVar + key;
        JsonElement jsonValue = entry.getValue();
        if (jsonValue.isJsonObject()) {
            buildKeyValuePairs((JsonObject) jsonValue, keyValues, path);
        } else {//from   ww w . ja  v a 2s  .  co  m
            if (jsonValue.isJsonPrimitive()) {
                JsonPrimitive primitive = jsonValue.getAsJsonPrimitive();
                if (primitive.isBoolean()) {
                    String value = primitive.getAsBoolean() ? "true" : "false";
                    keyValues.add(new Pair<String, String>(path, value));
                } else if (primitive.isNumber()) {
                    Number value = primitive.getAsNumber();
                    keyValues.add(new Pair<String, String>(path, value.toString()));
                } else if (primitive.isString()) {
                    String value = primitive.getAsString();
                    keyValues.add(new Pair<String, String>(path, value));
                } else {
                    throw new IllegalArgumentException(jsonValue + " isn't a number, boolean, or string");
                }

            } else {
                throw new IllegalArgumentException(jsonValue + " isn't a JsonPrimitive");
            }

        }
    }
}

From source file:org.eclim.Eclim.java

License:Open Source License

public static Object toType(JsonElement json) {
    // null/*from   w w w .j av  a 2s .c om*/
    if (json.isJsonNull()) {
        return null;

        // int, double, boolean, String
    } else if (json.isJsonPrimitive()) {
        JsonPrimitive prim = json.getAsJsonPrimitive();
        if (prim.isBoolean()) {
            return prim.getAsBoolean();
        } else if (prim.isString()) {
            return prim.getAsString();
        } else if (prim.isNumber()) {
            if (prim.getAsString().indexOf('.') != -1) {
                return prim.getAsDouble();
            }
            return prim.getAsInt();
        }

        // List
    } else if (json.isJsonArray()) {
        ArrayList<Object> type = new ArrayList<Object>();
        for (JsonElement element : json.getAsJsonArray()) {
            type.add(toType(element));
        }
        return type;

        // Map
    } else if (json.isJsonObject()) {
        HashMap<String, Object> type = new HashMap<String, Object>();
        for (Map.Entry<String, JsonElement> entry : json.getAsJsonObject().entrySet()) {
            type.put(entry.getKey(), toType(entry.getValue()));
        }
        return type;
    }

    return null;
}

From source file:org.eclipse.cdt.arduino.core.internal.board.ArduinoManager.java

License:Open Source License

public Collection<ArduinoLibrary> getLibraries(IProject project) throws CoreException {
    initInstalledLibraries();//from  w ww. j  a  v  a 2  s  .com
    IEclipsePreferences settings = getSettings(project);
    String librarySetting = settings.get(LIBRARIES, "[]"); //$NON-NLS-1$
    JsonArray libArray = new JsonParser().parse(librarySetting).getAsJsonArray();

    List<ArduinoLibrary> libraries = new ArrayList<>(libArray.size());
    for (JsonElement libElement : libArray) {
        if (libElement.isJsonPrimitive()) {
            String libName = libElement.getAsString();
            ArduinoLibrary lib = installedLibraries.get(libName);
            if (lib != null) {
                libraries.add(lib);
            }
        } else {
            JsonObject libObj = libElement.getAsJsonObject();
            String packageName = libObj.get("package").getAsString(); //$NON-NLS-1$
            String platformName = libObj.get("platform").getAsString(); //$NON-NLS-1$
            String libName = libObj.get("library").getAsString(); //$NON-NLS-1$
            ArduinoPackage pkg = getPackage(packageName);
            if (pkg != null) {
                ArduinoPlatform platform = pkg.getInstalledPlatform(platformName);
                if (platform != null) {
                    ArduinoLibrary lib = platform.getLibrary(libName);
                    if (lib != null) {
                        libraries.add(lib);
                    }
                }
            }
        }
    }
    return libraries;
}