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:cloud.google.oauth2.MyWayAuthentication.java

License:Apache License

/**
 * Just return access token/*from   ww w  . j  av  a2  s  .  co m*/
 * */
@Override
public String getAccessToken() {
    try {
        long iat = (System.currentTimeMillis() / 1000) - 60;
        long exp = iat + 3600;
        String urlParameters = "grant_type=" + GCDStatic.getGrant() + "&assertion=" + getAssertion(exp, iat);

        String result = ConnectionService.connect(GCDStatic.getAud()).body(urlParameters)
                .header("Content-Type", "application/x-www-form-urlencoded").post();
        JsonElement jelement = new JsonParser().parse(result);
        JsonObject jobject = jelement.getAsJsonObject();
        jelement = jobject.get("access_token");
        return jelement != null ? jelement.getAsString() : "";
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

From source file:cloudlens.cli.Whisk.java

License:Apache License

public static JsonObject main(JsonObject args) {
    final JsonObject res = new JsonObject();

    try {//w ww . jav a  2s  .  c o m
        final CL cl = new CL(System.out, System.err, false, true);

        String script = "";
        String logURI = "";

        if (args.has("script")) {
            script = args.getAsJsonPrimitive("script").getAsString();
        }
        if (args.has("log")) {
            logURI = args.getAsJsonPrimitive("log").getAsString();
        }

        try {
            final InputStream inputStream = FileReader.fetchFile(logURI);
            cl.source(inputStream);
            final List<ASTElement> top = ASTBuilder.parse(script);
            cl.launch(top);

            final JsonElement jelement = new JsonParser().parse(cl.cl.get("result").asString());
            return jelement.getAsJsonObject();

        } catch (final CLException e) {
            res.addProperty("error", e.getMessage());
            System.err.println(e.getMessage());
        } finally {
            cl.outWriter.flush();
            cl.errWriter.flush();
        }

    } catch (final Exception e) {
        res.addProperty("error", e.getMessage());
        System.err.println(e.getMessage());
    }

    return res;
}

From source file:cloudlens.cli.Whisk.java

License:Apache License

public static void main(String[] args) {
    try {/*from   www  .ja va 2s .  c  o  m*/
        final FileInputStream inputStream = new FileInputStream(new File(args[0]));
        final BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        final StringBuilder sb = new StringBuilder();
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }
        rd.close();

        final JsonElement jelement = new JsonParser().parse(sb.toString());

        final JsonObject res = main(jelement.getAsJsonObject());
        System.out.println(res);

    } catch (final FileNotFoundException e) {
        e.printStackTrace();
    } catch (final IOException e) {
        e.printStackTrace();
    }

}

From source file:club.jmint.mifty.service.MiftyService.java

License:Apache License

public String callProxy(String method, String params, boolean isEncrypt) throws TException {
    //parse parameters and verify signature
    CrossLog.logger.debug("callProxy: " + method + "(in: " + params + ")");
    JsonObject ip;//  w  w  w  . j a v  a  2 s.  co m
    try {
        ip = parseInputParams(params, isEncrypt);
    } catch (CrossException ce) {
        return buildOutputByCrossException(ce);
    }

    //extract all parameters
    HashMap<String, String> inputMap = new HashMap<String, String>();
    Iterator<Entry<String, JsonElement>> it = ip.entrySet().iterator();
    Entry<String, JsonElement> en = null;
    String key;
    JsonElement je;
    while (it.hasNext()) {
        en = it.next();
        key = en.getKey();
        je = en.getValue();
        if (je.isJsonArray()) {
            inputMap.put(key, je.getAsJsonArray().toString());
            //System.out.println(je.getAsJsonArray().toString());
        } else if (je.isJsonNull()) {
            inputMap.put(key, je.getAsJsonNull().toString());
            //System.out.println(je.getAsJsonNull().toString());
        } else if (je.isJsonObject()) {
            inputMap.put(key, je.getAsJsonObject().toString());
            //System.out.println(je.getAsJsonObject().toString());
        } else if (je.isJsonPrimitive()) {
            inputMap.put(key, je.getAsJsonPrimitive().getAsString());
            //System.out.println(je.getAsJsonPrimitive().toString());
        } else {
            //unkown type;
        }
    }

    //execute specific method
    Method[] ma = this.getClass().getMethods();
    int idx = 0;
    for (int i = 0; i < ma.length; i++) {
        if (ma[i].getName().equals(method)) {
            idx = i;
            break;
        }
    }
    HashMap<String, String> outputMap = null;
    try {
        Method m = this.getClass().getDeclaredMethod(method, ma[idx].getParameterTypes());
        outputMap = (HashMap<String, String>) m.invoke(this, inputMap);
        CrossLog.logger.debug("callProxy: " + method + "() executed.");
    } catch (NoSuchMethodException nsm) {
        CrossLog.logger.error("callProxy: " + method + "() not found.");
        CrossLog.printStackTrace(nsm);
        return buildOutputError(ErrorCode.CROSSING_ERR_INTERFACE_NOT_FOUND.getCode(),
                ErrorCode.CROSSING_ERR_INTERFACE_NOT_FOUND.getInfo());
    } catch (Exception e) {
        CrossLog.logger.error("callProxy: " + method + "() executed with exception.");
        CrossLog.printStackTrace(e);
        if (e instanceof CrossException) {
            return buildOutputByCrossException((CrossException) e);
        } else {
            return buildOutputError(ErrorCode.COMMON_ERR_UNKOWN.getCode(),
                    ErrorCode.COMMON_ERR_UNKOWN.getInfo());
        }
    }
    //if got error then return immediately
    String ec = outputMap.get("errorCode");
    String ecInfo = outputMap.get("errorInfo");
    if ((ec != null) && (!ec.isEmpty())) {
        return buildOutputError(Integer.parseInt(ec), ecInfo);
    }

    //build response parameters
    JsonObject op = new JsonObject();
    Iterator<Entry<String, String>> ito = outputMap.entrySet().iterator();
    Entry<String, String> eno = null;
    JsonParser jpo = new JsonParser();
    JsonElement jeo = null;
    while (ito.hasNext()) {
        eno = ito.next();
        try {
            jeo = jpo.parse(eno.getValue());
        } catch (JsonSyntaxException e) {
            //            MyLog.logger.error("callProxy: Malformed output parameters["+eno.getKey()+"].");
            //            return buildOutputError(ErrorCode.COMMON_ERR_PARAM_MALFORMED.getCode(), 
            //                  ErrorCode.COMMON_ERR_PARAM_MALFORMED.getInfo());
            //we do assume that it should be a common string
            jeo = new JsonPrimitive(eno.getValue());
        }
        op.add(eno.getKey(), jeo);
    }

    String output = null;
    try {
        output = buildOutputParams(op, isEncrypt);
    } catch (CrossException ce) {
        return buildOutputByCrossException(ce);
    }
    CrossLog.logger.debug("callProxy: " + method + "(out: " + output + ")");
    return output;
}

From source file:cn.com.caronwer.activity.AuthFirstActivity.java

private void getVehicleTypes() {

    JsonObject mJsonObject = new JsonObject();
    Map<String, String> map = EncryptUtil.encryptDES(mJsonObject.toString());

    HttpUtil.doPost(AuthFirstActivity.this, Contants.url_getvehicletypes, "getvehicletypes", map,
            new VolleyInterface(AuthFirstActivity.this, VolleyInterface.mListener,
                    VolleyInterface.mErrorListener) {
                @Override//from   w  ww.jav a2s  .  c  om
                public void onSuccess(JsonElement result) {
                    Gson gson = new Gson();
                    Type listType = new TypeToken<ArrayList<VehicleType>>() {
                    }.getType();
                    final ArrayList<VehicleType> vehicleTypes = gson
                            .fromJson(result.getAsJsonObject().get("VehicleTypeList"), listType);
                    ArrayAdapter<VehicleType> source = new ArrayAdapter<>(AuthFirstActivity.this,
                            android.R.layout.simple_spinner_dropdown_item, vehicleTypes);
                    vehicleType.setAdapter(source);
                    vehicleType.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

                        @Override
                        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                            VehType = vehicleTypes.get(arg2).getTypeCode();
                        }

                        @Override
                        public void onNothingSelected(AdapterView<?> arg0) {

                        }

                    });
                }

                @Override
                public void onError(VolleyError error) {
                }

                @Override
                public void onStateError(int sta, String msg) {
                    if (!TextUtils.isEmpty(msg)) {
                        showShortToastByString(msg);
                    }
                }
            });
}

