Example usage for com.google.gson.internal LinkedTreeMap LinkedTreeMap

List of usage examples for com.google.gson.internal LinkedTreeMap LinkedTreeMap

Introduction

In this page you can find the example usage for com.google.gson.internal LinkedTreeMap LinkedTreeMap.

Prototype

@SuppressWarnings("unchecked") 
public LinkedTreeMap() 

Source Link

Document

Create a natural order, empty tree map whose keys must be mutually comparable and non-null.

Usage

From source file:com.aelitis.azureus.util.ObjectTypeAdapterLong.java

License:Apache License

@Override
public Object read(JsonReader in) throws IOException {
    JsonToken token = in.peek();/*from www  .  j a  va2s  . com*/
    switch (token) {
    case BEGIN_ARRAY:
        List<Object> list = new ArrayList<Object>();
        in.beginArray();
        while (in.hasNext()) {
            list.add(read(in));
        }
        in.endArray();
        return list;

    case BEGIN_OBJECT:
        Map<String, Object> map = new LinkedTreeMap<String, Object>();
        in.beginObject();
        while (in.hasNext()) {
            map.put(in.nextName(), read(in));
        }
        in.endObject();
        return map;

    case STRING:
        return in.nextString();

    case NUMBER: {
        String value = in.nextString();
        if (value.indexOf('.') >= 0) {
            return Double.parseDouble(value);
        } else {
            return Long.parseLong(value);
        }
    }

    case BOOLEAN:
        return in.nextBoolean();

    case NULL:
        in.nextNull();
        return null;

    default:
        throw new IllegalStateException();
    }
}

From source file:com.bzcentre.dapiPush.MeetingPayload.java

License:Open Source License

private Object extractAps(JsonElement in) {
    if (in == null || in.isJsonNull())
        return null;

    if (in.isJsonArray()) {
        List<Object> list = new ArrayList<>();
        JsonArray arr = in.getAsJsonArray();
        for (JsonElement anArr : arr) {
            list.add(extractAps(anArr));
        }//from w ww.ja  va2  s  .co m
        return list;
    } else if (in.isJsonObject()) {
        Map<String, Object> map = new LinkedTreeMap<>();
        JsonObject obj = in.getAsJsonObject();
        Set<Map.Entry<String, JsonElement>> entitySet = obj.entrySet();
        for (Map.Entry<String, JsonElement> entry : entitySet) {
            map.put(entry.getKey(), extractAps(entry.getValue()));
            NginxClojureRT.log.debug(TAG + entry.getKey() + "=>" + map.get(entry.getKey()) + "=>"
                    + map.get(entry.getKey()).getClass().getTypeName());
            switch (entry.getKey()) {
            case "dapi":
                this.setDapi(map.get(entry.getKey()));
                break;
            case "acme1":
                this.setAcme1(map.get(entry.getKey()));
                break;
            case "acme2":
                this.setAcme2(map.get(entry.getKey()));
                break;
            case "acme3":
                this.setAcme3(map.get(entry.getKey()));
                break;
            case "acme4":
                this.setAcme4(map.get(entry.getKey()));
                break;
            case "acme5":
                this.setAcme5(map.get(entry.getKey()));
                break;
            case "acme6":
                this.setAcme6(map.get(entry.getKey()));
                break;
            case "acme7":
                this.setAcme7(map.get(entry.getKey()));
                break;
            case "acme8":
                this.setAcme8(map.get(entry.getKey()));
                break;
            case "aps":
                NginxClojureRT.log.debug(TAG + "aps initialized");
                break;
            case "badge":
                this.getAps().setBadge(map.get(entry.getKey()));
                break;
            case "sound":
                this.getAps().setSound(map.get(entry.getKey()));
                break;
            case "alert":
                NginxClojureRT.log.debug(TAG + "alert initialized");
                break;
            case "title":
                this.getAps().getAlert().setTitle(map.get(entry.getKey()));
                break;
            case "body":
                this.getAps().getAlert().setBody(map.get(entry.getKey()));
                break;
            case "action-loc-key":
                this.getAps().getAlert().setActionLocKey(map.get(entry.getKey()));
                break;
            default:
                NginxClojureRT.log.info(TAG + "Unhandled field : " + entry.getKey());
                break;
            }
        }
        return map;
    } else if (in.isJsonPrimitive()) {
        JsonPrimitive prim = in.getAsJsonPrimitive();
        if (prim.isBoolean()) {
            return prim.getAsBoolean();
        } else if (prim.isString()) {
            return prim.getAsString();
        } else if (prim.isNumber()) {
            Number num = prim.getAsNumber();
            // here you can handle double int/long values
            // and return any type you want
            // this solution will transform 3.0 float to long values
            if (Math.ceil(num.doubleValue()) == num.longValue()) {
                return num.longValue();
            } else {
                return num.doubleValue();
            }
        }
    }
    NginxClojureRT.log.info("Handling json null");
    return null;
}

