Example usage for android.database Cursor getBlob

List of usage examples for android.database Cursor getBlob

Introduction

In this page you can find the example usage for android.database Cursor getBlob.

Prototype

byte[] getBlob(int columnIndex);

Source Link

Document

Returns the value of the requested column as a byte array.

Usage

From source file:com.android.providers.contacts.ContactsSyncAdapter.java

protected void sendClientPhotos(SyncContext context, ContentProvider clientDiffs, Object syncInfo,
        SyncResult syncResult) {//www .  ja  v a2s.c o  m
    Entry entry = new MediaEntry();

    GDataServiceClient client = getGDataServiceClient();
    String authToken = getAuthToken();
    ContentResolver cr = getContext().getContentResolver();
    final String account = getAccount();

    Cursor c = clientDiffs.query(Photos.CONTENT_URI, null /* all columns */, null /* no where */,
            null /* no where args */, null /* default sort order */);
    try {
        int personColumn = c.getColumnIndexOrThrow(Photos.PERSON_ID);
        int dataColumn = c.getColumnIndexOrThrow(Photos.DATA);
        int numRows = c.getCount();
        while (c.moveToNext()) {
            if (mSyncCanceled) {
                if (Config.LOGD)
                    Log.d(TAG, "stopping since the sync was canceled");
                break;
            }

            entry.clear();
            context.setStatusText("Updating, " + (numRows - 1) + " to go");

            cursorToBaseEntry(entry, account, c);
            String editUrl = entry.getEditUri();

            if (TextUtils.isEmpty(editUrl)) {
                if (Config.LOGD) {
                    Log.d(TAG, "skipping photo edit for unsynced contact");
                }
                continue;
            }

            // Send the request and receive the response
            InputStream inputStream = null;
            byte[] imageData = c.getBlob(dataColumn);
            if (imageData != null) {
                inputStream = new ByteArrayInputStream(imageData);
            }
            Uri photoUri = Uri.withAppendedPath(People.CONTENT_URI,
                    c.getString(personColumn) + "/" + Photos.CONTENT_DIRECTORY);
            try {
                if (inputStream != null) {
                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
                        Log.v(TAG, "Updating photo " + entry.toString());
                    }
                    ++mPhotoUploads;
                    client.updateMediaEntry(editUrl, inputStream, IMAGE_MIME_TYPE, authToken);
                } else {
                    if (Log.isLoggable(TAG, Log.VERBOSE)) {
                        Log.v(TAG, "Deleting photo " + entry.toString());
                    }
                    client.deleteEntry(editUrl, authToken);
                }

                // Mark that this photo is no longer dirty. The next time we sync (which
                // should be soon), we will get the new version of the photo and whether
                // or not there is a new one to download (e.g. if we deleted our version
                // yet there is an evergreen version present).
                ContentValues values = new ContentValues();
                values.put(Photos.EXISTS_ON_SERVER, inputStream == null ? 0 : 1);
                values.put(Photos._SYNC_DIRTY, 0);
                if (cr.update(photoUri, values, null /* no where */, null /* no where args */) != 1) {
                    Log.e(TAG, "error updating photo " + photoUri + " with values " + values);
                    syncResult.stats.numParseExceptions++;
                } else {
                    syncResult.stats.numUpdates++;
                }
                continue;
            } catch (ParseException e) {
                Log.e(TAG, "parse error during update of " + ", skipping");
                syncResult.stats.numParseExceptions++;
            } catch (IOException e) {
                if (Config.LOGD) {
                    Log.d(TAG, "io error during update of " + entry.toString() + ", skipping");
                }
                syncResult.stats.numIoExceptions++;
            } catch (HttpException e) {
                switch (e.getStatusCode()) {
                case HttpException.SC_UNAUTHORIZED:
                    if (syncResult.stats.numAuthExceptions == 0) {
                        if (Config.LOGD) {
                            Log.d(TAG, "auth error during update of " + entry + ", skipping");
                        }
                    }
                    syncResult.stats.numAuthExceptions++;
                    try {
                        GoogleLoginServiceBlockingHelper.invalidateAuthToken(getContext(), authToken);
                    } catch (GoogleLoginServiceNotFoundException e1) {
                        if (Config.LOGD) {
                            Log.d(TAG, "could not invalidate auth token", e1);
                        }
                    }
                    return;

                case HttpException.SC_CONFLICT:
                    if (Config.LOGD) {
                        Log.d(TAG, "conflict detected during update of " + entry + ", skipping");
                    }
                    syncResult.stats.numConflictDetectedExceptions++;
                    break;
                case HttpException.SC_BAD_REQUEST:
                case HttpException.SC_FORBIDDEN:
                case HttpException.SC_NOT_FOUND:
                case HttpException.SC_INTERNAL_SERVER_ERROR:
                default:
                    if (Config.LOGD) {
                        Log.d(TAG, "error " + e.getMessage() + " during update of " + entry.toString()
                                + ", skipping");
                    }
                    syncResult.stats.numIoExceptions++;
                }
            }
        }
    } finally {
        c.close();
    }
}

From source file:com.odoo.orm.OModel.java

/**
 * Creates the record row./*from  www .  j a v a 2 s  . c  o m*/
 * 
 * @param column
 *            the column
 * @param cr
 *            the cr
 * @return the object
 */
