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

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

Introduction

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

Prototype

@Override
    public V put(K key, V value) 

Source Link

Usage

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

License:Apache License

/**
 * Calls a method through the API./*from   w  w w.j  a v 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.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 a2  s  . c  o m
    return returnCustomerGroup;
}

From source file:com.magestore.app.pos.api.m2.config.POSConfigDataAccess.java

/**
 * Ly customer group trong config/*  w  ww  .  ja va2  s .c o m*/
 *
 * @return
 * @throws DataAccessException
 * @throws ConnectionException
 * @throws ParseException
 * @throws IOException
 * @throws ParseException
 */
@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());
    }
    return returnCustomerGroup;
}

From source file:com.melchor629.musicote.MainActivity.java

License:Apache License

@Override
public boolean onQueryTextSubmit(String query) {
    DB dbs = new DB(this);
    SQLiteDatabase db = dbs.getReadableDatabase();
    Cursor c = dbs.get(db, query);
    songList.clear();/*  w  w w .j a  va 2 s . c  o m*/
    c.moveToFirst();
    if (c.getCount() > 0) {
        do {
            // creating new HashMap
            LinkedTreeMap<String, String> map = new LinkedTreeMap<>();

            long id = c.getLong(c.getColumnIndexOrThrow(DB_entry.COLUMN_CANCIONES_ID));
            String titulo = c.getString(c.getColumnIndexOrThrow(DB_entry.COLUMN_CANCIONES_TITULO));
            String artista = c.getString(c.getColumnIndexOrThrow(DB_entry.COLUMN_CANCIONES_ARTISTA));
            String album = c.getString(c.getColumnIndexOrThrow(DB_entry.COLUMN_CANCIONES_ALBUM));
            String archivo = c.getString(c.getColumnIndexOrThrow(DB_entry.COLUMN_CANCIONES_ARCHIVO));
            String duracion = c.getString(c.getColumnIndexOrThrow(DB_entry.COLUMN_CANCIONES_DURACION));
            String down = c.getString(c.getColumnIndexOrThrow(DB_entry.COLUMN_CANCIONES_DOWNLOADED));
            boolean downloaded = down.equalsIgnoreCase("true");

            // adding each child node to HashMap key => value
            map.put("id", "" + id);
            map.put("titulo", titulo);
            map.put("artista", artista);
            map.put("album", album);
            map.put("archivo", archivo);
            map.put("duracion", duracion);
            map.put("downloaded", downloaded ? "{fa-mobile}" : "{fa-cloud}"); //TODO

            songList.add(map);
        } while (c.moveToNext());
    }
    sis();
    c.close();
    db.close();
    return false;
}

From source file:com.melchor629.musicote.MainActivity.java

License:Apache License

/** Carga desde la base de datos */
private void cursordb(SQLiteDatabase db) {
    // Define a projection that specifies which columns from the database
    // you will actually use after this query.
    String[] projection = { DB_entry.COLUMN_CANCIONES_ID, DB_entry.COLUMN_CANCIONES_TITULO,
            DB_entry.COLUMN_CANCIONES_ARTISTA, DB_entry.COLUMN_CANCIONES_ALBUM,
            DB_entry.COLUMN_CANCIONES_DURACION, DB_entry.COLUMN_CANCIONES_ARCHIVO,
            DB_entry.COLUMN_CANCIONES_DOWNLOADED };

    // How you want the results sorted in the resulting Cursor
    String sortOrder = DB_entry.COLUMN_CANCIONES_ID + " ASC";

    Cursor c = db.query(DB_entry.TABLE_CANCIONES, // The table to query
            projection, // The columns to return
            null, // The columns for the WHERE clause
            null, // The values for the WHERE clause
            null, // don't group the rows
            null, // don't filter by row groups
            sortOrder // The sort order
    );//w w w  .j  av  a 2  s  .co  m
    if (songList != null)
        songList.clear();
    else
        songList = new ArrayList<>();

    c.moveToFirst();
    try {
        do {
            // creating new HashMap
            LinkedTreeMap<String, String> map = new LinkedTreeMap<>();

            long id = c.getLong(c.getColumnIndexOrThrow(DB_entry.COLUMN_CANCIONES_ID));
            String titulo = c.getString(c.getColumnIndexOrThrow(DB_entry.COLUMN_CANCIONES_TITULO));
            String artista = c.getString(c.getColumnIndexOrThrow(DB_entry.COLUMN_CANCIONES_ARTISTA));
            String album = c.getString(c.getColumnIndexOrThrow(DB_entry.COLUMN_CANCIONES_ALBUM));
            String archivo = c.getString(c.getColumnIndexOrThrow(DB_entry.COLUMN_CANCIONES_ARCHIVO));
            String duracion = c.getString(c.getColumnIndexOrThrow(DB_entry.COLUMN_CANCIONES_DURACION));
            String downloaded = "false";//c.getString(c.getColumnIndexOrThrow(DB_entry.COLUMN_CANCIONES_DOWNLOADED));

            // adding each child node to HashMap key => value
            map.put("id", "" + id);
            map.put("titulo", titulo);
            map.put("artista", artista);
            map.put("album", album);
            map.put("archivo", archivo);
            map.put("duracion", duracion);
            map.put("downloaded", downloaded.equalsIgnoreCase("true") ? "{fa-mobile}" : "{fa-cloud}"); //TODO

            songList.add(map);
        } while (c.moveToNext());
    } catch (CursorIndexOutOfBoundsException e) {
        db.execSQL(DB_entry.DELETE_CANCIONES);
        Log.e("DB", "Mala integridad de la BD");
    }
    c.close();
    sis();
}