From source file:com.devoxx.watson.AskDevoxxController.java

License:Apache License

/**
 * Calls the appropriate Watson services to get an answer to the client's inquiry
 * @param question/*from  www. j  a va  2s .  c o m*/
 * @return An answer to the client's inquiry
 */
private InquiryResponseNear callDevoxxWatsonServices(final DevoxxQuestion question) {

    InquiryResponseNear inquiryResponseNear = new InquiryResponseNear();
    List<RetrieveAndRankDocument> retrieveAndRankDocumentList = new ArrayList<>();

    Map<String, Object> requestContext = new LinkedTreeMap<>();
    Map<String, Object> requestContextSystem = new LinkedTreeMap<>();

    String dialogStack;
    String dialogTurnCounter;
    String dialogRequestCounter;
    String conversationId = null;

    final ConversationContext context = question.getContext();
    if (context != null) {

        dialogStack = context.getSystem().getDialogStack();
        dialogTurnCounter = context.getSystem().getDialogTurnCounter();
        dialogRequestCounter = context.getSystem().getDialogRequestCounter();
        conversationId = context.getConversationId();

        if (dialogStack != null && dialogStack.length() > 2) {
            List<String> dialogStackList = new ArrayList<>();
            if (dialogStack.charAt(0) == '[' && dialogStack.charAt(dialogStack.length() - 1) == ']') {
                dialogStack = dialogStack.substring(1, dialogStack.length() - 1);
            }
            dialogStackList.add(dialogStack);
            requestContextSystem.put("dialog_stack", dialogStackList);
        }

        if (dialogTurnCounter != null && dialogTurnCounter.length() > 0) {
            requestContextSystem.put("dialog_turn_counter", new Double(dialogTurnCounter));
        }

        if (dialogRequestCounter != null && dialogRequestCounter.length() > 0) {
            requestContextSystem.put("dialog_request_counter", new Double(dialogRequestCounter));
        }

        if (dialogStack != null && dialogStack.length() > 0
                || dialogTurnCounter != null && dialogTurnCounter.length() > 0
                || dialogRequestCounter != null && dialogRequestCounter.length() > 0) {
            requestContext.put("system", requestContextSystem);
        }

        if (conversationId != null && conversationId.length() > 0) {
            requestContext.put("conversation_id", conversationId);
        }
    }

    MessageRequest request = new MessageRequest.Builder().inputText(question.getText())
            .context(conversationId != null && conversationId.length() > 1 ? requestContext : null).build();

    ConversationService service = new ConversationService(ConversationService.VERSION_DATE_2016_07_11);
    if (conversationUsername != null || conversationPassword != null) {
        service.setUsernameAndPassword(conversationUsername, conversationPassword);
    }
    if (conversationUrl != null) {
        service.setEndPoint(conversationUrl);
    }

    // Use the previously configured service object to make a call to the conversational service
    MessageResponse response = service.message(workspaceId, request).execute();

    String responseText = response.getTextConcatenated(", ");

    // Determine if conversation's response is sufficient to answer the user's question or if we
    // should call the retrieve and rank service to obtain better answers
    if (response.getOutput().toString().contains("callRetrieveAndRank")) {
        log.info("Calling retrieve and rank with inquiry: " + question.getText());
        retrieveAndRankDocumentList = retrieveAndRankController.call(question.getText());

        // Truncate the extra JSON from the responseText that indicated that retrieve and rank should be called
        int indexOfLeftCurly = responseText.indexOf('{');
        if (indexOfLeftCurly > 1) {
            responseText = responseText.substring(0, indexOfLeftCurly);
        }
    }

    inquiryResponseNear.setInquiryText(question.getText());
    inquiryResponseNear.setResponseText(responseText);
    inquiryResponseNear.setResources(retrieveAndRankDocumentList);

    Map<String, Object> responseContext = response.getContext();
    Map<String, Object> responseContextSystem = (Map) responseContext.get("system");
    ConversationContextSystem conversationContextSystem = null;
    if (responseContextSystem != null) {
        conversationContextSystem = new ConversationContextSystem(
                responseContextSystem.get("dialog_stack") != null
                        ? responseContextSystem.get("dialog_stack").toString()
                        : "",
                responseContextSystem.get("dialog_turn_counter") != null
                        ? responseContextSystem.get("dialog_turn_counter").toString()
                        : "",
                responseContextSystem.get("dialog_request_counter") != null
                        ? responseContextSystem.get("dialog_request_counter").toString()
                        : "");
    }
    ConversationContext conversationContext = new ConversationContext(
            responseContext.get("conversation_id") != null ? responseContext.get("conversation_id").toString()
                    : "",
            conversationContextSystem);
    inquiryResponseNear.setContext(conversationContext);
    log.info("response.toString() " + response.toString());

    return inquiryResponseNear;
}