public Object createRecordRow(OColumn column, Cursor cr) {
    Object value = false;
    if (column.getDefaultValue() != null) {
        value = column.getDefaultValue();
    }
    int index = cr.getColumnIndex(column.getName());
    switch (cr.getType(index)) {
    case Cursor.FIELD_TYPE_NULL:
        value = false;
        break;
    case Cursor.FIELD_TYPE_STRING:
        value = cr.getString(index);
        break;
    case Cursor.FIELD_TYPE_INTEGER:
        value = cr.getInt(index);
        break;
    case Cursor.FIELD_TYPE_FLOAT:
        value = cr.getFloat(index);
        break;
    case Cursor.FIELD_TYPE_BLOB:
        value = cr.getBlob(index);
        break;
    }
    return value;
}

From source file:android.support.content.InMemoryCursor.java

/**
 * @param cursor source of data to copy. Ownership is reserved to the called, meaning
 *               we won't ever close it.
 *///from w  w  w. j  ava 2s .  c  o  m
InMemoryCursor(Cursor cursor, int offset, int length, int disposition) {
    checkArgument(offset < cursor.getCount());

    // NOTE: The cursor could simply be saved to a field, but we choose to wrap
    // in a dedicated relay class to avoid hanging directly onto a reference
    // to the cursor...so future authors are not enticed to think there's
    // a live link between the delegate cursor and this cursor.
    mObserverRelay = new ObserverRelay(cursor);

    mColumnNames = cursor.getColumnNames();
    mRowCount = Math.min(length, cursor.getCount() - offset);
    int numColumns = cursor.getColumnCount();

    mExtras = ContentPager.buildExtras(cursor.getExtras(), cursor.getCount(), disposition);

    mColumnType = new int[numColumns];
    mTypedColumnIndex = new int[NUM_TYPES][numColumns];
    mColumnTypeCount = new int[NUM_TYPES];

    if (!cursor.moveToFirst()) {
        throw new RuntimeException("Can't position cursor to first row.");
    }

    for (int col = 0; col < numColumns; col++) {
        int type = cursor.getType(col);
        mColumnType[col] = type;
        mTypedColumnIndex[type][col] = mColumnTypeCount[type]++;
    }

    mLongs = new long[mRowCount * mColumnTypeCount[FIELD_TYPE_INTEGER]];
    mDoubles = new double[mRowCount * mColumnTypeCount[FIELD_TYPE_FLOAT]];
    mBlobs = new byte[mRowCount * mColumnTypeCount[FIELD_TYPE_BLOB]][];
    mStrings = new String[mRowCount * mColumnTypeCount[FIELD_TYPE_STRING]];

    for (int row = 0; row < mRowCount; row++) {
        if (!cursor.moveToPosition(offset + row)) {
            throw new RuntimeException("Unable to position cursor.");
        }

        // Now copy data from the row into primitive arrays.
        for (int col = 0; col < mColumnType.length; col++) {
            int type = mColumnType[col];
            int position = getCellPosition(row, col, type);

            switch (type) {
            case FIELD_TYPE_NULL:
                throw new UnsupportedOperationException("Not implemented.");
            case FIELD_TYPE_INTEGER:
                mLongs[position] = cursor.getLong(col);
                break;
            case FIELD_TYPE_FLOAT:
                mDoubles[position] = cursor.getDouble(col);
                break;
            case FIELD_TYPE_BLOB:
                mBlobs[position] = cursor.getBlob(col);
                break;
            case FIELD_TYPE_STRING:
                mStrings[position] = cursor.getString(col);
                break;
            }
        }
    }
}

From source file:com.clough.android.androiddbviewer.ADBVApplication.java

