Example usage for com.google.gson JsonElement toString

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

Introduction

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

Prototype

@Override
public String toString() 

Source Link

Document

Returns a String representation of this element.

Usage

From source file:org.cloudfoundry.community.servicebroker.vrealize.VraClient.java

License:Open Source License

Map<String, Object> getLinks(JsonElement resources) {
    Map<String, Object> map = new HashMap<String, Object>();
    ReadContext ctx = JsonPath.parse(resources.toString());

    JSONArray o = ctx.read("$.content[*].links[*]");
    Iterator it = o.iterator();/*from  w w  w.  j a  v  a  2s .com*/
    while (it.hasNext()) {
        LinkedHashMap ja = (LinkedHashMap) it.next();
        Object key = ja.get("rel");
        Object val = ja.get("href");

        if (key != null && val != null) {
            map.put(key.toString(), val);
        }

    }
    return map;
}

From source file:org.coding.git.api.CodingNetConnection.java

License:Apache License

/**
 * OpenAPI?//from   w  w  w. java  2s.c  o m
 *
 * @param jsonElement
 */
private void checkCodingNetCode(JsonElement jsonElement) throws IOException {
    int code = jsonElement.getAsJsonObject().get("code").getAsInt();
    System.out.println("Current Code is: " + code + " JsonElement is:" + jsonElement.toString());
    if (code == CodingNetOpenAPICodeMsg.NO_LOGIN.getCode()) {
        CodingNetOpenAPICodeMsg.ICodingNetOpenAPICodeMsg codingNetOpenAPICodeMsg = (CodingNetOpenAPICodeMsg.ICodingNetOpenAPICodeMsg) fromJson(
                jsonElement, CodingNetOpenAPICodeMsg.NO_LOGIN.getClazz());
        throw new CodingNetAuthenticationException(codingNetOpenAPICodeMsg.getMessage());
    } else if (code == CodingNetOpenAPICodeMsg.NO_EXIST_USER.getCode()) {
        CodingNetOpenAPICodeMsg.ICodingNetOpenAPICodeMsg codingNetOpenAPICodeMsg = (CodingNetOpenAPICodeMsg.ICodingNetOpenAPICodeMsg) fromJson(
                jsonElement, CodingNetOpenAPICodeMsg.NO_EXIST_USER.getClazz());
        throw new CodingNetAuthenticationException(codingNetOpenAPICodeMsg.getMessage());
    } else if (code == CodingNetOpenAPICodeMsg.NEED_VERIFICATION_CODE.getCode()) {
        CodingNetOpenAPICodeMsg.ICodingNetOpenAPICodeMsg codingNetOpenAPICodeMsg = (CodingNetOpenAPICodeMsg.ICodingNetOpenAPICodeMsg) fromJson(
                jsonElement, CodingNetOpenAPICodeMsg.NEED_VERIFICATION_CODE.getClazz());
        throw new CodingNetAuthenticationException(codingNetOpenAPICodeMsg.getMessage());
    } else if (code == CodingNetOpenAPICodeMsg.USER_LOCKED.getCode()) {
        CodingNetOpenAPICodeMsg.ICodingNetOpenAPICodeMsg codingNetOpenAPICodeMsg = (CodingNetOpenAPICodeMsg.ICodingNetOpenAPICodeMsg) fromJson(
                jsonElement, CodingNetOpenAPICodeMsg.USER_LOCKED.getClazz());
        throw new CodingNetAuthenticationException(codingNetOpenAPICodeMsg.getMessage());
    } else if (code == CodingNetOpenAPICodeMsg.USER_PASSWORD_NO_CORRECT.getCode()) {
        CodingNetOpenAPICodeMsg.ICodingNetOpenAPICodeMsg codingNetOpenAPICodeMsg = (CodingNetOpenAPICodeMsg.ICodingNetOpenAPICodeMsg) fromJson(
                jsonElement, CodingNetOpenAPICodeMsg.USER_PASSWORD_NO_CORRECT.getClazz());
        throw new CodingNetAuthenticationException(codingNetOpenAPICodeMsg.getMessage());
    } else if (code == CodingNetOpenAPICodeMsg.AUTH_ERROR.getCode()) {
        CodingNetOpenAPICodeMsg.ICodingNetOpenAPICodeMsg codingNetOpenAPICodeMsg = (CodingNetOpenAPICodeMsg.ICodingNetOpenAPICodeMsg) fromJson(
                jsonElement, CodingNetOpenAPICodeMsg.AUTH_ERROR.getClazz());
        throw new CodingNetTwoFactorAuthenticationException(codingNetOpenAPICodeMsg.getMessage());
    } else if (code == CodingNetOpenAPICodeMsg.NEED_TWO_FACTOR_AUTH_CODE.getCode()
            || code == CodingNetOpenAPICodeMsg.TWO_FACTOR_AUTH_CODE_REQUIRED.getCode()) {
        return;
    } else if (code == CodingNetOpenAPICodeMsg.LOGIN_EXPIRED.getCode()) {
        CodingNetOpenAPICodeMsg.ICodingNetOpenAPICodeMsg codingNetOpenAPICodeMsg = (CodingNetOpenAPICodeMsg.ICodingNetOpenAPICodeMsg) fromJson(
                jsonElement, CodingNetOpenAPICodeMsg.LOGIN_EXPIRED.getClazz());
        throw new CodingNetTwoFactorAuthenticationException(codingNetOpenAPICodeMsg.getMessage());
    } else if (code != 0) {
        throw new CodingNetAuthenticationException();
    }
}