From source file:com.google.api.codegen.discogapic.DiscoGapicGenerator.java

License:Apache License

@Override
public Map<String, GeneratedResult<Doc>> generate() {
    Map<String, GeneratedResult<Doc>> results = new LinkedTreeMap<>();

    for (ModelToViewTransformer<DiscoApiModel> transformer : transformers) {
        List<ViewModel> surfaceDocs = transformer.transform(model, productConfig);

        for (ViewModel surfaceDoc : surfaceDocs) {
            results.putAll(snippetSetRunner.generate(surfaceDoc));
        }//from w ww  . jav a 2 s  . c o m
    }

    return results;
}

From source file:com.google.api.codegen.discovery.Document.java

License:Apache License

private static Map<String, List<Method>> parseResources(DiscoveryNode root) {
    List<Method> methods = new ArrayList<>();
    DiscoveryNode methodsNode = root.getObject("methods");
    List<String> resourceNames = methodsNode.getFieldNames();
    for (String name : resourceNames) {
        methods.add(Method.from(methodsNode.getObject(name), null));
    }/*from  w  ww  .  j  a  v a2s . c o m*/
    Map<String, List<Method>> resources = new LinkedTreeMap<>();
    DiscoveryNode resourcesNode = root.getObject("resources");
    resourceNames = resourcesNode.getFieldNames();
    for (String name : resourceNames) {
        resources.put(name, parseMethods(resourcesNode.getObject(name)));
    }
    return resources;
}

From source file:com.inverseinnovations.VBulletinAPI.VBulletinAPI.java

License:Apache License

/**
 * Calls a method through the API.//from w w w . j  av  a 2  s.  co m
 *
 * @param methodname
 *            the name of the method to call
 * @param params
 *            the parameters as a map
 * @param sign
 *            if the request should be signed or not. Generally, you want this to be true
 * @return the array returned by the server
 * @throws IOException
 *             If the URL is wrong, or a connection is unable to be made for
 *             whatever reason.
 */