@Override
public void onCreate() {
    super.onCreate();

    // Getting user configured(custom) SQLiteOpenHelper instance.
    sqliteOpenHelper = getDataBase();//  ww w.j a  v  a 2s  .  c  om

    // getDataBase() could return a null
    if (sqliteOpenHelper != null) {

        // Background operation of creating the server socket.
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    // Server socket re create when device is being disconnected or
                    // when AndroidDBViewer desktop application is being closed.
                    // Creating server socket will exit when
                    // android application runs in low memory or when
                    // android application being terminated due some reasons.
                    l1: while (flag) {
                        serverSocket = new ServerSocket(1993);
                        socket = serverSocket.accept();
                        br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        pw = new PrintWriter(socket.getOutputStream(), true);

                        // Keeps a continuous communication between android application and
                        // AndroidDBViewer desktop application through IO streams of the accepted socket connection.
                        // There will be continuous data parsing between desktop application and android application.
                        // Identification of device being disconnected or desktop application being closed will be determined
                        // only when there is a NULL data being received.
                        l2: while (flag) {

                            // Format of the parsing data string is JSON, a content of a 'Data' instance
                            String requestJSONString = br.readLine();

                            if (requestJSONString == null) {

                                // Received a null response from desktop application, due to disconnecting the
                                // device or closing the AndroidDBViewer desktop application.
                                // Therefore, closing all current connections and streams to re create the server
                                // socket so that desktop application can connect in it's next run.

                                // Device disconnection doesn't produce an IOException.
                                // Also, even after calling
                                // socket.close(), socket.shutdownInput() and socket.shutdownOutput()
                                // within a shutdown hook in desktop application, the socket connection
                                // in this async task always gives
                                // socket.isConnected() as 'true' ,
                                // socket.isClosed() as 'false' ,
                                // socket.isInputShutdown() as 'false' and
                                // socket.isOutputShutdown() as 'false' .
                                // But, bufferedReader.readLine() starts returning 'null' continuously.
                                // So, inorder to desktop application to connect with the device again,
                                // there should be a ServerSocket waiting to accept a socket connection, in device.
                                closeConnection();
                                continue l1;
                            } else {

                                // Received a valid response from the desktop application.
                                Data data;
                                try {

                                    // Converting received request to a 'Data' instance.
                                    data = new Data(new JSONObject(requestJSONString));
                                    int status = data.getStatus();
                                    if (status == Data.CONNECTION_REQUEST) {

                                        // Very first request from desktop application to
                                        // establish the connection and setting the response as
                                        // connection being accepted.
                                        data.setStatus(Data.CONNECTION_ACCEPTED);
                                    } else if (status == Data.LIVE_CONNECTION) {

                                        // When there is no user interaction in desktop application,
                                        // data being passed from desktop application to android
                                        // application with the status of LIVE_CONNECTION, and the
                                        // same data send again to the desktop application from android application,
                                        // to notify that connection is still alive.
                                        // This exchange won't change until  there is a request from
                                        // desktop application with a different status.
                                    } else if (status == Data.QUERY) {

                                        // Requesting to perform a query execution.

                                        String result = "No result";
                                        try {

                                            // Performing select, insert, delete and update queries.
                                            Cursor cursor = sqliteOpenHelper.getWritableDatabase()
                                                    .rawQuery(data.getQuery(), null);

                                            // Flag to identify the firs move of the cursor
                                            boolean firstTime = true;

                                            int columnCount = 0;

                                            // JSONArray to hold the all JSONObjects, created per every row
                                            // of the result returned, executing the given query.
                                            JSONArray jsonArray = new JSONArray();

                                            // Moving the cursor to the next row of retrieved result
                                            // after executing the requested query.
                                            while (cursor.moveToNext()) {

                                                if (firstTime) {

                                                    // Column count of the result returned, executing the given query.
                                                    columnCount = cursor.getColumnCount();
                                                    firstTime = false;
                                                }

                                                // JOSNObject to hold the values of a single row
                                                JSONObject jsonObject = new JSONObject();
                                                for (int i = 0; i < columnCount; i++) {
                                                    int columnType = cursor.getType(i);
                                                    String columnName = cursor.getColumnName(i);
                                                    if (columnType == Cursor.FIELD_TYPE_STRING) {
                                                        jsonObject.put(columnName, cursor.getString(i));
                                                    } else if (columnType == Cursor.FIELD_TYPE_BLOB) {
                                                        jsonObject.put(columnName,
                                                                cursor.getBlob(i).toString());
                                                    } else if (columnType == Cursor.FIELD_TYPE_FLOAT) {
                                                        jsonObject.put(columnName,
                                                                String.valueOf(cursor.getFloat(i)));
                                                    } else if (columnType == Cursor.FIELD_TYPE_INTEGER) {
                                                        jsonObject.put(columnName,
                                                                String.valueOf(cursor.getInt(i)));
                                                    } else if (columnType == Cursor.FIELD_TYPE_NULL) {
                                                        jsonObject.put(columnName, "NULL");
                                                    } else {
                                                        jsonObject.put(columnName, "invalid type");
                                                    }
                                                }
                                                jsonArray.put(jsonObject);
                                            }
                                            result = jsonArray.toString();
                                            cursor.close();
                                        } catch (Exception e) {

                                            // If SQL error is occurred when executing the requested query,
                                            // error content will be the response to the desktop application.
                                            StringWriter sw = new StringWriter();
                                            PrintWriter epw = new PrintWriter(sw);
                                            e.printStackTrace(epw);
                                            result = sw.toString();
                                            epw.close();
                                            sw.close();
                                        } finally {
                                            data.setResult(result);
                                        }
                                    } else if (status == Data.DEVICE_NAME) {

                                        // Requesting device information
                                        data.setResult(Build.BRAND + " " + Build.MODEL);
                                    } else if (status == Data.APPLICATION_ID) {

                                        // Requesting application id (package name)
                                        data.setResult(getPackageName());
                                    } else if (status == Data.DATABASE_NAME) {

                                        // Requesting application database name.
                                        // Will provide the database name according
                                        // to the SQLiteOpenHelper user provided
                                        data.setResult(sqliteOpenHelper.getDatabaseName());
                                    } else {

                                        // Unidentified request state.
                                        closeConnection();
                                        continue l1;
                                    }
                                    String responseJSONString = data.toJSON().toString();
                                    pw.println(responseJSONString);
                                } catch (JSONException e) {

                                    // Response couldn't convert to a 'Data' instance.
                                    // Desktop application will be notified to close the application.
                                    closeConnection();
                                    continue l1;
                                }
                            }
                        }
                    }
                } catch (IOException e) {
                    // Cannot create a server socket. Letting background process to end.
                }
            }
        }).start();
    }
}

From source file:org.thialfihar.android.apg.ui.ViewKeyMainFragment.java