From source file:ddf.catalog.source.solr.rest.SolrRest.java

License:Open Source License

private void setSimilarities() {
    if (CollectionUtils.isNotEmpty(fieldTypes)) {
        LinkedTreeMap<String, Object> replaceField = new LinkedTreeMap<>();
        for (Object fieldType : fieldTypes) {
            LinkedTreeMap<String, Object> objectLinkedTreeMap = (LinkedTreeMap<String, Object>) fieldType;
            Object nameObj = objectLinkedTreeMap.get("name");
            if (nameObj instanceof String) {
                String name = (String) nameObj;
                if (name.contains("suggest")) {
                    LOGGER.trace("Skipping suggest field");
                    continue;
                }/*w ww.  j  a  v a 2s. c  o  m*/
            }

            objectLinkedTreeMap.put("similarity", similarityFormat);
            replaceField.put("replace-field-type", objectLinkedTreeMap);

            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Replacing field: {}", gson.toJson(replaceField));
            }

            String response = solrCatalogSchemaClientFactory.getClient()
                    .replaceField(gson.toJson(replaceField));
            LOGGER.trace("Catalog Configuration update response: {}", response);

            response = solrMetacardCacheSchemaClientFactory.getClient().replaceField(gson.toJson(replaceField));
            LOGGER.trace("Metacard Cache Configuration update response: {}", response);
        }
    }
}

From source file:org.cgiar.ccafs.marlo.action.center.json.autosave.AutoSaveWriterAction.java

License:Open Source License

@Override
public String execute() throws Exception {

    String fileId = "";
    String fileClass = "";
    String nameClass = "";
    String fileAction = "";

    status = new HashMap<String, Object>();

    if (autoSave.length > 0) {

        Gson gson = new Gson();
        byte ptext[] = autoSave[0].getBytes(ISO_8859_1);
        String value = new String(ptext, UTF_8);

        @SuppressWarnings("unchecked")

        LinkedTreeMap<String, Object> result = gson.fromJson(value, LinkedTreeMap.class);

        String userModifiedBy = fileId = (String) result.get("modifiedBy.id");
        if (result.containsKey("id")) {
            fileId = (String) result.get("id");
        } else {//from   www  . j  av  a 2  s. com
            fileId = "XX";
        }

        if (result.containsKey("className")) {
            String ClassName = (String) result.get("className");
            String[] composedClassName = ClassName.split("\\.");
            nameClass = ClassName;
            fileClass = composedClassName[composedClassName.length - 1];
        }

        if (result.containsKey("actionName")) {
            fileAction = (String) result.get("actionName");
            fileAction = fileAction.replace("/", "_");
        }
        ArrayList<String> keysRemove = new ArrayList<>();

        for (Map.Entry<String, Object> entry : result.entrySet()) {
            if (entry.getKey().contains("__")) {
                keysRemove.add(entry.getKey());
            }
        }
        for (String string : keysRemove) {
            result.remove(string);
        }
        Date generatedDate = new Date();
        result.put("activeSince", generatedDate);

        String jSon = gson.toJson(result);

        if (nameClass.equals(CenterOutcome.class.getName())) {
            jSon = jSon.replaceAll("outcome\\.", "");
        }
        if (nameClass.equals(CenterOutput.class.getName())) {
            jSon = jSon.replaceAll("output\\.", "");
        }
        if (nameClass.equals(CenterProject.class.getName())) {
            jSon = jSon.replaceAll("project\\.", "");
        }
        if (nameClass.equals(CenterDeliverable.class.getName())) {
            jSon = jSon.replaceAll("deliverable\\.", "");
        }
        if (nameClass.equals(CapacityDevelopment.class.getName())) {
            jSon = jSon.replaceAll("capdev\\.", "");
        }

        try {

            String fileName = fileId + "_" + fileClass + "_" + fileAction + ".json";
            String pathFile = config.getAutoSaveFolder();
            Path path = Paths.get(pathFile);

            if (Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
                File file = new File(config.getAutoSaveFolder() + fileName);
                Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"));
                out.append(jSon).append("\r\n");
                ;

                out.flush();
                out.close();
            } else {
                Files.createDirectories(path);
                File file = new File(config.getAutoSaveFolder() + fileName);
                Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"));
                out.append(jSon).append("\r\n");
                ;

                out.flush();
                out.close();
            }
            status.put("status", true);
            SimpleDateFormat dt = new SimpleDateFormat("yyyyy-mm-dd hh:mm:ss");
            status.put("modifiedBy",
                    userService.getUser(Long.parseLong(userModifiedBy)).getComposedCompleteName());
            status.put("activeSince", dt.format(generatedDate));
        } catch (IOException e) {
            status.put("status", false);
            e.printStackTrace();
        } catch (Exception e) {
            status.put("status", false);
            e.printStackTrace();
        }

    }

    return Action.SUCCESS;
}