private LinkedTreeMap<String, Object> callMethod(String methodname, Map<String, String> params, boolean sign) {// throws IOException{
    LinkedTreeMap<String, Object> map = new LinkedTreeMap<String, Object>();

    try {

        StringBuffer queryStringBuffer = new StringBuffer("api_m=" + methodname);
        SortedSet<String> keys = new TreeSet<String>(params.keySet());
        for (String key : keys) {// ' " \ are unsafe
            String value = Functions.querySafeString(params.get(key));
            queryStringBuffer.append("&" + key + "=" + URLEncoder.encode(value, "UTF-8"));
        }
        if (sign) {
            queryStringBuffer.append("&api_sig=" + Functions.MD5((queryStringBuffer.toString()
                    + getAPIAccessToken() + apiClientID + getSecret() + getAPIkey())).toLowerCase());
            if (DEBUG) {
                System.out.println("encoded: " + queryStringBuffer.toString());
            }
        }

        queryStringBuffer.append("&api_c=" + apiClientID);
        queryStringBuffer.append("&api_s=" + getAPIAccessToken());
        String queryString = queryStringBuffer.toString();
        queryString = queryString.replace(" ", "%20");
        URL apiUrl = new URL(apiURL + "?" + queryString);
        HttpURLConnection conn = (HttpURLConnection) apiUrl.openConnection();
        conn.setRequestMethod("POST");

        conn.setConnectTimeout(10000); //set timeout to 10 seconds
        conn.setReadTimeout(10000);//set timeout to 10 seconds
        conn.setDoOutput(true);
        conn.setDoInput(true);
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        out.writeBytes(queryString);
        InputStream is = null;
        try {
            is = conn.getInputStream();
        } finally {
            if (is != null) {
                String json = Functions.inputStreamToString(is);

                //need to remove everything before {
                if (json.contains("{")) {
                    json = json.substring(json.indexOf("{"));
                }

                Gson gson = new Gson();
                JsonReader reader = new JsonReader(new StringReader(json));
                reader.setLenient(true);
                try {
                    map = gson.fromJson(reader, new TypeToken<Map<String, Object>>() {
                    }.getType());
                } catch (Exception e) {//TODO need to check what kind of errors...
                    System.out.println(json);
                    e.printStackTrace();
                    map = new LinkedTreeMap<String, Object>();
                    map.put("custom", new String("IllegalStateException"));
                }
            }

        }
        conn.disconnect();
    } catch (java.net.SocketTimeoutException e) {
        map = new LinkedTreeMap<String, Object>();
        map.put("custom", new String("SocketTimeoutException"));
    } catch (IOException e) {
        map = new LinkedTreeMap<String, Object>();
        map.put("custom", new String("IOException"));
    }
    return map;
}

From source file:com.jkoolcloud.tnt4j.streams.utils.Utils.java

License:Apache License

/**
 * Deserializes JSON data object ({@link String}, {@link java.io.Reader}, {@link java.io.InputStream}) into map
 * structured data./*from  w w  w .ja  v  a2s  . c o m*/
 *
 * @param jsonData
 *            JSON format data object
 * @param jsonAsLine
 *            flag indicating that complete JSON data package is single line
 * @return data map parsed from JSON data object
 * @throws com.google.gson.JsonSyntaxException
 *             if there was a problem reading from the Reader
 * @throws com.google.gson.JsonIOException
 *             if json is not a valid representation for an object of type
 * 
 * @see com.google.gson.Gson#fromJson(String, Class)
 * @see com.google.gson.Gson#fromJson(java.io.Reader, Class)
 */
@SuppressWarnings("unchecked")
public static Map<String, ?> fromJsonToMap(Object jsonData, boolean jsonAsLine) {
    Map<String, ?> map = new LinkedTreeMap<String, Object>();
    Gson gson = new Gson();

    if (jsonAsLine) {
        try {
            map = (Map<String, ?>) gson.fromJson(getStringLine(jsonData), map.getClass());
        } catch (IOException ioe) {
            throw new JsonIOException(ioe);
        }
    } else {
        if (jsonData instanceof String) {
            map = (Map<String, ?>) gson.fromJson((String) jsonData, map.getClass());
        } else if (jsonData instanceof byte[]) {
            map = (Map<String, ?>) gson.fromJson(getString((byte[]) jsonData), map.getClass());
        } else if (jsonData instanceof Reader) {
            map = (Map<String, ?>) gson.fromJson((Reader) jsonData, map.getClass());
        } else if (jsonData instanceof InputStream) {
            map = (Map<String, ?>) gson.fromJson(
                    new BufferedReader(new InputStreamReader((InputStream) jsonData)), map.getClass());
        }
    }

    return map;
}