public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    // Swap the new cursor in. (The framework will take care of closing the
    // old cursor once we return.)
    switch (loader.getId()) {
    case LOADER_ID_KEYRING:
        if (data.moveToFirst()) {
            // get name, email, and comment from USER_ID
            String[] mainUserId = PgpKeyHelper.splitUserId(data.getString(KEYRING_INDEX_USER_ID));
            if (mainUserId[0] != null) {
                getActivity().setTitle(mainUserId[0]);
                mName.setText(mainUserId[0]);
            } else {
                getActivity().setTitle(R.string.user_id_no_name);
                mName.setText(R.string.user_id_no_name);
            }/*from  w  w w. j ava  2  s. c o  m*/
            mEmail.setText(mainUserId[1]);
            mComment.setText(mainUserId[2]);
        }

        break;
    case LOADER_ID_USER_IDS:
        mUserIdsAdapter.swapCursor(data);
        break;
    case LOADER_ID_KEYS:
        // the first key here is our master key
        if (data.moveToFirst()) {
            // get key id from MASTER_KEY_ID
            long keyId = data.getLong(KEYS_INDEX_KEY_ID);
            String keyIdStr = PgpKeyHelper.convertKeyIdToHex(keyId);
            mKeyId.setText(keyIdStr);

            // get creation date from CREATION
            if (data.isNull(KEYS_INDEX_CREATION)) {
                mCreation.setText(R.string.none);
            } else {
                Date creationDate = new Date(data.getLong(KEYS_INDEX_CREATION) * 1000);

                mCreation.setText(
                        DateFormat.getDateFormat(getActivity().getApplicationContext()).format(creationDate));
            }

            // get expiry date from EXPIRY
            if (data.isNull(KEYS_INDEX_EXPIRY)) {
                mExpiry.setText(R.string.none);
            } else {
                Date expiryDate = new Date(data.getLong(KEYS_INDEX_EXPIRY) * 1000);

                mExpiry.setText(
                        DateFormat.getDateFormat(getActivity().getApplicationContext()).format(expiryDate));
            }

            String algorithmStr = PgpKeyHelper.getAlgorithmInfo(data.getInt(KEYS_INDEX_ALGORITHM),
                    data.getInt(KEYS_INDEX_KEY_SIZE));
            mAlgorithm.setText(algorithmStr);

            byte[] fingerprintBlob = data.getBlob(KEYS_INDEX_FINGERPRINT);
            if (fingerprintBlob == null) {
                // FALLBACK for old database entries
                fingerprintBlob = ProviderHelper.getFingerprint(getActivity(), mDataUri);
            }
            String fingerprint = PgpKeyHelper.convertFingerprintToHex(fingerprintBlob);

            mFingerprint.setText(PgpKeyHelper.colorizeFingerprint(fingerprint));
        }

        mKeysAdapter.swapCursor(data);
        break;

    default:
        break;
    }
}

From source file:com.mobile.system.db.abatis.AbatisService.java

public Object parseToObject(Class beanClass, Cursor cur)
        throws IllegalAccessException, InstantiationException, SecurityException, NoSuchMethodException {
    Object obj = null;//from ww w . j  av  a 2 s .co  m
    Field[] props = beanClass.getDeclaredFields();
    if (props == null || props.length == 0) {
        Log.d(TAG, "Class" + beanClass.getName() + " has no fields");
        return null;
    }
    // Create instance of this Bean class
    obj = beanClass.newInstance();
    // Set value of each member variable of this object
    for (int i = 0; i < props.length; i++) {
        String fieldName = props[i].getName();
        if (props[i].getModifiers() == (Modifier.PUBLIC | Modifier.STATIC)) {
            continue;
        }

        Class type = props[i].getType();
        String typeName = type.getName();
        // Check for Custom type

        Class[] parms = { type };
        Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
        m.setAccessible(true);
        // Set value
        try {
            int curIdx = cur.getColumnIndex(fieldName);
            if (curIdx != -1) {
                int nDotIdx = typeName.lastIndexOf(".");
                if (nDotIdx >= 0) {
                    typeName = typeName.substring(nDotIdx);
                }

                if (typeName.equals("int")) {
                    m.invoke(obj, cur.getInt(curIdx));
                } else if (typeName.equals("double")) {
                    m.invoke(obj, cur.getDouble(curIdx));
                } else if (typeName.equals("String")) {
                    m.invoke(obj, cur.getString(curIdx));
                } else if (typeName.equals("long")) {
                    m.invoke(obj, cur.getLong(curIdx));
                } else if (typeName.equals("float")) {
                    m.invoke(obj, cur.getFloat(curIdx));
                } else if (typeName.equals("Date")) {
                    m.invoke(obj, cur.getString(curIdx));
                } else if (typeName.equals("byte[]") || typeName.equals("[B")) {
                    m.invoke(obj, cur.getBlob(curIdx));
                } else {
                    m.invoke(obj, cur.getString(curIdx));
                }
            }

        } catch (Exception ex) {
            Log.d(TAG, ex.getMessage());
        }
    }
    return obj;
}