From source file:org.cgiar.ccafs.marlo.action.json.autosave.AutoSaveWriterAction.java

License:Open Source License

@Override
public String execute() throws Exception {

    String fileId = "";
    String fileClass = "";
    String nameClass = "";
    String fileAction = "";

    status = new HashMap<String, Object>();

    if (autoSave.length > 0) {

        Gson gson = new Gson();
        byte ptext[] = autoSave[0].getBytes(ISO_8859_1);
        String value = new String(ptext, UTF_8);

        @SuppressWarnings("unchecked")

        LinkedTreeMap<String, Object> result = gson.fromJson(value, LinkedTreeMap.class);

        String userModifiedBy = fileId = (String) result.get("modifiedBy.id");
        if (result.containsKey("id")) {
            fileId = (String) result.get("id");
        } else {/*from  w  ww  . j a  v  a 2  s .com*/
            fileId = "XX";
        }

        if (result.containsKey("className")) {
            String ClassName = (String) result.get("className");
            String[] composedClassName = ClassName.split("\\.");
            nameClass = ClassName;
            fileClass = composedClassName[composedClassName.length - 1];
        }

        if (result.containsKey("actionName")) {
            fileAction = (String) result.get("actionName");
            fileAction = fileAction.replace("/", "_");
        }
        ArrayList<String> keysRemove = new ArrayList<>();

        for (Map.Entry<String, Object> entry : result.entrySet()) {
            if (entry.getKey().contains("__")) {
                keysRemove.add(entry.getKey());
            }
        }
        for (String string : keysRemove) {
            result.remove(string);
        }
        Date generatedDate = new Date();
        result.put("activeSince", generatedDate);

        String jSon = gson.toJson(result);

        if (nameClass.equals(ResearchOutcome.class.getName())) {
            jSon = jSon.replaceAll("outcome\\.", "");
        }
        if (nameClass.equals(ResearchOutput.class.getName())) {
            jSon = jSon.replaceAll("output\\.", "");
        }

        try {

            String fileName = fileId + "_" + fileClass + "_" + fileAction + ".json";
            String pathFile = config.getAutoSaveFolder();
            System.out.println(pathFile);
            Path path = Paths.get(pathFile);

            if (Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
                File file = new File(config.getAutoSaveFolder() + fileName);
                Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"));
                out.append(jSon).append("\r\n");
                ;

                out.flush();
                out.close();
            } else {
                Files.createDirectories(path);
                File file = new File(config.getAutoSaveFolder() + fileName);
                Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"));
                out.append(jSon).append("\r\n");
                ;

                out.flush();
                out.close();
            }
            status.put("status", true);
            SimpleDateFormat dt = new SimpleDateFormat("yyyyy-mm-dd hh:mm:ss");
            status.put("modifiedBy",
                    userService.getUser(Long.parseLong(userModifiedBy)).getComposedCompleteName());
            status.put("activeSince", dt.format(generatedDate));
        } catch (IOException e) {
            status.put("status", false);
            e.printStackTrace();
        } catch (Exception e) {
            status.put("status", false);
            e.printStackTrace();
        }

    }

    return Action.SUCCESS;
}

From source file:ro.sandd.qsync.QSync.java

License:Open Source License

/**
 * Saves a key-value pair for syncing/*from  w  ww.  j  a v a 2 s. com*/
 * @param key A string representing the key for identifying the stored data
 * @param value The stored data
 * @throws CouchbaseLiteException
 */
public static void putValue(String key, Object value) throws CouchbaseLiteException {
    Gson gson = new Gson();
    HashMap<String, Object> hm = new HashMap<String, Object>();
    hm.put("data", value);
    String json = gson.toJson(hm);
    final LinkedTreeMap map = gson.fromJson(json, LinkedTreeMap.class);
    map.put("timestamp", System.currentTimeMillis());
    db.getDocument(key).update(new Document.DocumentUpdater() {
        public boolean update(UnsavedRevision unsavedRevision) {
            unsavedRevision.setUserProperties(map);
            return true;
        }
    });
    Map<String, Object> doc = new HashMap<String, Object>();
    doc.put("sequence", db.getLastSequenceNumber());
    db.putLocalDocument("sequence", doc);
}