Search in sources :

Example 1 with JsonWriter

use of android.util.JsonWriter in project MQTTPushClient_Android by RadioShuttle.

the class DashBoardViewModel method saveLastReceivedMessages.

public void saveLastReceivedMessages() {
    if (mLastReceivedMessages != null && mLastReceivedMessages.size() > 0) {
        final ArrayList<Message> msgArr = new ArrayList<>(mLastReceivedMessages.values());
        final String pushServerID = mPushAccount.pushserverID;
        final String mqttAccount = mPushAccount.getMqttAccountName();
        final Application app = getApplication();
        Log.d(TAG, "Save messages: " + pushServerID + ", " + mqttAccount);
        if (!Utils.isEmpty(pushServerID) && !Utils.isEmpty(mqttAccount)) {
            Utils.executor.execute(new Runnable() {

                @Override
                public void run() {
                    try {
                        AppDatabase db = AppDatabase.getInstance(app);
                        MqttMessageDao dao = db.mqttMessageDao();
                        Long psid = dao.getCode(pushServerID);
                        if (psid == null) {
                            Code c = new Code();
                            c.setName(pushServerID);
                            try {
                                psid = db.mqttMessageDao().insertCode(c);
                            } catch (SQLiteConstraintException e) {
                                // rare case: sync messages has just inserted this pushServerID
                                Log.d(TAG, "insert pushserver id into code table: ", e);
                                // reread
                                psid = db.mqttMessageDao().getCode(pushServerID);
                            }
                        // Log.d(TAG, " (before null) code: " + psCode);
                        }
                        Long accountID = dao.getCode(mqttAccount);
                        if (accountID == null) {
                            Code c = new Code();
                            c.setName(mqttAccount);
                            try {
                                accountID = db.mqttMessageDao().insertCode(c);
                            } catch (SQLiteConstraintException e) {
                                // rare case: sync messages has just inserted this accountname
                                Log.d(TAG, "insert accountname into code table: ", e);
                                accountID = db.mqttMessageDao().getCode(mqttAccount);
                            }
                        // Log.d(TAG, " (before null) mqttAccountCode: " + mqttAccountCode);
                        }
                        File msgs = new File(app.getFilesDir(), "mc_" + psid + "_" + accountID + ".tmp");
                        File msgsD = new File(app.getFilesDir(), "mc_" + psid + "_" + accountID + ".json");
                        BufferedWriter bufferedWriter = null;
                        JsonWriter jsonWriter = null;
                        boolean writeCompleted = false;
                        synchronized (mFileLock) {
                            try {
                                bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(msgs), "UTF-8"));
                                jsonWriter = new JsonWriter(bufferedWriter);
                                jsonWriter.beginArray();
                                for (Message m : msgArr) {
                                    jsonWriter.beginObject();
                                    jsonWriter.name("status");
                                    jsonWriter.value(m.status);
                                    jsonWriter.name("received");
                                    jsonWriter.value(m.getWhen());
                                    jsonWriter.name("seqno");
                                    jsonWriter.value(m.getSeqno());
                                    jsonWriter.name("topic");
                                    jsonWriter.value(m.getTopic() == null ? "" : m.getTopic());
                                    jsonWriter.name("payload");
                                    jsonWriter.value(Base64.encodeToString(m.getPayload(), Base64.DEFAULT));
                                    jsonWriter.endObject();
                                }
                                jsonWriter.endArray();
                                writeCompleted = true;
                            } finally {
                                if (jsonWriter != null) {
                                    jsonWriter.close();
                                }
                                if (writeCompleted) {
                                    msgs.renameTo(msgsD);
                                }
                                msgs.delete();
                            }
                        }
                    } catch (Exception e) {
                        Log.e(TAG, "Error saving messages for account: " + pushServerID + ", " + mqttAccount, e);
                    }
                }
            });
        }
    }
}
Also used : ArrayList(java.util.ArrayList) Code(de.radioshuttle.db.Code) JsonWriter(android.util.JsonWriter) SQLiteConstraintException(android.database.sqlite.SQLiteConstraintException) BufferedWriter(java.io.BufferedWriter) FileOutputStream(java.io.FileOutputStream) MqttMessageDao(de.radioshuttle.db.MqttMessageDao) SQLiteConstraintException(android.database.sqlite.SQLiteConstraintException) AppDatabase(de.radioshuttle.db.AppDatabase) OutputStreamWriter(java.io.OutputStreamWriter) Application(android.app.Application) File(java.io.File)

Example 2 with JsonWriter

use of android.util.JsonWriter in project platform_packages_inputmethods_LatinIME by GrapheneOS.

the class JsonUtils method listToJsonStr.

public static String listToJsonStr(final List<Object> list) {
    if (list == null || list.isEmpty()) {
        return EMPTY_STRING;
    }
    final StringWriter sw = new StringWriter();
    final JsonWriter writer = new JsonWriter(sw);
    try {
        writer.beginArray();
        for (final Object o : list) {
            writer.beginObject();
            if (o instanceof Integer) {
                writer.name(INTEGER_CLASS_NAME).value((Integer) o);
            } else if (o instanceof String) {
                writer.name(STRING_CLASS_NAME).value((String) o);
            }
            writer.endObject();
        }
        writer.endArray();
        return sw.toString();
    } catch (final IOException e) {
    } finally {
        close(writer);
    }
    return EMPTY_STRING;
}
Also used : StringWriter(java.io.StringWriter) IOException(java.io.IOException) JsonWriter(android.util.JsonWriter)

