io.paperdb.Paper Java Examples

The following examples show how to use io.paperdb.Paper. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: App.java    From NMSAlphabetAndroidApp with MIT License 6 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    CustomActivityOnCrash.install(this);
    EventBus.getDefault().register(this);
    EasyImage.configuration(this)
            .saveInRootPicturesDirectory()
            .setImagesFolderName(getString(R.string.app_name));
    Nammu.init(this);
    Paper.init(this);
    Typekit.getInstance()
            .addNormal(Typekit.createFromAsset(this, "fonts/LatoLatin-Regular.ttf"))
            .addBold(Typekit.createFromAsset(this, "fonts/LatoLatin-Bold.ttf"))
            .addItalic(Typekit.createFromAsset(this, "fonts/LatoLatin-Italic.ttf"))
            .addBoldItalic(Typekit.createFromAsset(this, "fonts/LatoLatin-BoldItalic.ttf"))
            .addCustom1(Typekit.createFromAsset(this, "fonts/Geomanist-Regular.otf"))
            .addCustom2(Typekit.createFromAsset(this, "fonts/Handlee-Regular.ttf"));

    initFabric();
    initParse();
}
 
Example #2
Source File: MultiThreadTest.java    From Paper with Apache License 2.0 5 votes vote down vote up
@NonNull
private CountDownLatch startWritingLargeDataSetInSeparateThread(
        @SuppressWarnings("SameParameterValue") final String key) throws InterruptedException {
    final CountDownLatch writeStartLatch = new CountDownLatch(1);
    final CountDownLatch writeFinishLatch = new CountDownLatch(1);
    new Thread() {
        final List<Person> dataset = TestDataGenerator.genPersonList(10000);

        @Override
        public void run() {
            Log.d(TAG, "write '" + key + "': start");
            writeStartLatch.countDown();
            Paper.book().write(key, dataset);
            Log.d(TAG, "write '" + key + "': finish");
            writeFinishLatch.countDown();
        }
    }.start();
    writeStartLatch.await(5, TimeUnit.SECONDS);
    // A small delay is required to let writer thread start writing data and acquire a lock
    Thread.sleep(100);
    return writeFinishLatch;
}
 