From source file:org.commoncrawl.util.Base64.java

License:Apache License

/**
 * Main program. Used for testing./*  w  ww  .ja v  a  2s .c o  m*/
 *
 * Encodes or decodes two files from the command line
 *
 * @param args command arguments
 */
public static void main(String[] args) {

    JsonObject object = new JsonObject();

    object.addProperty("fileId", 1234L);
    object.addProperty("timestamp", 4561234L);

    String encoded = encodeBytes(object.toString().getBytes());
    System.out.println("Encoded:" + encoded);

    byte decoded[] = decode(encoded);

    String decodedStr = new String(decoded);
    JsonParser parser = new JsonParser();
    JsonElement element = parser.parse(decodedStr);
    if (element != null && element.isJsonObject()) {
        System.out.println("Decoded Obj:" + element.toString());
    }

    /*
    if (args.length < 3) {
      usage("Not enough arguments.");
            
    } else {
      String flag = args[0];
      String infile = args[1];
      String outfile = args[2];
      if (flag.equals("-e")) {                          // encode
        encodeFileToFile(infile, outfile);
            
      } else if (flag.equals("-d")) {                   // decode
        decodeFileToFile(infile, outfile);
            
      } else {
        usage("Unknown flag: " + flag);
      }
    }*/
}

From source file:org.couchbase.mock.subdoc.Executor.java

License:Apache License

private void ensureUnique(JsonArray array) throws SubdocException {
    if (!value.isJsonPrimitive() && !value.isJsonNull()) {
        throw new CannotInsertException("Cannot verify uniqueness with non-primitives");
    }/*  ww  w . ja  v  a 2  s  . c o  m*/

    String valueString = value.toString();
    for (int i = 0; i < array.size(); i++) {
        JsonElement e = array.get(i);
        if (!e.isJsonPrimitive()) {
            throw new PathMismatchException("Values in the array are not all primitives");
        }
        if (e.toString().equals(valueString)) {
            throw new PathExistsException();
        }
    }
}

From source file:org.couchpotato.json.deserializer.JsonBooleanDeserializer.java

License:Open Source License

@Override
public JsonBoolean deserialize(JsonElement arg0, Type arg1, JsonDeserializationContext arg2)
        throws JsonParseException {
    try {/* w  w w. ja va  2s.co m*/
        String value = arg0.getAsJsonPrimitive().getAsString();
        if (value.toLowerCase().equals("true")) {
            return new JsonBoolean(true);
        } else if (value.toLowerCase().equals("false")) {
            return new JsonBoolean(false);
        } else {
            return new JsonBoolean(Integer.valueOf(value) != 0);
        }
    } catch (ClassCastException e) {
        throw new JsonParseException("Cannot parse JsonBoolean string '" + arg0.toString() + "'", e);
    } catch (Exception e) {
        throw new JsonParseException("Cannot parse JsonBoolean string '" + arg0.toString() + "'", e);
    }
}

From source file:org.cvasilak.jboss.mobile.app.fragments.AttributeEditorFragment.java

License:Apache License

public void save() {
    ProgressDialogFragment.showDialog(getActivity(), R.string.applyingAction);

    ParametersMap params = ParametersMap.newMap().add("operation", "write-attribute")
            .add("address", (attr.getPath() == null ? Arrays.asList("/") : attr.getPath()))
            .add("name", attr.getName()).add("value", clonedAttr.getValue());

    application.getOperationsManager().genericRequest(params, false, new Callback() {
        @Override//from   ww  w .  j  av  a2 s  . co  m
        public void onSuccess(JsonElement reply) {
            ProgressDialogFragment.dismissDialog(getActivity());

            if (reply.getAsJsonObject().get("outcome").getAsString().equals("success"))
                attr.setValue(clonedAttr.getValue());

            // show the reply from server
            InfoDialogFragment infoDialog = InfoDialogFragment
                    .newInstance(getString(R.string.dialog_server_reply_title), reply.toString());
            infoDialog.show(getActivity().getSupportFragmentManager(), InfoDialogFragment.TAG);
        }

        @Override
        public void onFailure(Exception e) {
            ProgressDialogFragment.dismissDialog(getActivity());
            ErrorDialogFragment.showDialog(getActivity(), e.getMessage());
        }
    });
}

From source file:org.cvasilak.jboss.mobile.app.fragments.OperationExecViewFragment.java

License:Apache License

