com.couchbase.lite.CouchbaseLiteException Java Examples

The following examples show how to use com.couchbase.lite.CouchbaseLiteException. 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: TunesPerfTest.java    From couchbase-lite-android with Apache License 2.0 6 votes vote down vote up
protected void createArtistsIndex() {
    System.err.println("Indexing artists...");
    _indexArtistsBench.start();

    Collation.Unicode cd = Collation.unicode().locale(null).ignoreCase(true).ignoreAccents(true);
    Expression artist = Expression.property("Artist").collate(cd);
    Expression comp   = Expression.property("Compilation");
    ValueIndex index = IndexBuilder.valueIndex(ValueIndexItem.expression(artist), ValueIndexItem.expression(comp));
    try {
        db.createIndex("byArtist", index);
    } catch (CouchbaseLiteException e) {
        e.printStackTrace();
    }

    double t = _indexArtistsBench.stop();
    System.err.println(String.format("Indexed artists in %.06f sec", t));
}
 
Example #2
Source File: QueryPerfTest.java    From couchbase-lite-android with Apache License 2.0 6 votes vote down vote up
int query() {
    int count = 0;
    bench.start();
    Query q = QueryBuilder.select(SelectResult.expression(Meta.id))
            .from(DataSource.database(db));
    ResultSet rs = null;
    try {
        rs = q.execute();
    } catch (CouchbaseLiteException e) {
        e.printStackTrace();
    }
    for (Result r : rs) {
        count++;
    }
    double t = bench.stop();
    System.err.print(String.format("Query %d documents in %.06f sec\n", count, t));
    return count;
}
 
Example #3
Source File: PlacesAdapter.java    From mini-hacks with MIT License 6 votes vote down vote up
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    Place place = dataSet.get(position);

    holder.restaurantName.setText(place.getName());
    holder.restaurantText.setText(place.getAddress());

    Document document = database.getDocument(place.getId());
    Attachment attachment = document.getCurrentRevision().getAttachment("photo");
    if (attachment != null) {
        InputStream is = null;
        try {
            is = attachment.getContent();
        } catch (CouchbaseLiteException e) {
            e.printStackTrace();
        }
        Drawable drawable = Drawable.createFromStream(is, "photo");
        holder.restaurantImage.setImageDrawable(drawable);
    }
}
 
Example #4
Source File: MainActivity.java    From mini-hacks with MIT License 6 votes vote down vote up
private void setupQuery() {
    Database database = null;
    try {
        database = manager.getExistingDatabase("todo");
    } catch (CouchbaseLiteException e) {
        e.printStackTrace();
    }
    if (database != null) {
        LiveQuery liveQuery = database.createAllDocumentsQuery().toLiveQuery();
        liveQuery.addChangeListener(new LiveQuery.ChangeListener() {
            @Override
            public void changed(final LiveQuery.ChangeEvent event) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        docCountLabel.setText(String.valueOf(event.getRows().getCount()));
                    }
                });
            }
        });
        liveQuery.start();
    }
}
 
Example #5
Source File: SyncManager.java    From mini-hacks with MIT License 6 votes vote down vote up
private void queryCities() {
    final Query query = database.getView(CITIES_VIEW).createQuery();
    query.setGroupLevel(1);

    LiveQuery liveQuery = query.toLiveQuery();
    liveQuery.addChangeListener(new LiveQuery.ChangeListener() {
        @Override
        public void changed(LiveQuery.ChangeEvent event) {
            try {
                QueryEnumerator enumeration = query.run();
                for (QueryRow row : enumeration) {
                    Log.d("CityExplorer", "Row is " + row.getValue() + " and key " + row.getKey());
                }

            } catch (CouchbaseLiteException e) {
                e.printStackTrace();
            }
        }
    });

    liveQuery.start();
}
 
Example #6
Source File: RatingsAdapter.java    From mini-hacks with MIT License 6 votes vote down vote up
/**
 * Use the position to get the corresponding query row and populate the ViewHolder that
 * was created above.
 * @param holder
 * @param position
 */
@Override
public void onBindViewHolder(ViewHolder holder, int position) {

    final QueryRow row = (QueryRow) getItem(position);

    /** TODO: This is a hack to populate the result of the ratings or conflicts view query,
     ** have two different recycler view adapters instead. */
    holder.ratingValue.setText(String.valueOf(row.getKey()));
    if (row.getValue() == null) {
        try {
            int conflicts = row.getDocument().getConflictingRevisions().size();
            holder.totalRatings.setText(String.valueOf(conflicts - 1));
        } catch (CouchbaseLiteException e) {
            e.printStackTrace();
        }

    } else {
        holder.totalRatings.setText(String.valueOf(row.getValue()));
    }
}
 