From source file:com.magestore.app.pos.api.m1.config.POSConfigDataAccessM1.java

@Override
public Map<String, String> getCustomerGroup()
        throws DataAccessException, ConnectionException, ParseException, IOException, ParseException {
    // nu cha load config, cn khi to ch  default
    if (mConfig == null)
        mConfig = new PosConfigDefault();

    // Chuyn i customer
    List<LinkedTreeMap> customerGroupList = (ArrayList) mConfig.getValue("customerGroup");
    LinkedTreeMap<String, String> returnCustomerGroup = new LinkedTreeMap<String, String>();
    for (LinkedTreeMap customerGroup : customerGroupList) {
        Double id = (Double) customerGroup.get("id");
        returnCustomerGroup.put(String.format("%.0f", id), customerGroup.get("code").toString());
    }//from w ww.  j  a  v  a  2s.  c om
    return returnCustomerGroup;
}

From source file:com.magestore.app.pos.api.m1.config.POSConfigDataAccessM1.java

@Override
public Map<String, ConfigCountry> getCountryGroup()
        throws DataAccessException, ConnectionException, ParseException, IOException, ParseException {
    // nu cha load config, cn khi to ch  default
    if (mConfig == null)
        mConfig = new PosConfigDefault();

    List<LinkedTreeMap> countryList = (ArrayList) mConfig.getValue("country");
    Map<String, ConfigCountry> listConfigCountry = new LinkedTreeMap<>();
    Collections.sort(countryList, new Comparator<LinkedTreeMap>() {
        @Override/*from w  w  w.java2s .  c  o m*/
        public int compare(LinkedTreeMap linkedTreeMap, LinkedTreeMap linkedTreeMap1) {
            String name = linkedTreeMap.get("country_name").toString();
            String name1 = linkedTreeMap1.get("country_name").toString();
            return name.compareToIgnoreCase(name1);
        }
    });
    for (LinkedTreeMap country : countryList) {
        ConfigCountry configCountry = new PosConfigCountry();
        String country_id = country.get("country_id").toString();
        String country_name = country.get("country_name").toString();
        configCountry.setCountryID(country_id);
        configCountry.setCountryName(country_name);
        Map<String, ConfigRegion> mapRegion = getRegion(country_id);
        if (mapRegion != null) {
            configCountry.setRegions(mapRegion);
        }
        listConfigCountry.put(country_id, configCountry);
    }
    return listConfigCountry;
}

From source file:com.magestore.app.pos.api.m1.config.POSConfigDataAccessM1.java

private Map<String, Map<String, ConfigRegion>> getRegionGroup() {
    // nu cha load config, cn khi to ch  default
    if (mConfig == null)
        mConfig = new PosConfigDefault();
    Map<String, LinkedTreeMap> regionGroup = (Map) mConfig.getValue("regionJson");
    Map<String, Map<String, ConfigRegion>> mapCountry = new HashMap<>();

    for (String key : regionGroup.keySet()) {
        if (!key.equals("config")) {
            Map<String, ConfigRegion> listConfigRegion = new LinkedTreeMap<>();
            Map<String, LinkedTreeMap> region = (Map<String, LinkedTreeMap>) regionGroup.get(key);
            for (String id : region.keySet()) {
                ConfigRegion configRegion = new PosConfigRegion();
                LinkedTreeMap item = (LinkedTreeMap) region.get(id);
                String code = (String) item.get("code");
                String name = (String) item.get("name");
                configRegion.setID(id);//  w  w w  . j ava  2  s.  co m
                configRegion.setCode(code);
                configRegion.setName(name);
                listConfigRegion.put(id, configRegion);
            }
            mapCountry.put(key, listConfigRegion);
        }
    }
    return mapCountry;
}