From source file:co.aurasphere.botmill.fb.internal.util.json.AttachmentDeserializer.java

License:Open Source License

public Attachment deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    Attachment attachment = delegateGson.fromJson(json, Attachment.class);
    AttachmentType type = attachment.getType();
    Class<? extends Payload> payloadClass = null;
    JsonElement payloadJson = json.getAsJsonObject().get("payload");

    switch (type) {
    case AUDIO://  w  w w  .j a  va 2s. c  o m
    case FILE:
    case IMAGE:
    case VIDEO:
        payloadClass = UrlPayload.class;
        break;
    case LOCATION:
        payloadClass = QuickReplyLocationPayload.class;
        break;
    case FALLBACK:
        // In case of Fallback attachment the payload will be null so I do
        // nothing.
        break;
    case TEMPLATE:
        // In case of a template I need to check which one to instantiate.
        String payloadTypeString = payloadJson.getAsJsonObject().get("template_type").getAsString();
        PayloadType templateType = PayloadType.valueOf(payloadTypeString.toUpperCase());

        switch (templateType) {
        case AIRLINE_BOARDINGPASS:
            payloadClass = AirlineBoardingPassTemplatePayload.class;
            break;
        case AIRLINE_CHECKIN:
            payloadClass = AirlineCheckinTemplatePayload.class;
            break;
        case AIRLINE_ITINERARY:
            payloadClass = AirlineItineraryTemplatePayload.class;
            break;
        case AIRLINE_UPDATE:
            payloadClass = AirlineFlightUpdateTemplatePayload.class;
            break;
        case BUTTON:
            payloadClass = ButtonTemplatePayload.class;
            break;
        case GENERIC:
            payloadClass = GenericTemplatePayload.class;
            break;
        case LIST:
            payloadClass = ListTemplatePayload.class;
            break;
        case RECEIPT:
            payloadClass = ReceiptTemplatePayload.class;
            break;
        }
        break;
    }
    Payload payload = context.deserialize(payloadJson, payloadClass);
    attachment.setPayload(payload);
    return attachment;
}