public void save() {
    ProgressDialogFragment.showDialog(getActivity(), R.string.applyingAction);

    ParametersMap params = ParametersMap.newMap().add("operation", oper.getName());

    for (OperationParameter param : oper.getParameters()) {

        // if generic "add" append the name to the path
        if (param.isAddParameter()) {
            List<String> path = new ArrayList<String>(oper.getPath());
            // remove trailed star
            path.remove(path.size() - 1);

            // don't append 'null' in the path
            if (param.getValue() != null)
                path.add((String) param.getValue());

            params.add("address", path);
            continue;
        }//from  w  w  w .  j a v a2  s.c  o m

        if (param.getValue() != null) {
            if (param.getType() == ManagementModelBase.Type.LIST) {
                // only add the parameter if the list contains items
                if (((List) param.getValue()).size() > 0) {
                    params.add(param.getName(), param.getValue());
                }
            } else {
                params.add(param.getName(), param.getValue());
            }
        }
    }

    // check if generic add operation already added the address
    // if NOT set it
    if (!params.containsKey("address")) {
        params.add("address", oper.getPath() == null ? Arrays.asList("/") : oper.getPath());
    }

    application.getOperationsManager().genericRequest(params, false, new Callback() {
        @Override
        public void onSuccess(JsonElement reply) {
            ProgressDialogFragment.dismissDialog(getActivity());

            InfoDialogFragment infoDialog = InfoDialogFragment
                    .newInstance(getString(R.string.dialog_server_reply_title), reply.toString());
            infoDialog.show(getActivity().getSupportFragmentManager(), InfoDialogFragment.TAG);
        }

        @Override
        public void onFailure(Exception e) {
            ProgressDialogFragment.dismissDialog(getActivity());

            ErrorDialogFragment.showDialog(getActivity(), e.getMessage());
        }
    });
}

From source file:org.cvasilak.jboss.mobile.app.model.ManagementModelBase.java

License:Apache License

public void setValue(JsonElement value) {
    if (value instanceof JsonPrimitive) {
        JsonPrimitive primitive = (JsonPrimitive) value;

        if (primitive.isNumber()) {
            try {
                this.value = NumberFormat.getInstance().parse(primitive.getAsString());
            } catch (ParseException e) {
            }//from  w  w w.j  av  a2s  .  c o  m
        } else if (primitive.isBoolean()) {
            this.value = primitive.getAsBoolean();
        } else if (primitive.isString()) {
            this.value = primitive.getAsString();
        }

    } else if (value instanceof JsonNull) {
        this.value = "undefined";

    } else if (value instanceof JsonArray) {
        List<String> list = new ArrayList<String>();

        Iterator<JsonElement> iterator = value.getAsJsonArray().iterator();

        while (iterator.hasNext()) {
            JsonElement elem = iterator.next();

            if (elem instanceof JsonObject)
                list.add(elem.toString());
            else
                list.add(elem.getAsString());
        }

        this.value = list;

    } else if (value instanceof JsonObject) {
        this.value = value.toString();
    }
}

From source file:org.davidmendoza.fileUpload.web.VideoController.java

License:Open Source License

private String base64EncodePolicy(JsonElement jsonElement) throws UnsupportedEncodingException {
    String policyJsonStr = jsonElement.toString();
    String base64Encoded = DatatypeConverter.printBase64Binary(policyJsonStr.getBytes("UTF-8"))
            .replaceAll("\n", "").replaceAll("\r", "");

    return base64Encoded;
}

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

License:Apache License

@Override
public List<T> onReadWithFilter(ReadFilter filter, Pipe<T> requestingPipe) {
    List<T> result;/*from   w w  w . j  a va  2s  . c  o  m*/
    HttpProvider httpProvider;

    if (filter == null) {
        filter = new ReadFilter();
    }

    if (filter.getLinkUri() == null) {
        httpProvider = getHttpProvider(parameterProvider.getParameters(filter));
    } else {
        httpProvider = getHttpProvider(filter.getLinkUri());
    }

    HeaderAndBody httpResponse;

    try {
        httpResponse = httpProvider.get();
    } catch (HttpException exception) {
        if (RETRY_CODES.contains(exception.getStatusCode()) && retryAuth(authModule)) {
            httpResponse = httpProvider.get();
        } else {
            throw exception;
        }
    }
    byte[] responseBody = httpResponse.getBody();
    String responseAsString = new String(responseBody, encoding);
    JsonParser parser = new JsonParser();
    JsonElement httpJsonResult = parser.parse(responseAsString);
    httpJsonResult = getResultElement(httpJsonResult, dataRoot);
    if (httpJsonResult.isJsonArray()) {
        T[] resultArray = responseParser.handleArrayResponse(httpJsonResult.toString(), arrayKlass);
        result = Arrays.asList(resultArray);
        if (pageConfig != null) {
            result = computePagedList(result, httpResponse, filter.getWhere(), requestingPipe);
        }
    } else {
        T resultObject = responseParser.handleResponse(httpJsonResult.toString(), klass);
        List<T> resultList = new ArrayList<T>(1);
        resultList.add(resultObject);
        result = resultList;
        if (pageConfig != null) {
            result = computePagedList(result, httpResponse, filter.getWhere(), requestingPipe);
        }
    }
    return result;

}