From source file:edu.stanford.mobisocial.dungbeetle.DBHelper.java

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion);

    if (oldVersion <= 23) {
        Log.w(TAG, "Schema too old to migrate, dropping all.");
        dropAll(db);// ww  w .  j av a  2  s  .co  m
        onCreate(db);
        return;
    }

    if (oldVersion <= 24) {
        Log.w(TAG, "Adding columns 'presence' and 'status' to contact table.");
        db.execSQL("ALTER TABLE " + Contact.TABLE + " ADD COLUMN " + Contact.STATUS + " TEXT");
        db.execSQL("ALTER TABLE " + Contact.TABLE + " ADD COLUMN " + Contact.PRESENCE + " INTEGER DEFAULT "
                + Presence.AVAILABLE);
    }

    if (oldVersion <= 25) {
        Log.w(TAG, "Adding columns 'presence' and 'status' to contact table.");
        db.execSQL("ALTER TABLE " + Group.TABLE + " ADD COLUMN " + Group.FEED_NAME + " TEXT");
    }

    if (oldVersion <= 26) {
        Log.w(TAG, "Adding column 'picture' to contact table.");
        db.execSQL("ALTER TABLE " + Contact.TABLE + " ADD COLUMN " + Contact.PICTURE + " BLOB");
    }

    if (oldVersion <= 27) {
        Log.w(TAG, "Adding column 'last_presence_time' to contact table.");
        db.execSQL("ALTER TABLE " + Contact.TABLE + " ADD COLUMN " + Contact.LAST_PRESENCE_TIME
                + " INTEGER DEFAULT 0");
    }

    if (oldVersion <= 28) {
        Log.w(TAG, "Adding column 'picture' to my_info table.");
        db.execSQL("ALTER TABLE " + MyInfo.TABLE + " ADD COLUMN " + MyInfo.PICTURE + " BLOB");
    }
    if (oldVersion <= 29) {
        Log.w(TAG, "Adding column 'version' to group table.");
        db.execSQL("ALTER TABLE " + Group.TABLE + " ADD COLUMN " + Group.VERSION + " INTEGER DEFAULT -1");
    }
    if (oldVersion <= 30) {
        Log.w(TAG, "Adding column 'E' to object table.");
        db.execSQL("ALTER TABLE " + DbObject.TABLE + " ADD COLUMN " + DbObject.ENCODED + " BLOB");
        createIndex(db, "INDEX", "objects_by_encoded", DbObject.TABLE, DbObject.ENCODED);
    }
    if (oldVersion <= 31) {
        Log.w(TAG, "Adding column 'child_feed' to object table.");
        db.execSQL("ALTER TABLE " + DbObject.TABLE + " ADD COLUMN " + DbObject.CHILD_FEED_NAME + " TEXT");
        createIndex(db, "INDEX", "child_feeds", DbObject.TABLE, DbObject.CHILD_FEED_NAME);
    }
    if (oldVersion <= 32) {
        // Bug fix.
        Log.w(TAG, "Updating app state objects.");
        db.execSQL("UPDATE " + DbObject.TABLE + " SET " + DbObject.CHILD_FEED_NAME + " = NULL WHERE "
                + DbObject.CHILD_FEED_NAME + " = " + DbObject.FEED_NAME);
    }
    if (oldVersion <= 33) {
        Log.w(TAG, "Adding column 'nearby' to contact table.");
        db.execSQL("ALTER TABLE " + Contact.TABLE + " ADD COLUMN " + Contact.NEARBY + " INTEGER DEFAULT 0");
    }
    if (oldVersion <= 34) {
        Log.w(TAG, "Adding column 'secret' to contact table.");
        db.execSQL("ALTER TABLE " + Contact.TABLE + " ADD COLUMN " + Contact.SHARED_SECRET + " BLOB");

    }
    if (oldVersion <= 35) {
        Log.w(TAG, "Adding column 'last_updated' to group table.");
        db.execSQL("ALTER TABLE " + Group.TABLE + " ADD COLUMN " + Group.LAST_UPDATED + " INTEGER");
    }
    if (oldVersion <= 36) {
        // Can't easily drop columns, but 'update_id' and 'is_child_feed' are dead columns.

        Log.w(TAG, "Adding column 'parent_feed_id' to group table.");
        db.execSQL(
                "ALTER TABLE " + Group.TABLE + " ADD COLUMN " + Group.PARENT_FEED_ID + " INTEGER DEFAULT -1");

        Log.w(TAG, "Adding column 'last_object_id' to group table.");
        db.execSQL(
                "ALTER TABLE " + Group.TABLE + " ADD COLUMN " + Group.LAST_OBJECT_ID + " INTEGER DEFAULT -1");
    }
    if (oldVersion <= 37) {
        // Can't easily drop columns, but 'update_id' and 'is_child_feed' are dead columns.

        Log.w(TAG, "Adding column 'num_unread' to group table.");
        db.execSQL("ALTER TABLE " + Group.TABLE + " ADD COLUMN " + Group.NUM_UNREAD + " INTEGER DEFAULT 0");
    }
    if (oldVersion <= 38) {
        Log.w(TAG, "Adding column 'raw' to object table.");
        db.execSQL("ALTER TABLE " + DbObject.TABLE + " ADD COLUMN " + DbObject.RAW + " BLOB");
    }
    // sadly, we have to do this again because incoming voice obj's were not being split!
    if (oldVersion <= 50) {
        Log.w(TAG, "Converting voice and picture objs to raw.");

        Log.w(TAG, "Converting objs to raw.");
        Cursor c = db.query(DbObject.TABLE, new String[] { DbObject._ID },
                DbObject.TYPE + " = ? AND " + DbObject.RAW + " IS NULL", new String[] { PictureObj.TYPE }, null,
                null, null);
        ArrayList<Long> ids = new ArrayList<Long>();
        if (c.moveToFirst())
            do {
                ids.add(c.getLong(0));
            } while (c.moveToNext());
        c.close();
        DbEntryHandler dbh = DbObjects.forType(PictureObj.TYPE);
        for (Long id : ids) {
            c = db.query(DbObject.TABLE, new String[] { DbObject.JSON, DbObject.RAW }, DbObject._ID + " = ? ",
                    new String[] { String.valueOf(id.longValue()) }, null, null, null);
            if (c.moveToFirst())
                try {
                    String json = c.getString(0);
                    byte[] raw = c.getBlob(1);
                    c.close();
                    if (raw == null) {
                        Pair<JSONObject, byte[]> p = dbh.splitRaw(new JSONObject(json));
                        if (p != null) {
                            json = p.first.toString();
                            raw = p.second;
                            updateJsonAndRaw(db, id, json, raw);
                        }
                    }
                } catch (JSONException e) {
                }
            c.close();
        }
        c = db.query(DbObject.TABLE, new String[] { DbObject._ID },
                DbObject.TYPE + " = ? AND " + DbObject.RAW + " IS NULL", new String[] { VoiceObj.TYPE }, null,
                null, null);
        ids = new ArrayList<Long>();
        if (c.moveToFirst())
            do {
                ids.add(c.getLong(0));
            } while (c.moveToNext());
        c.close();
        dbh = DbObjects.forType(VoiceObj.TYPE);
        for (Long id : ids) {
            c = db.query(DbObject.TABLE, new String[] { DbObject.JSON, DbObject.RAW }, DbObject._ID + " = ? ",
                    new String[] { String.valueOf(id.longValue()) }, null, null, null);
            if (c.moveToFirst())
                try {
                    String json = c.getString(0);
                    byte[] raw = c.getBlob(1);
                    c.close();
                    if (raw == null) {
                        Pair<JSONObject, byte[]> p = dbh.splitRaw(new JSONObject(json));
                        if (p != null) {
                            json = p.first.toString();
                            raw = p.second;
                            updateJsonAndRaw(db, id, json, raw);
                        }
                    }
                } catch (JSONException e) {
                }
            c.close();
        }
    }
    if (oldVersion <= 40) {
        Log.w(TAG, "Adding column 'E' to object table.");
        db.execSQL("ALTER TABLE " + DbObject.TABLE + " ADD COLUMN " + DbObject.HASH + " INTEGER");
        createIndex(db, "INDEX", "objects_by_hash", DbObject.TABLE, DbObject.HASH);
        db.execSQL("DROP INDEX objects_by_encoded");
        db.delete(DbObject.TABLE, DbObject.TYPE + " = ?", new String[] { "profile" });
        db.delete(DbObject.TABLE, DbObject.TYPE + " = ?", new String[] { "profilepicture" });
        ContentValues cv = new ContentValues();
        cv.putNull(DbObject.ENCODED);
        db.update(DbObject.TABLE, cv, null, null);
    }
    if (oldVersion <= 41) {
        db.execSQL("DROP INDEX objects_by_sequence_id");
        db.execSQL("CREATE INDEX objects_by_sequence_id ON " + DbObject.TABLE + "(" + DbObject.CONTACT_ID + ", "
                + DbObject.FEED_NAME + ", " + DbObject.SEQUENCE_ID + ")");
    }
    //secret to life, etc
    if (oldVersion <= 42) {
        db.execSQL("DROP INDEX objects_by_creator_id");
        db.execSQL("CREATE INDEX objects_by_creator_id ON " + DbObject.TABLE + "(" + DbObject.CONTACT_ID + ", "
                + DbObject.SENT + ")");
    }

    if (oldVersion <= 44) {
        // oops.
        db.execSQL("DROP TABLE IF EXISTS " + DbRelation.TABLE);
        createRelationBaseTable(db);
    }
    if (oldVersion <= 45) {
        db.execSQL("ALTER TABLE " + Contact.TABLE + " ADD COLUMN " + Contact.LAST_OBJECT_ID + " INTEGER");
        db.execSQL("ALTER TABLE " + Contact.TABLE + " ADD COLUMN " + Contact.LAST_UPDATED + " INTEGER");
        db.execSQL("ALTER TABLE " + Contact.TABLE + " ADD COLUMN " + Contact.NUM_UNREAD + " INTEGER DEFAULT 0");
    }
    if (oldVersion <= 46) {
        db.execSQL("ALTER TABLE " + DbObject.TABLE + " ADD COLUMN " + DbObject.DELETED + " INTEGER DEFAULT 0");
    }
    if (oldVersion <= 47) {
        addRelationIndexes(db);
    }
    if (oldVersion <= 44) {
        createUserAttributesTable(db);
    }

    if (oldVersion <= 49) {
        if (oldVersion > 44) {
            db.execSQL("ALTER TABLE " + DbRelation.TABLE + " ADD COLUMN " + DbRelation.RELATION_TYPE + " TEXT");
            createIndex(db, "INDEX", "relations_by_type", DbRelation.TABLE, DbRelation.RELATION_TYPE);
        }
        db.execSQL("UPDATE " + DbRelation.TABLE + " SET " + DbRelation.RELATION_TYPE + " = 'parent'");
    }
    if (oldVersion <= 52) {
        Log.w(TAG, "Adding column 'about' to my_info table.");
        try {
            db.execSQL("ALTER TABLE " + MyInfo.TABLE + " ADD COLUMN " + MyInfo.ABOUT + " TEXT DEFAULT ''");
        } catch (Exception e) {
            // because of bad update, we just ignore the duplicate column error
        }
    }
    if (oldVersion <= 53) {
        db.execSQL("ALTER TABLE " + Contact.TABLE + " ADD COLUMN " + Contact.HIDDEN + " INTEGER DEFAULT 0");
    }
    if (oldVersion <= 55) {
        db.execSQL("ALTER TABLE " + DbObj.TABLE + " ADD COLUMN " + DbObj.COL_KEY_INT + " INTEGER");
    }
    if (oldVersion <= 56) {
        db.execSQL("DROP INDEX attrs_by_contact_id");
        createIndex(db, "INDEX", "attrs_by_contact_id", DbContactAttributes.TABLE,
                DbContactAttributes.CONTACT_ID);
    }
    if (oldVersion <= 57) {
        db.execSQL("ALTER TABLE " + DbObject.TABLE + " ADD COLUMN " + DbObject.LAST_MODIFIED_TIMESTAMP
                + " INTEGER");
        db.execSQL("UPDATE " + DbObject.TABLE + " SET " + DbObject.LAST_MODIFIED_TIMESTAMP + " = "
                + DbObject.TIMESTAMP);
    }
    if (oldVersion <= 58) {
        db.execSQL("ALTER TABLE " + Group.TABLE + " ADD COLUMN " + Group.GROUP_TYPE + " TEXT DEFAULT 'group'");
        db.execSQL("UPDATE " + Group.TABLE + " SET " + Group.GROUP_TYPE + " = 'group'");
    }
    if (oldVersion <= 59) {
        createIndex(db, "INDEX", "objects_last_modified", DbObject.TABLE, DbObject.LAST_MODIFIED_TIMESTAMP);
    }
    if (oldVersion <= 60) {
        db.execSQL("ALTER TABLE " + Contact.TABLE + " ADD COLUMN " + Contact.PUBLIC_KEY_HASH_64
                + " INTEGER DEFAULT 0");
        createIndex(db, "INDEX", "contacts_by_pkp", Contact.TABLE, Contact.PUBLIC_KEY_HASH_64);
        Cursor peeps = db
                .rawQuery("SELECT " + Contact._ID + "," + Contact.PUBLIC_KEY + " FROM " + Contact.TABLE, null);
        peeps.moveToFirst();
        while (!peeps.isAfterLast()) {
            db.execSQL("UPDATE " + Contact.TABLE + " SET " + Contact.PUBLIC_KEY_HASH_64 + " = "
                    + hashPublicKey(peeps.getBlob(1)) + " WHERE " + Contact._ID + " = " + peeps.getLong(0));
            peeps.moveToNext();
        }
        peeps.close();
    }
    db.setVersion(VERSION);
}