Example #7
Source File: TestUtils.java    From couchbase-lite-java with Apache License 2.0 5 votes vote down vote up
public static void assertThrowsCBL(String domain, int code, Fn.TaskThrows<CouchbaseLiteException> task) {
    try {
        task.run();
        fail("Expected a CouchbaseLiteException");
    }
    catch (CouchbaseLiteException e) {
        assertEquals(code, e.getCode());
        assertEquals(domain, e.getDomain());
    }
}
 
Example #8
Source File: C4Key.java    From couchbase-lite-java with Apache License 2.0 5 votes vote down vote up
@NonNull
public static byte[] getCoreKey(@NonNull String password) throws CouchbaseLiteException {
    final byte[] key = C4Key.deriveKeyFromPassword(password, C4Constants.EncryptionAlgorithm.AES256);
    if (key != null) { return key; }

    throw new CouchbaseLiteException("Could not generate key", CBLError.Domain.CBLITE, CBLError.Code.CRYPTO);
}
 
Example #9
Source File: C4PathsQueryTest.java    From couchbase-lite-java with Apache License 2.0 5 votes vote down vote up
@Before
@Override
public void setUp() throws CouchbaseLiteException {
    super.setUp();

    importJSONLinesSafely("paths.json");
}
 
Example #10
Source File: C4ObserverTest.java    From couchbase-lite-java with Apache License 2.0 5 votes vote down vote up
@Before
@Override
public void setUp() throws CouchbaseLiteException {
    super.setUp();

    dbCallbackCalls = new AtomicInteger(0);
}
 
Example #11
Source File: C4AllDocsPerformanceTest.java    From couchbase-lite-java with Apache License 2.0 5 votes vote down vote up
@Before
@Override
public void setUp() throws CouchbaseLiteException {
    super.setUp();

    char[] chars = new char[DOC_SIZE];
    Arrays.fill(chars, 'a');
    final String content = new String(chars);

    boolean commit = false;
    try {
        c4Database.beginTransaction();
        try {
            Random random = new Random();
            for (int i = 0; i < DOC_NUM; i++) {
                String docID = String.format(
                    "doc-%08x-%08x-%08x-%04x",
                    random.nextLong(),
                    random.nextLong(),
                    random.nextLong(),
                    i);
                String json = String.format("{\"content\":\"%s\"}", content);
                List<String> list = new ArrayList<>();
                list.add("1-deadbeefcafebabe80081e50");
                String[] history = list.toArray(new String[0]);
                C4Document doc = c4Database.put(json2fleece(json), docID, 0, true, false, history, true, 0, 0);
                assertNotNull(doc);
                doc.free();
            }
            commit = true;
        }
        finally {
            c4Database.endTransaction(commit);
        }
    }
    catch (LiteCoreException e) { throw CBLStatus.convertException(e); }

    assertEquals(DOC_NUM, c4Database.getDocumentCount());
}
 
Example #12
Source File: C4QueryTest.java    From couchbase-lite-java with Apache License 2.0 5 votes vote down vote up
@Before
@Override
public void setUp() throws CouchbaseLiteException {
    super.setUp();

    importJSONLinesSafely("names_100.json");
}
 
Example #13
Source File: C4MutableFleeceTest.java    From couchbase-lite-java with Apache License 2.0 5 votes vote down vote up
@Before
@Override
public void setUp() throws CouchbaseLiteException {
    super.setUp();

    delegate = MValue.getRegisteredDelegate();
    MValue.registerDelegate(new MValueDelegate());
}
 
Example #14
Source File: PerfTest.java    From couchbase-lite-android with Apache License 2.0 5 votes vote down vote up
protected void openDB() {
    try {
        db = new Database(dbName, dbConfig);
    } catch (CouchbaseLiteException e) {
        e.printStackTrace();
    }
}
 
Example #15
Source File: PerfTest.java    From couchbase-lite-android with Apache License 2.0 5 votes vote down vote up
protected Database closeDB(Database _db) {
    if (_db != null) {
        try {
            _db.close();
        } catch (CouchbaseLiteException e) {
            e.printStackTrace();
        }
    }
    return null;
}
 