Example 3 with JsonWriter

use of android.util.JsonWriter in project NClientV2 by Dar9586.

the class GeneralPreferenceFragment method getDataSettings.

private String getDataSettings(Context context) throws IOException {
    String[] names = new String[] { "Settings", "ScrapedTags" };
    StringWriter sw = new StringWriter();
    JsonWriter writer = new JsonWriter(sw);
    writer.setIndent("\t");
    writer.beginObject();
    for (String name : names) processSharedFromName(writer, context, name);
    writer.endObject();
    writer.flush();
    String settings = sw.toString();
    writer.close();
    LogUtility.d(settings);
    return settings;
}
Also used : StringWriter(java.io.StringWriter) JsonWriter(android.util.JsonWriter)

Example 4 with JsonWriter

use of android.util.JsonWriter in project NClientV2 by Dar9586.

the class TagsAdapter method onlineTagUpdate.

private void onlineTagUpdate(final Tag tag, final boolean add, final ImageView imgView) throws IOException {
    if (!Login.isLogged() || Login.getUser() == null)
        return;
    StringWriter sw = new StringWriter();
    JsonWriter jw = new JsonWriter(sw);
    jw.beginObject().name("added").beginArray();
    if (add)
        writeTag(jw, tag);
    jw.endArray().name("removed").beginArray();
    if (!add)
        writeTag(jw, tag);
    jw.endArray().endObject();
    final String url = String.format(Locale.US, Utility.getBaseUrl() + "users/%d/%s/blacklist", Login.getUser().getId(), Login.getUser().getCodename());
    final RequestBody ss = RequestBody.create(MediaType.get("application/json"), sw.toString());
    new AuthRequest(url, url, new Callback() {

        @Override
        public void onFailure(@NonNull Call call, @NonNull IOException e) {
        }

        @Override
        public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
            if (response.body().string().contains("ok")) {
                if (add)
                    Login.addOnlineTag(tag);
                else
                    Login.removeOnlineTag(tag);
                if (tagMode == TagMode.ONLINE)
                    updateLogo(imgView, add ? TagStatus.AVOIDED : TagStatus.DEFAULT);
            }
        }
    }).setMethod("POST", ss).start();
}
Also used : Response(okhttp3.Response) AuthRequest(com.dar.nclientv2.settings.AuthRequest) Call(okhttp3.Call) Callback(okhttp3.Callback) StringWriter(java.io.StringWriter) IOException(java.io.IOException) JsonWriter(android.util.JsonWriter) RequestBody(okhttp3.RequestBody)

Example 5 with JsonWriter

use of android.util.JsonWriter in project NClientV2 by Dar9586.

the class Exporter method dumpDB.

private static void dumpDB(OutputStream stream) throws IOException {
    SQLiteDatabase db = Database.getDatabase();
    JsonWriter writer = new JsonWriter(new OutputStreamWriter(stream));
    writer.beginObject();
    for (String s : SCHEMAS) {
        Cursor cur = db.query(s, null, null, null, null, null, null);
        writer.name(s).beginArray();
        if (cur.moveToFirst()) {
            do {
                writer.beginObject();
                for (int i = 0; i < cur.getColumnCount(); i++) {
                    writer.name(cur.getColumnName(i));
                    if (cur.isNull(i)) {
                        writer.nullValue();
                    } else {
                        switch(cur.getType(i)) {
                            case Cursor.FIELD_TYPE_INTEGER:
                                writer.value(cur.getLong(i));
                                break;
                            case Cursor.FIELD_TYPE_FLOAT:
                                writer.value(cur.getDouble(i));
                                break;
                            case Cursor.FIELD_TYPE_STRING:
                                writer.value(cur.getString(i));
                                break;
                            case Cursor.FIELD_TYPE_BLOB:
                            case Cursor.FIELD_TYPE_NULL:
                                break;
                        }
                    }
                }
                writer.endObject();
            } while (cur.moveToNext());
        }
        writer.endArray();
        cur.close();
    }
    writer.endObject();
    writer.flush();
}
Also used : SQLiteDatabase(android.database.sqlite.SQLiteDatabase) OutputStreamWriter(java.io.OutputStreamWriter) Cursor(android.database.Cursor) JsonWriter(android.util.JsonWriter)

Aggregations

JsonWriter (android.util.JsonWriter)30 IOException (java.io.IOException)11 StringWriter (java.io.StringWriter)11 OutputStreamWriter (java.io.OutputStreamWriter)9 FileOutputStream (java.io.FileOutputStream)4 ArrayList (java.util.ArrayList)4 File (java.io.File)3 List (java.util.List)3 SharedPreferences (android.content.SharedPreferences)2 TargetApi (android.annotation.TargetApi)1 Application (android.app.Application)1 PackageInfo (android.content.pm.PackageInfo)1 PackageManager (android.content.pm.PackageManager)1 ColorStateList (android.content.res.ColorStateList)1 Cursor (android.database.Cursor)1 SQLiteConstraintException (android.database.sqlite.SQLiteConstraintException)1 SQLiteDatabase (android.database.sqlite.SQLiteDatabase)1 Paint (android.graphics.Paint)1 Uri (android.net.Uri)1 AuthRequest (com.dar.nclientv2.settings.AuthRequest)1