From source file:org.kontalk.service.msgcenter.MessageCenterService.java

private void sendMessages(Cursor c, boolean retrying) {
    // this set will cache thread IDs within this cursor with
    // pending group commands (i.e. just processed group commands)
    // This will be looked up when sending consecutive message in the group
    // and stop them
    Set<Long> pendingGroupCommandThreads = new HashSet<>();

    while (c.moveToNext()) {
        long id = c.getLong(0);
        long threadId = c.getLong(1);
        String msgId = c.getString(2);
        String peer = c.getString(3);
        byte[] textContent = c.getBlob(4);
        String bodyMime = c.getString(5);
        int securityFlags = c.getInt(6);
        String attMime = c.getString(7);
        String attFileUri = c.getString(8);
        String attFetchUrl = c.getString(9);
        String attPreviewPath = c.getString(10);
        long attLength = c.getLong(11);
        int compress = c.getInt(12);
        // TODO int attSecurityFlags = c.getInt(13);

        String groupJid = c.getString(13); // 14
        String groupSubject = c.getString(14); // 15

        if (pendingGroupCommandThreads.contains(threadId)) {
            Log.v(TAG, "group message for pending group command - delaying");
            continue;
        }/*from w w w . j a v a 2 s. c  o m*/

        final boolean isGroupCommand = GroupCommandComponent.supportsMimeType(bodyMime);
        if (isGroupCommand) {
            if (groupJid == null) {
                // orphan group command waiting to be sent
                groupJid = peer;
            } else {
                // cache the thread -- it will block future messages until
                // this command is received by the server
                pendingGroupCommandThreads.add(threadId);
            }
        }

        String[] groupMembers = null;
        if (groupJid != null) {
            /*
             * Huge potential issue here. Selecting all members, regardless of pending flags,
             * might e.g. deliver messages to removed users if there is a content message right
             * after a remove command.
             * However, selecting members with zero flags will make a remove command to be sent
             * only to existing members and not to the ones being removed.
             */
            groupMembers = MessagesProviderUtils.getGroupMembers(this, groupJid, -1);
            if (groupMembers.length == 0) {
                // no group member left - skip message
                // this might be a pending message that was queued before we realized there were no members left
                // since the group might get populated again, we just skip the message but keep it
                Log.d(TAG, "no members in group - skipping message");
                continue;
            }
        }

        // media message encountered and no upload service available - delay message
        if (attFileUri != null && attFetchUrl == null && getUploadService() == null && !retrying) {
            Log.w(TAG, "no upload info received yet, delaying media message");
            continue;
        }

        Bundle b = new Bundle();
        // mark as retrying
        b.putBoolean("org.kontalk.message.retrying", true);

        b.putLong("org.kontalk.message.msgId", id);
        b.putString("org.kontalk.message.packetId", msgId);

        if (groupJid != null) {
            b.putString("org.kontalk.message.group.jid", groupJid);
            b.putString("org.kontalk.message.group.subject", groupSubject);
            // will be replaced by the group command (if any)
            b.putStringArray("org.kontalk.message.to", groupMembers);
        } else {
            b.putString("org.kontalk.message.to", peer);
        }

        // TODO shouldn't we pass security flags directly here??
        b.putBoolean("org.kontalk.message.encrypt", securityFlags != Coder.SECURITY_CLEARTEXT);

        if (isGroupCommand) {
            int cmd = 0;
            byte[] _command = c.getBlob(4);
            String command = new String(_command);

            String[] createMembers;
            String[] addMembers;
            String[] removeMembers = null;
            String subject;
            if ((createMembers = GroupCommandComponent.getCreateCommandMembers(command)) != null) {
                cmd = GROUP_COMMAND_CREATE;
                b.putStringArray("org.kontalk.message.to", createMembers);
            } else if (command.equals(GroupCommandComponent.COMMAND_PART)) {
                cmd = GROUP_COMMAND_PART;
            } else if ((addMembers = GroupCommandComponent.getAddCommandMembers(command)) != null
                    || (removeMembers = GroupCommandComponent.getRemoveCommandMembers(command)) != null) {
                cmd = GROUP_COMMAND_MEMBERS;
                b.putStringArray("org.kontalk.message.group.add", addMembers);
                b.putStringArray("org.kontalk.message.group.remove", removeMembers);
            } else if ((subject = GroupCommandComponent.getSubjectCommand(command)) != null) {
                cmd = GROUP_COMMAND_SUBJECT;
                b.putString("org.kontalk.message.group.subject", subject);
            }

            b.putInt("org.kontalk.message.group.command", cmd);
        } else if (textContent != null) {
            b.putString("org.kontalk.message.body", MessageUtils.toString(textContent));
        }

        // message has already been uploaded - just send media
        if (attFetchUrl != null) {
            b.putString("org.kontalk.message.mime", attMime);
            b.putString("org.kontalk.message.fetch.url", attFetchUrl);
            b.putString("org.kontalk.message.preview.uri", attFileUri);
            b.putString("org.kontalk.message.preview.path", attPreviewPath);
        }
        // check if the message contains some large file to be sent
        else if (attFileUri != null) {
            b.putString("org.kontalk.message.mime", attMime);
            b.putString("org.kontalk.message.media.uri", attFileUri);
            b.putString("org.kontalk.message.preview.path", attPreviewPath);
            b.putLong("org.kontalk.message.length", attLength);
            b.putInt("org.kontalk.message.compress", compress);
        }

        Log.v(TAG, "resending pending message " + id);
        sendMessage(b);
    }
}

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

