Java Code Examples for com.couchbase.lite.CouchbaseLiteException

The following examples show how to use com.couchbase.lite.CouchbaseLiteException. These examples are extracted from open source projects. 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 Project: mini-hacks   Source File: PlacesAdapter.java    License: 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 2
Source Project: mini-hacks   Source File: MainActivity.java    License: 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 3
Source Project: mini-hacks   Source File: SyncManager.java    License: 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 4
Source Project: mini-hacks   Source File: RatingsAdapter.java    License: 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 5
Source Project: couchbase-lite-android   Source File: QueryPerfTest.java    License: 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 6
Source Project: couchbase-lite-android   Source File: TunesPerfTest.java    License: 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 7
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 8
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 9
Source Project: mini-hacks   Source File: MainActivity.java    License: 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 10
Source Project: mini-hacks   Source File: UniqueRatingFragment.java    License: 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 11
Source Project: mini-hacks   Source File: RatingsAdapter.java    License: 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 12
Source Project: couchbase-lite-java   Source File: CBLStatus.java    License: 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 13
Source Project: couchbase-lite-java   Source File: CBLStatus.java    License: 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 14
Source Project: couchbase-lite-java   Source File: CBLStatus.java    License: 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 15
Source Project: couchbase-lite-java   Source File: C4Key.java    License: 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 16
Source Project: couchbase-lite-java   Source File: C4Key.java    License: 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 17
Source Project: couchbase-lite-java   Source File: TestUtils.java    License: 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 18
Source Project: couchbase-lite-java   Source File: C4PathsQueryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
@Override
public void setUp() throws CouchbaseLiteException {
    super.setUp();

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

    dbCallbackCalls = new AtomicInteger(0);
}
 
Example 20
@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 21
Source Project: couchbase-lite-java   Source File: C4QueryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
@Override
public void setUp() throws CouchbaseLiteException {
    super.setUp();

    importJSONLinesSafely("names_100.json");
}
 
Example 22
Source Project: couchbase-lite-java   Source File: C4MutableFleeceTest.java    License: 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 23
Source Project: couchbase-lite-android   Source File: PerfTest.java    License: 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 24
Source Project: couchbase-lite-android   Source File: PerfTest.java    License: 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 25
Source Project: couchbase-lite-android   Source File: PerfTest.java    License: 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 26
Source Project: couchbase-lite-android   Source File: DocPerfTest.java    License: 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 27
Source Project: couchbase-lite-android   Source File: TunesPerfTest.java    License: 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 28
private void setupCouchbase() throws CouchbaseLiteException, IOException {
    Manager manager = new Manager(new AndroidContext(getTargetContext()),
            Manager.DEFAULT_OPTIONS);
    database = manager.getDatabase(DB_NAME);
}
 
Example 29
private void indexedStringEntityQueriesRun(View indexedStringView, int count)
        throws CouchbaseLiteException {
    // create entities
    String[] fixedRandomStrings = StringGenerator.createFixedRandomStrings(count);
    database.beginTransaction();
    for (int i = 0; i < count; i++) {
        Document entity = database.getDocument(String.valueOf(i));
        Map<String, Object> properties = new HashMap<>();
        properties.put("indexedString", fixedRandomStrings[i]);
        entity.putProperties(properties);
    }
    database.endTransaction(true);
    log("Built and inserted entities.");

    // query for entities by indexed string at random
    int[] randomIndices = StringGenerator.getFixedRandomIndices(getQueryCount(), count - 1);

    // clear the document cache to force loading properties from the database
    database.clearDocumentCache();

    startClock();
    for (int i = 0; i < getQueryCount(); i++) {
        int nextIndex = randomIndices[i];
        List<Object> keyToQuery = new ArrayList<>(1);
        keyToQuery.add(fixedRandomStrings[nextIndex]);

        Query query = indexedStringView.createQuery();
        query.setKeys(keyToQuery);
        QueryEnumerator result = query.run();
        while (result.hasNext()) {
            QueryRow row = result.next();
            //noinspection unused
            Document document = row.getDocument();
        }
    }
    stopClock(Benchmark.Type.QUERY_INDEXED);

    // delete all entities
    deleteAll();
    log("Deleted all entities.");
}
 
Example 30
Source Project: couchbase-lite-java   Source File: CBLStatus.java    License: 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);
}