From source file:co.aurasphere.botmill.fb.internal.util.json.ButtonDeserializer.java

License:Open Source License

public Button deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    String buttonTypeString = json.getAsJsonObject().get("type").getAsString();
    ButtonType buttonType = ButtonType.valueOf(buttonTypeString.toUpperCase());
    Class<? extends Button> buttonClass = null;
    switch (buttonType) {
    case ACCOUNT_LINK:
        buttonClass = LoginButton.class;
        break;/* ww  w.  j ava  2  s  .co m*/
    case ACCOUNT_UNLINK:
        buttonClass = LogoutButton.class;
        break;
    case ELEMENT_SHARE:
        buttonClass = ShareButton.class;
        break;
    case PAYMENT:
        buttonClass = BuyButton.class;
        break;
    case PHONE_NUMBER:
        buttonClass = PostbackButton.class;
        break;
    case POSTBACK:
        buttonClass = PostbackButton.class;
        break;
    case WEB_URL:
        buttonClass = WebUrlButton.class;
        break;
    }
    return context.deserialize(json, buttonClass);
}

From source file:co.aurasphere.botmill.fb.internal.util.json.ButtonSerializer.java

License:Open Source License

public Button deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    String buttonTypeString = json.getAsJsonObject().get("type").getAsString();
    ButtonType buttonType = ButtonType.valueOf(buttonTypeString.toUpperCase());
    Class<?> buttonClass = getButtonClass(buttonType);
    return context.deserialize(json, buttonClass);
}

From source file:co.aurasphere.botmill.fb.internal.util.json.IncomingMessageDeserializer.java

License:Open Source License

public IncomingMessage deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    boolean isEcho = false;

    if (json.getAsJsonObject().get("is_echo") != null && json.getAsJsonObject().get("is_echo").isJsonNull()) {
        isEcho = json.getAsJsonObject().get("is_echo").getAsBoolean();
    }//from   www .j  a  v  a  2 s  .  co  m

    Class<? extends IncomingMessage> incomingMessageClass = null;
    if (isEcho == true) {
        incomingMessageClass = EchoMessage.class;
    } else {
        incomingMessageClass = ReceivedMessage.class;
    }
    return context.deserialize(json, incomingMessageClass);
}

From source file:co.aurasphere.botmill.kik.util.json.IncomingMessagesDeserializer.java

License:Open Source License

@SuppressWarnings("incomplete-switch")
public MessageCallback deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    MessageCallback messageCallback = new MessageCallback();
    //   The message callback can have multiple message bodies.
    JsonElement jsonMessages = json.getAsJsonObject().get("messages");

    for (int i = 0; i < jsonMessages.getAsJsonArray().size(); i++) {
        //   get type.
        JsonObject jsonMessage = jsonMessages.getAsJsonArray().get(i).getAsJsonObject();
        String typeString = jsonMessage.get("type").getAsString();
        MessageType messageType = MessageType.valueOf(typeString.replace('-', '_').toUpperCase());
        Class<? extends Message> messageClass = null;
        switch (messageType) {
        case TEXT:
            messageClass = TextMessage.class;
            break;
        case PICTURE:
            messageClass = PictureMessage.class;
            break;
        case VIDEO:
            messageClass = VideoMessage.class;
            break;
        case LINK:
            messageClass = LinkMessage.class;
            break;
        case SCAN_DATA:
            messageClass = ScanDataMessage.class;
            break;
        case STICKER:
            messageClass = StickerMessage.class;
            break;
        case FRIEND_PICKER:
            messageClass = FriendPickerMessage.class;
            break;
        case IS_TYPING:
            messageClass = IsTypingMessage.class;
            break;
        case READ_RECEIPT:
            messageClass = ReadReceiptMessage.class;
            break;
        case START_CHATTING:
            messageClass = StartChattingMessage.class;
            break;
        }/*from www.  jav a2  s. co  m*/

        Message message = context.deserialize(jsonMessage, messageClass);
        messageCallback.addMessage(message);
    }

    return messageCallback;
}