Example #16
Source File: PerfTest.java    From couchbase-lite-android with Apache License 2.0 5 votes vote down vote up
protected void eraseDB() {
    closeDB();
    try {
        Database.delete(dbName, new File(dbConfig.getDirectory()));
    } catch (CouchbaseLiteException e) {
        e.printStackTrace();
    }
    openDB();
}
 
Example #17
Source File: DocPerfTest.java    From couchbase-lite-android with Apache License 2.0 5 votes vote down vote up
void updateDocWithGetDocument(MutableDocument doc, final int revisions) throws CouchbaseLiteException {
    for (int i = 0; i < revisions; i++) {
        doc.setValue("count", i);
        db.save(doc);
        doc = db.getDocument("doc").toMutable();
    }
}
 
Example #18
Source File: TunesPerfTest.java    From couchbase-lite-android with Apache License 2.0 5 votes vote down vote up
List<String> collectQueryResults(Query query) throws CouchbaseLiteException {
    List<String> results = new ArrayList<>();
    ResultSet rs = query.execute();
    for(Result r : rs){
        results.add(r.getString(0));
    }
    return results;
}
 
Example #19
Source File: C4Key.java    From couchbase-lite-java with Apache License 2.0 5 votes vote down vote up
@NonNull
public static byte[] getPbkdf2Key(@NonNull String password) throws CouchbaseLiteException {
    final byte[] key = C4Key.pbkdf2(
        password,
        DEFAULT_PBKDF2_KEY_SALT.getBytes(StandardCharsets.UTF_8),
        DEFAULT_PBKDF2_KEY_ROUNDS,
        C4Constants.EncryptionKeySize.AES256);
    if (key != null) { return key; }

    throw new CouchbaseLiteException("Could not generate key", CBLError.Domain.CBLITE, CBLError.Code.CRYPTO);
}
 
Example #20
Source File: PerfTestCouchbase.java    From android-database-performance with Apache License 2.0 5 votes vote down vote up
private void deleteAll() throws CouchbaseLiteException {
    // query all documents, mark them as deleted
    Query query = database.createAllDocumentsQuery();
    QueryEnumerator result = query.run();
    database.beginTransaction();
    while (result.hasNext()) {
        QueryRow row = result.next();
        row.getDocument().purge();
    }
    database.endTransaction(true);
}
 
Example #21
Source File: PerfTestCouchbase.java    From android-database-performance with Apache License 2.0 5 votes vote down vote up
private Map<String, Object> createDocumentMap(int seed) throws CouchbaseLiteException {
    Map<String, Object> map = new HashMap<>();
    map.put("type", DOC_TYPE);
    map.put("simpleBoolean", true);
    map.put("simpleByte", seed & 0xff);
    map.put("simpleShort", seed & 0xffff);
    map.put("simpleInt", seed);
    map.put("simpleLong", Long.MAX_VALUE - seed);
    map.put("simpleFloat", (float) (Math.PI * seed));
    map.put("simpleDouble", Math.E * seed);
    map.put("simpleString", "greenrobot greenDAO");
    byte[] bytes = { 42, -17, 23, 0, 127, -128 };
    map.put("simpleByteArray", bytes);
    return map;
}
 
Example #22
Source File: MainActivity.java    From mini-hacks with MIT License 5 votes vote down vote up
public void deletePlace(android.view.View view) {
    Log.d("", "delete me");
    adapter.dataSet.remove(2);
    try {
        database.getExistingDocument(adapter.dataSet.get(2).getId()).delete();
    } catch (CouchbaseLiteException e) {
        e.printStackTrace();
    }
    adapter.notifyItemRemoved(2);
}
 
Example #23
Source File: UniqueRatingFragment.java    From mini-hacks with MIT License 5 votes vote down vote up
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_unique, container, false);

    nameInput = (EditText) rootView.findViewById(R.id.nameInput);
    ratingBar = (RatingBar) rootView.findViewById(R.id.ratingBar);
    button = (Button) rootView.findViewById(R.id.button);

    database = ((MainActivity) getActivity()).storageManager.database;

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Document document = database.createDocument();

            Map<String, Object> properties = new HashMap<String, Object>();

            properties.put("name", nameInput.getText().toString());
            properties.put("rating", String.valueOf(ratingBar.getRating()));
            properties.put("type", "unique");

            try {
                document.putProperties(properties);
            } catch (CouchbaseLiteException e) {
                e.printStackTrace();
            }
        }
    });

    return rootView;
}
 
