Project

General

Profile

Actions

InitializeSubscriber JAVA

/**
 * Recreate database schema from remote server for specific subscriber
 * @param subscriberId id of subscriber
 * @throws Exception
 */
public void initializeSubscriber(String subscriberId) throws Exception {
    HttpURLConnection connection = null;
    InputStream resultStream = null;
    String resultString = null;
    Map<String, String> schema = null;

    String requestUrl = String.format("%s/InitializeSubscriber/%s", _serverURL, subscriberId);

    try {
        connection = (HttpURLConnection) new URL(requestUrl).openConnection();

        int status = connection.getResponseCode();

        switch (status){
            case HttpURLConnection.HTTP_OK:
                resultStream = connection.getInputStream();
                resultString = IOUtils.toString(resultStream, "UTF-8");
                schema = new Gson().fromJson(resultString, new TypeToken<Map<String, String>>(){}.getType());
                break;
            default:
                resultStream = connection.getErrorStream();
                resultString = IOUtils.toString(resultStream, "UTF-8");
                throw new Exception(resultString);
        }
    }
    finally {
        if (resultStream != null) {
            try {
                resultStream.close();
            } catch (IOException e) {
            }
        }
        if (connection != null) {
            connection.disconnect();
        }
    }

    List<String> keys = new ArrayList<String>();
    Set<String> keySet = schema.keySet();
    for(String key : keySet){
        keys.add(key);
    }
    Collections.sort(keys);

    SQLiteDatabase db = openOrCreateDatabase(_dbFileName, null);
    try{
        db.beginTransaction();
        for (String key : keys) {
            if(!key.startsWith("00000")){
                db.execSQL(schema.get(key));
            }
        }
        db.setTransactionSuccessful();
    }
    finally {
        db.endTransaction();
        db.close();
    }
}

Updated by Tomek Dziemidowicz 5 months ago · 1 revisions