public String Cat(String fileName, OutputStream out) {
    String sTmpFileName = fixFileName(fileName);
    String sRet = sErrorPrefix + "Could not read the file " + sTmpFileName;
    byte[] buffer = new byte[4096];
    int nRead = 0;

    if (sTmpFileName.contains("org.mozilla.fennec") || sTmpFileName.contains("org.mozilla.firefox")) {
        ContentResolver cr = contextWrapper.getContentResolver();
        Uri ffxFiles = null;//from   w  w w  .  j  a  va2  s  .co m

        ffxFiles = Uri
                .parse("content://" + (sTmpFileName.contains("fennec") ? fenProvider : ffxProvider) + "/file");

        String[] columns = new String[] { "_id", "chunk" };

        Cursor myCursor = cr.query(ffxFiles, columns, // Which columns to return
                sTmpFileName, // Which rows to return (all rows)
                null, // Selection arguments (none)
                null); // Order clause (none)
        if (myCursor != null) {
            int nRows = myCursor.getCount();
            int nBytesRecvd = 0;

            for (int lcv = 0; lcv < nRows; lcv++) {
                if (myCursor.moveToPosition(lcv)) {
                    byte[] buf = myCursor.getBlob(1);
                    if (buf != null) {
                        nBytesRecvd += buf.length;
                        try {
                            out.write(buf);
                            sRet = "";
                        } catch (IOException e) {
                            e.printStackTrace();
                            sRet = sErrorPrefix + "Could not write to out " + sTmpFileName;
                        }
                        buf = null;
                    }
                }
            }
            if (nRows == 0) {
                sRet = "";
            }

            myCursor.close();
        }
    } else {
        try {
            FileInputStream fin = new FileInputStream(sTmpFileName);
            while ((nRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, nRead);
            }
            fin.close();
            out.flush();
            sRet = "";
        } catch (FileNotFoundException e) {
            sRet = sErrorPrefix + sTmpFileName + " No such file or directory";
        } catch (IOException e) {
            sRet = e.toString();
        }
    }
    return (sRet);
}

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