Example #3
Source File: ReadBenchmark.java    From Paper with Apache License 2.0 5 votes vote down vote up
@Test
public void readLargeList() throws InterruptedException {
    List<Person> list = TestDataGenerator.genPersonList(50000);
    Paper.book().write("list1", list);
    Paper.book().write("list2", list);
    Paper.book().write("list3", list);

    long average = runManyTimes(3, new Runnable() {
        @Override
        public void run() {
            ExecutorService executor = Executors.newFixedThreadPool(3);
            executor.execute(readRunnable("list1"));
            executor.execute(readRunnable("list2"));
            executor.execute(readRunnable("list3"));
            executor.shutdown();
            boolean finished = false;
            try {
                finished = executor.awaitTermination(40, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
            }
            assertTrue(finished);
        }
    });


    Log.d(TAG, "read 3 large lists in 3 threads: " + average + "ms");
}
 
Example #4
Source File: ReadBenchmark.java    From Paper with Apache License 2.0 5 votes vote down vote up
@Test
public void readSmallList() throws InterruptedException {
    List<Person> list = TestDataGenerator.genPersonList(1000);
    Paper.book().write("list1", list);
    Paper.book().write("list2", list);
    Paper.book().write("list3", list);

    long average = runManyTimes(10, new Runnable() {
        @Override
        public void run() {
            ExecutorService executor = Executors.newFixedThreadPool(3);
            executor.execute(readRunnable("list1"));
            executor.execute(readRunnable("list2"));
            executor.execute(readRunnable("list3"));
            executor.shutdown();
            boolean finished = false;
            try {
                finished = executor.awaitTermination(10, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
            }
            assertTrue(finished);
        }
    });


    Log.d(TAG, "read 3 small lists in 3 threads: " + average + "ms");
}
 
Example #5
Source File: MultiThreadTest.java    From Paper with Apache License 2.0 5 votes vote down vote up
@Test
public void read_write_different_keys() throws InterruptedException {
    // Primary write something else
    Paper.book().write("city", "Victoria");

    // Start writing large dataset
    CountDownLatch writeEndLatch = startWritingLargeDataSetInSeparateThread("dataset");

    Log.d(TAG, "read other key: start");
    // Read for different key 'city' should be locked by writing other key 'dataset'
    assertEquals("Victoria", Paper.book().read("city"));
    assertEquals(1, writeEndLatch.getCount());
    writeEndLatch.await(5, TimeUnit.SECONDS);
    assertEquals(10000, Paper.book().<List<Person>>read("dataset").size());
    Log.d(TAG, "read other key: finish");
}
 
Example #6
Source File: DataTest.java    From Paper with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutGetList() {
    final List<Person> inserted = genPersonList(10000);
    Paper.put("persons", inserted);
    List<Person> persons = Paper.get("persons");
    assertThat(persons).isEqualTo(inserted);
}
 
Example #7
Source File: DataTest.java    From Paper with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutMap() {
    final Map<Integer, Person> inserted = genPersonMap(10000);
    Paper.put("persons", inserted);

    final Map<Integer, Person> personMap = Paper.get("persons");
    assertThat(personMap).isEqualTo(inserted);
}
 
Example #8
Source File: PaperDataSaver.java    From Android-NoSql with Apache License 2.0 5 votes vote down vote up
@Override
public void remove(String startingPath) {
    final Book bookNodes = Paper.book(NODES);
    final Book bookValues = Paper.book(VALUES);
    final Set<String> nodes = getNodes();
    final Set<String> nodesToKeep = new HashSet<>();
    //update values
    for (String node : nodes) {
        if(node.startsWith(startingPath)) {
            bookValues.delete(formatPath(node));
        } else {
            nodesToKeep.add(node);
        }
    }
    bookNodes.write(NODES, nodesToKeep);
}
 
Example #9
Source File: DataTest.java    From Paper with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutPOJO() {
    final Person person = genPerson(new Person(), 1);
    Paper.put("profile", person);

    final Person savedPerson = Paper.get("profile");
    assertThat(savedPerson).isEqualTo(person);
    assertThat(savedPerson).isNotSameAs(person);
}
 
Example #10
Source File: MainActivity.java    From Paper with Apache License 2.0 5 votes vote down vote up
@Override
protected ArrayList<AbstractValueHolder> doInBackground(Void... voids) {
    LongHolder o1 = Paper.book().read("o1", new LongHolder(-1L));
    LongListHolder o2 = Paper.book().read("o2",
            new LongListHolder(Collections.singletonList(-1L)));
    ArrayList<AbstractValueHolder> result = new ArrayList<>();
    result.add(o1);
    result.add(o2);
    return result;
}
 
Example #11
Source File: PaperDataSaver.java    From Android-NoSql with Apache License 2.0 5 votes vote down vote up
@Override
public void saveValue(String completePath, Object value) {

    completePath = formatPath(completePath);

    final Book book = Paper.book(VALUES);
    if(value instanceof Integer) {
        book.write(completePath, (Integer) value);
    } else if(value instanceof Float) {
        book.write(completePath, (Float) value);
    } else if(value instanceof Boolean) {
        book.write(completePath, (Boolean) value);
    } else if(value instanceof Long) {
        book.write(completePath, (Long) value);
    } else {
        book.write(completePath, String.valueOf(value));
    }
}
 
Example #12
Source File: MainActivity.java    From Paper with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("SameParameterValue")
private void writeReadDestroy(final String key, final int iterations) {
    new Thread() {
        @Override
        public void run() {
            for (int i = 0; i < iterations; i++) {
                Paper.book().write(key, "key:" + key + " iteration#" + i);
                Log.d(Thread.currentThread().getName(), "All keys:" + Paper.book().getAllKeys().toString());
                Log.d(Thread.currentThread().getName(), "read key:" + key + "=" + Paper.book().<String>read(key));
                // This caused the issue on multi-thread paper db dir creation
                Paper.book().destroy();
            }
        }
    }.start();
}
 
Example #13
Source File: App.java    From ONE-Unofficial with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    Paper.init(this);

    CrashHandler.getInstance().init(this);
    ImageUtil.init(this);
    NetworkUtil.init(this);
    ConfigUtil.init(this);
    TextToast.init(this);

    //Facebook分享初始化
    FacebookSdk.sdkInitialize(getApplicationContext());
    //友盟意见反馈初始化
    FeedbackPush.getInstance(this).init(false);
}
 
Example #14
Source File: PaperDeprecatedAPITest.java    From Paper with Apache License 2.0 5 votes vote down vote up
@Test
public void testDelete() throws Exception {
    Paper.put("persons", TestDataGenerator.genPersonList(10));
    assertTrue(Paper.exist("persons"));
    Paper.delete("persons");
    assertFalse(Paper.exist("persons"));
}
 
Example #15
Source File: LeadersListFragment.java    From 4pdaClient-plus with Apache License 2.0 5 votes vote down vote up
@Override
public void loadCache() {
    mCacheList.clear();
    ArrayList<LeadUser> items = Paper.book().read(getListName(), new ArrayList<>());
    HashMap<String, ExpandableGroup> groups = new HashMap<>();
    for (LeadUser leadUser : items) {
        leadUser.fillFromCache();

        if (!groups.containsKey(leadUser.getGroup())) {
            groups.put(leadUser.getGroup(), new ExpandableGroup(leadUser.getGroup()));
            mCacheList.add(groups.get(leadUser.getGroup()));
        }

    }
}
 
Example #16
Source File: resend_service.java    From telegram-sms with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void network_progress_handle(String message, String chat_id, OkHttpClient okhttp_client) {
    message_json request_body = new message_json();
    request_body.chat_id = chat_id;
    request_body.text = message;
    if (message.contains("<code>") && message.contains("</code>")) {
        request_body.parse_mode = "html";
    }
    String request_body_json = new Gson().toJson(request_body);
    RequestBody body = RequestBody.create(request_body_json, public_func.JSON);
    Request request_obj = new Request.Builder().url(request_uri).method("POST", body).build();
    Call call = okhttp_client.newCall(request_obj);
    try {
        Response response = call.execute();
        if (response.code() == 200) {
            ArrayList<String> resend_list_local = Paper.book().read(table_name, new ArrayList<>());
            resend_list_local.remove(message);
            Paper.book().write(table_name, resend_list_local);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #17
Source File: HomeContentFragment.java    From ONE-Unofficial with Apache License 2.0 5 votes vote down vote up
@Override
public void onDataOk(String url, String data) {
    switch (url) {
        case Api.URL_HOME:
            Home home = JsonUtil.getEntity(data, Home.class);
            refreshUI(home);
            if (home != null) {
                Paper.book().write(Constants.TAG_HOME + curDate, home);
            }
            HomeFragment.getInstance().pager.onRefreshComplete();
            break;
        case Api.URL_LIKE_OR_CANCLELIKE:
            try {
                JSONObject jsonObject = new JSONObject(data);
                int likeCount = jsonObject.optInt("strPraisednumber");
                //若实际的喜欢数量与LikeView自增的结果值不同,显示实际的数量
                if (likeCount != lvSaying.getLikeCount()) {
                    lvSaying.setText(likeCount + "");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            break;
    }
}
 
Example #18
Source File: PaperDeprecatedAPITest.java    From Paper with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutGetNormalAfterReinit() {
    Paper.put("city", "Lund");
    String val = Paper.get("city", "default");
    Paper.init(getTargetContext());// Reinit Paper instance
    assertThat(val).isEqualTo("Lund");
}
 
Example #19
Source File: battery_service.java    From telegram-sms with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    context = getApplicationContext();
    Paper.init(context);
    SharedPreferences sharedPreferences = context.getSharedPreferences("data", MODE_PRIVATE);
    chat_id = sharedPreferences.getString("chat_id", "");
    bot_token = sharedPreferences.getString("bot_token", "");
    doh_switch = sharedPreferences.getBoolean("doh_switch", true);
    final boolean charger_status = sharedPreferences.getBoolean("charger_status", false);
    battery_receiver = new battery_receiver();
    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_BATTERY_OKAY);
    filter.addAction(Intent.ACTION_BATTERY_LOW);
    filter.addAction(public_func.BROADCAST_STOP_SERVICE);
    if (charger_status) {
        filter.addAction(Intent.ACTION_POWER_CONNECTED);
        filter.addAction(Intent.ACTION_POWER_DISCONNECTED);
    }
    registerReceiver(battery_receiver, filter);

}
 
Example #20
Source File: Benchmark.java    From Paper with Apache License 2.0 5 votes vote down vote up
@Test
public void testWrite500Contacts() throws Exception {
    final List<Person> contacts = TestDataGenerator.genPersonList(500);
    Paper.init(getTargetContext());
    Paper.book().destroy();
    long paperTime = runTest(new PaperWriteContactsTest(), contacts, REPEAT_COUNT);

    Hawk.init(getTargetContext());
    Hawk.clear();
    long hawkTime = runTest(new HawkWriteContactsTest(), contacts, REPEAT_COUNT);

    printResults("Write 500 contacts", paperTime, hawkTime);
}
 
Example #21
Source File: Benchmark.java    From Paper with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadWrite500Contacts() throws Exception {
    final List<Person> contacts = TestDataGenerator.genPersonList(500);
    Paper.init(getTargetContext());
    Paper.book().destroy();
    long paperTime = runTest(new PaperReadWriteContactsTest(), contacts, REPEAT_COUNT);

    Hawk.init(getTargetContext());
    Hawk.clear();
    long hawkTime = runTest(new HawkReadWriteContactsTest(), contacts, REPEAT_COUNT);

    final List<PersonArg> contactsArg = TestDataGenerator.genPersonArgList(500);
    Paper.init(getTargetContext());
    Paper.book().destroy();
    long paperArg = runTest(new PaperReadWriteContactsArgTest(), contactsArg, REPEAT_COUNT);

    printResults("Read/write 500 contacts", paperTime, hawkTime, paperArg);
}
 
Example #22
Source File: PaperDeprecatedAPITest.java    From Paper with Apache License 2.0 4 votes vote down vote up
@Test
public void testPaperExist() throws Exception {
    assertFalse(Paper.book().exist("persons"));
    Paper.book().write("persons", TestDataGenerator.genPersonList(10));
    assertTrue(Paper.book().exist("persons"));
}
 
Example #23
Source File: PaperDeprecatedAPITest.java    From Paper with Apache License 2.0 4 votes vote down vote up
@Test(expected = PaperDbException.class)
public void testInvalidKeyNameBackslash() {
    Paper.put("city/ads", "Lund");
    assertThat(Paper.get("city/ads")).isEqualTo("Lund");
}
 
Example #24
Source File: Benchmark.java    From Paper with Apache License 2.0 4 votes vote down vote up
@Override
public void run(int i, List<Person> extra) {
    String key = "contacts" + i;
    Paper.book().<List<Person>>read(key);
}
 
Example #25
Source File: ReadBenchmark.java    From Paper with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
    Paper.init(getTargetContext());
    Paper.book().destroy();
}
 
Example #26
Source File: BaseLoaderListFragment.java    From 4pdaClient-plus with Apache License 2.0 4 votes vote down vote up
private ArrayList<IListItem> loadCache() {
    if (!TextUtils.isEmpty(getListName()))
        return Paper.book().read(getListName(), new ArrayList<>());
    else
        return new ArrayList<>();
}
 
Example #27
Source File: ArticleContentFragment.java    From ONE-Unofficial with Apache License 2.0 4 votes vote down vote up
@Override
public void onRestoreData(String url) {
    if (url.equals(Api.URL_ARTICLE)) {
        Article article = Paper.book().read(Constants.TAG_ARTICLE + curDate, null);
        refreshUI(article);
        ArticleFragment.getInstance().pager.onRefreshComplete();
    }
}
 
Example #28
Source File: ArticleContentFragment.java    From ONE-Unofficial with Apache License 2.0 4 votes vote down vote up
@Override
public void onDataOk(String url, String data) {
    switch (url) {
        case Api.URL_ARTICLE:
            Article article = JsonUtil.getEntity(data, Article.class);
            //刷新显示界面
            refreshUI(article);
            //写入缓存
            if (article != null) {
                Paper.book().write(Constants.TAG_ARTICLE + curDate, article);
            }
            ArticleFragment.getInstance().pager.onRefreshComplete();
            break;
        case Api.URL_LIKE_OR_CANCLELIKE:
            try {
                JSONObject jsonObject = new JSONObject(data);
                int likeCount = jsonObject.optInt("strPraisednumber");
                //若实际的喜欢数量与LikeView自增的结果值不同,显示实际的数量
                if (likeCount != lvArticle.getLikeCount()) {
                    lvArticle.setText(likeCount + "");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            break;
    }
}
 
Example #29
Source File: QuestionContentFragment.java    From ONE-Unofficial with Apache License 2.0 4 votes vote down vote up
@Override
public void onRestoreData(String url) {
    if (url.equals(Api.URL_QUESTION)) {
        Question question = Paper.book().read(Constants.TAG_QUESTION + curDate, null);
        refreshUI(question);
        QuestionFragment.getInstance().pager.onRefreshComplete();
    }
}
 
Example #30
Source File: MultiThreadTest.java    From Paper with Apache License 2.0 4 votes vote down vote up
private Runnable getSelectRunnable() {
    return new Runnable() {
        @Override
        public void run() {
            Paper.book().read("persons");
        }
    };
}