Example #24
Source File: RatingsAdapter.java    From mini-hacks with MIT License 5 votes vote down vote up
/**
 * Initialize parameters and starts listening on the Live Query for updates from the database.
 * @param context Android context in which the application is running
 * @param query LiveQuery to use in the adapter to populate the Recycler View
 */
public RatingsAdapter(Context context, final LiveQuery query, Database database) {
    this.context = context;
    this.query = query;

    /** Use the database change listener instead of live query listener because we want
     * to listen for conflicts as well
     */
    database.addChangeListener(new Database.ChangeListener() {
        @Override
        public void changed(final Database.ChangeEvent event) {
            ((Activity) RatingsAdapter.this.context).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    enumerator = query.getRows();
                    notifyDataSetChanged();
                }
            });
        }
    });
    query.start();
    ((Activity) RatingsAdapter.this.context).runOnUiThread(new Runnable() {
        @Override
        public void run() {
            try {
                enumerator = query.run();
            } catch (CouchbaseLiteException e) {
                e.printStackTrace();
            }
            notifyDataSetChanged();
        }
    });
}
 
Example #25
Source File: CBLStatus.java    From couchbase-lite-java with Apache License 2.0 5 votes vote down vote up
@SuppressFBWarnings("NP_NONNULL_PARAM_VIOLATION")
@NonNull
public static CouchbaseLiteException convertError(@Nullable C4Error c4err) {
    return (c4err == null)
        ? new CouchbaseLiteException()
        : convertException(c4err.getDomain(), c4err.getCode(), c4err.getInternalInfo());
}
 
Example #26
Source File: CBLStatus.java    From couchbase-lite-java with Apache License 2.0 5 votes vote down vote up
@SuppressFBWarnings("NP_NONNULL_PARAM_VIOLATION")
@NonNull
public static CouchbaseLiteException convertException(@Nullable LiteCoreException e) {
    return (e == null)
        ? new CouchbaseLiteException()
        : convertException(e.domain, e.code, null, e);
}
 
Example #27
Source File: CBLStatus.java    From couchbase-lite-java with Apache License 2.0 5 votes vote down vote up
public static CouchbaseLiteException convertException(
    int domainCode,
    int statusCode,
    @Nullable String msg,
    @Nullable Exception e) {
    int code = statusCode;

    String domain = CBLError.Domain.CBLITE;
    switch (domainCode) {
        case C4Constants.ErrorDomain.LITE_CORE:
            break;
        case C4Constants.ErrorDomain.POSIX:
            domain = "POSIXErrorDomain";
            break;
        case C4Constants.ErrorDomain.SQLITE:
            domain = CBLError.Domain.SQLITE;
            break;
        case C4Constants.ErrorDomain.FLEECE:
            domain = CBLError.Domain.FLEECE;
            break;
        case C4Constants.ErrorDomain.NETWORK:
            code += CBLError.Code.NETWORK_BASE;
            break;
        case C4Constants.ErrorDomain.WEB_SOCKET:
            code += CBLError.Code.HTTP_BASE;
            break;
        default:
            Log.w(
                LogDomain.DATABASE,
                "Unable to map C4Error(%d,%d) to an CouchbaseLiteException",
                domainCode,
                statusCode);
            break;
    }

    return new CouchbaseLiteException(msg, e, domain, code, null);
}
 
Example #28
Source File: C4NestedQueryTest.java    From couchbase-lite-java with Apache License 2.0 4 votes vote down vote up
@Before
@Override
public void setUp() throws CouchbaseLiteException {
    super.setUp();
    importJSONLinesSafely("nested.json");
}
 
Example #29
Source File: CBLStatus.java    From couchbase-lite-java with Apache License 2.0 4 votes vote down vote up
@NonNull
public static CouchbaseLiteException convertException(@Nullable LiteCoreException e, @NonNull String msg) {
    return (e == null)
        ? new CouchbaseLiteException(msg)
        : convertException(e.domain, e.code, msg, e);
}
 
Example #30
Source File: C4CollatedQueryTest.java    From couchbase-lite-java with Apache License 2.0 4 votes vote down vote up
@Before
@Override
public void setUp() throws CouchbaseLiteException {
    super.setUp();
    importJSONLinesSafely("iTunesMusicLibrary.json");
}