public String HashFile(String fileName) {
    String sTmpFileName = fixFileName(fileName);
    String sRet = sErrorPrefix + "Couldn't calculate hash for file " + sTmpFileName;
    byte[] buffer = new byte[4096];
    int nRead = 0;
    long lTotalRead = 0;
    MessageDigest digest = null;// ww  w. j  av  a2s . c  om

    try {
        digest = java.security.MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    if (sTmpFileName.contains("org.mozilla.fennec") || sTmpFileName.contains("org.mozilla.firefox")) {
        ContentResolver cr = contextWrapper.getContentResolver();
        Uri ffxFiles = null;

        ffxFiles = Uri
                .parse("content://" + (sTmpFileName.contains("fennec") ? fenProvider : ffxProvider) + "/file");

        String[] columns = new String[] { "_id", "chunk" };

        Cursor myCursor = cr.query(ffxFiles, columns, // Which columns to return
                sTmpFileName, // Which rows to return (all rows)
                null, // Selection arguments (none)
                null); // Order clause (none)
        if (myCursor != null) {
            int nRows = myCursor.getCount();
            int nBytesRecvd = 0;

            for (int lcv = 0; lcv < nRows; lcv++) {
                if (myCursor.moveToPosition(lcv)) {
                    byte[] buf = myCursor.getBlob(1);
                    if (buf != null) {
                        nBytesRecvd += buf.length;
                        digest.update(buf, 0, buf.length);
                        lTotalRead += nRead;
                        buf = null;
                    }
                }
            }
            myCursor.close();
            byte[] hash = digest.digest();

            sRet = getHex(hash);
        }
    } else {
        try {
            FileInputStream srcFile = new FileInputStream(sTmpFileName);
            while ((nRead = srcFile.read(buffer)) != -1) {
                digest.update(buffer, 0, nRead);
                lTotalRead += nRead;
            }
            srcFile.close();
            byte[] hash = digest.digest();

            sRet = getHex(hash);
        } catch (FileNotFoundException e) {
            sRet += " file not found";
        } catch (IOException e) {
            sRet += " io exception";
            e.printStackTrace();
        }
    }
    return (sRet);
}