Example usage for android.database Cursor getColumnName

List of usage examples for android.database Cursor getColumnName

Introduction

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

Prototype

String getColumnName(int columnIndex);

Source Link

Document

Returns the column name at the given zero-based column index.

Usage

From source file:com.kncwallet.wallet.ui.SendingAddressesFragment.java

@Override
public void onActivityCreated(final Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    setEmptyText(getString(R.string.address_book_empty_text));

    adapter = new SimpleCursorAdapter(activity, R.layout.address_book_row, null,
            new String[] { AddressBookProvider.KEY_RAW_TELEPHONE, AddressBookProvider.KEY_ADDRESS,
                    AddressBookProvider.KEY_LABEL, AddressBookProvider.KEY_ADDRESS,
                    AddressBookProvider.KEY_ADDRESS },
            new int[] { R.id.address_book_row_number, R.id.address_book_contact_image,
                    R.id.address_book_row_label, R.id.address_book_row_address,
                    R.id.address_book_row_source_image },
            0);/*from   w w  w .  j a va2  s  .  com*/
    adapter.setViewBinder(new ViewBinder() {
        @Override
        public boolean setViewValue(final View view, final Cursor cursor, final int columnIndex) {
            if (view.getId() == R.id.address_book_contact_image) {

                SmartImageView img = (SmartImageView) view;

                String address = cursor.getString(columnIndex);
                Bitmap contactImage = cachedBitmap(address);
                if (contactImage != null) {
                    img.setImageBitmap(contactImage);
                } else {

                    String imageUrl = cachedImageUrl(address);
                    if (imageUrl != null) {
                        img.setImageUrl(imageUrl, R.drawable.contact_placeholder);
                    } else {
                        img.setImageResource(R.drawable.contact_placeholder);
                    }
                }

                return true; //true because the data was bound to the view
            }

            if (view.getId() == R.id.address_book_row_number) {
                ((TextView) view).setText(cursor.getString(columnIndex));
                return true;
            }

            if (!AddressBookProvider.KEY_ADDRESS.equals(cursor.getColumnName(columnIndex)))
                return false;

            if (view.getId() == R.id.address_book_row_source_image) {
                ((ImageView) view).setImageResource(cachedSourceImageResource(cursor.getString(columnIndex)));
                view.setVisibility(View.VISIBLE);
                return true;
            }

            ((TextView) view).setText(WalletUtils.formatHash(cursor.getString(columnIndex),
                    Constants.ADDRESS_FORMAT_GROUP_SIZE, 24));

            return true;
        }
    });
    setListAdapter(adapter);

    loaderManager.initLoader(0, null, this);

    getListView().setCacheColorHint(Color.TRANSPARENT);
    getListView().setBackgroundColor(getResources().getColor(R.color.knc_background_darker));
    getView().setBackgroundColor(getResources().getColor(R.color.knc_background_darker));
}

From source file:com.android.contacts.common.list.ContactListItemView.java

/**
 * Shows search snippet.//from   w  w w.jav a 2 s  .  co m
 */
public void showSnippet(Cursor cursor, int summarySnippetColumnIndex) {
    if (cursor.getColumnCount() <= summarySnippetColumnIndex
            || !SearchSnippets.SNIPPET.equals(cursor.getColumnName(summarySnippetColumnIndex))) {
        setSnippet(null);
        return;
    }

    String snippet = cursor.getString(summarySnippetColumnIndex);

    // Do client side snippeting if provider didn't do it
    final Bundle extras = cursor.getExtras();
    if (extras.getBoolean(ContactsContract.DEFERRED_SNIPPETING)) {

        final String query = extras.getString(ContactsContract.DEFERRED_SNIPPETING_QUERY);

        String displayName = null;
        int displayNameIndex = cursor.getColumnIndex(Contacts.DISPLAY_NAME);
        if (displayNameIndex >= 0) {
            displayName = cursor.getString(displayNameIndex);
        }

        snippet = updateSnippet(snippet, query, displayName);

    } else {
        if (snippet != null) {
            int from = 0;
            int to = snippet.length();
            int start = snippet.indexOf(DefaultContactListAdapter.SNIPPET_START_MATCH);
            if (start == -1) {
                snippet = null;
            } else {
                int firstNl = snippet.lastIndexOf('\n', start);
                if (firstNl != -1) {
                    from = firstNl + 1;
                }
                int end = snippet.lastIndexOf(DefaultContactListAdapter.SNIPPET_END_MATCH);
                if (end != -1) {
                    int lastNl = snippet.indexOf('\n', end);
                    if (lastNl != -1) {
                        to = lastNl;
                    }
                }

                StringBuilder sb = new StringBuilder();
                for (int i = from; i < to; i++) {
                    char c = snippet.charAt(i);
                    if (c != DefaultContactListAdapter.SNIPPET_START_MATCH
                            && c != DefaultContactListAdapter.SNIPPET_END_MATCH) {
                        sb.append(c);
                    }
                }
                snippet = sb.toString();
            }
        }
    }

    setSnippet(snippet);
}

From source file:com.jsonstore.api.JSONStoreCollection.java

/**
 * Find documents in the collection that are based on the given query.
 *
 * @param query/*from  ww  w  . j  ava 2s  .  c om*/
 *             The find query that restricts the search.
 * @param options
 *             Additional options to modify the count operation.
 * @return   A list of documents.
 * @throws JSONStoreFindException
 *             An error occurred when trying to execute the find.
 * @throws JSONStoreFilterException
 *             An error occurred when trying to apply a filter to the query.
 * @throws JSONStoreDatabaseClosedException
 *             The JSONStore database is closed, and cannot be accessed to
 *             execute the find.
 */
public List<JSONObject> findDocuments(JSONStoreQueryParts query, JSONStoreFindOptions options)
        throws JSONStoreFindException, JSONStoreFilterException, JSONStoreDatabaseClosedException {
    JSONStoreAnalyticsLogInstance logInst = JSONStoreLogger.startAnalyticsInstance(getUsername(), getName(),
            JSONStoreLogger.OPERATION_FIND);
    try {
        getAccessor(); // This does some closed checks.
        if (options == null) {
            options = new JSONStoreFindOptions();
        }

        if (query == null) {
            query = new JSONStoreQueryParts();
        }

        QueryBuilderSelect selectQuery = new QueryBuilderSelect(this, query);
        selectQuery.setLimit(options.getLimit());
        selectQuery.setOffset(options.getOffset());
        selectQuery.setSort(options.getSort());

        if (options.shouldIncludeDeletedDocuments()) {
            selectQuery.setSearchIncludeDeleted();
        }

        LinkedHashMap<Integer, JSONObject> resultHash = new LinkedHashMap<Integer, JSONObject>();
        List<JSONObject> filterResults = new ArrayList<JSONObject>();

        // Set the fields to select in the query, if specified, otherwise default to _id and _json:
        Map<String, Boolean> filters = options.getSearchFilters();
        if (filters != null && filters.size() > 0) {
            for (String filter : filters.keySet()) {
                boolean isSpecial = filters.get(filter);
                selectQuery.addSelectStatement(filter, isSpecial);
            }
        } else {
            selectQuery.addSelectStatement(DatabaseConstants.FIELD_ID, false);
            selectQuery.addSelectStatement(DatabaseConstants.FIELD_JSON, false);
        }

        Cursor cursor = null;
        List<JSONObject> result = null;
        try {
            cursor = runQuery(selectQuery);
            if (cursor != null) {
                result = new LinkedList<JSONObject>();

                for (int j = 0; j < cursor.getCount(); ++j) {
                    JSONObject item = new JacksonSerializedJSONObject();

                    cursor.moveToNext();

                    for (int k = 0; k < cursor.getColumnNames().length; ++k) {
                        if (cursor.getColumnName(k).equals(DatabaseConstants.FIELD_ID)) {
                            item.put(cursor.getColumnName(k), cursor.getInt(k));
                        } else if (cursor.getColumnName(k).equals(DatabaseConstants.FIELD_JSON)) {
                            item.put(DatabaseConstants.FIELD_JSON,
                                    JsonOrgModule.deserializeJSONObject(cursor.getString(k)));
                        } else if (isJSONCreatedColumn(cursor.getColumnName(k))) {
                            item.put(cursor.getColumnName(k), cursor.getString(k));
                        } else {
                            item.put(cursor.getColumnName(k).replace("_", "."), cursor.getString(k)); //$NON-NLS-1$ //$NON-NLS-2$
                        }
                    }

                    result.add(item);
                }
            }
        } catch (Throwable e) {
            String message = "Error when attempting to find a document. An error occurred when reading from the database.";
            JSONStoreFindException jsException = new JSONStoreFindException(message, e);
            logger.logError(message, jsException);
            throw jsException;

        } finally {
            if (cursor != null)
                cursor.close();
        }

        if (options.getSearchFilters() != null) {
            for (JSONObject obj : result) {
                filterResults.add(obj);
            }
        } else {
            addNonDuplicates(resultHash, result);
        }

        List<JSONObject> results = null;

        if (options.getSearchFilters() != null) {
            results = removeFilterDuplicates(filterResults);
        } else {
            results = new ArrayList<JSONObject>(resultHash.values());
        }

        return results;
    } finally {
        logInst.end();
    }
}

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

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

    // Getting user configured(custom) SQLiteOpenHelper instance.
    sqliteOpenHelper = getDataBase();/*  w w  w  . j a  va  2 s.co m*/

    // 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:ru.orangesoftware.financisto2.export.flowzr.FlowzrSyncEngine.java

private JSONObject cursorToDict(String tableName, Cursor c) {
    int totalColumn = c.getColumnCount();
    JSONObject rowObject = new JSONObject();
    if (c.getColumnIndex("_id") != -1) {
        try {/*from   w w  w . j  a  v  a  2 s. c  o  m*/
            rowObject.put("_id", c.getInt(c.getColumnIndex("_id")));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    for (int i = 0; i < totalColumn; i++) {
        if (c.getColumnName(i) != null) {
            String colName = c.getColumnName(i);
            try {
                if (c.getString(i) != null) {
                    if (colName.endsWith("_id") || colName.equals("parent")) {
                        if (tableName.equals(DatabaseHelper.BUDGET_TABLE)) {
                            if (colName.equals("parent_budget_id")) {
                                rowObject.put(colName, c.getInt(i));
                            } else if (!colName.equals("_id")) {
                                String[] entities = c.getString(c.getColumnIndex(colName)).split(",");
                                String keys = "";
                                for (String entity_id2 : entities) {
                                    keys += getRemoteKey(getTableForColName(colName), entity_id2) + ",";
                                }
                                if (keys.endsWith(",")) {
                                    keys = keys.substring(0, keys.length() - 1);
                                }
                                rowObject.put(colName, keys);
                            }
                        } else {
                            if (!colName.equals("_id")) {
                                String k = getRemoteKey(getTableForColName(colName), c.getString(i));
                                if (k != null) {
                                    rowObject.put(colName, k);
                                } else {
                                    rowObject.put(colName, c.getInt(i));
                                }
                            }
                        }
                    } else {
                        rowObject.put(colName, c.getString(c.getColumnIndex(colName)));
                    }
                    /****/
                    if (tableName.equals(DatabaseHelper.ACCOUNT_TABLE)) {
                        String sql = "select max(dateTime) as maxDate, min(dateTime) as minDate from "
                                + DatabaseHelper.TRANSACTION_TABLE + " where from_account_id="
                                + c.getInt(c.getColumnIndex("_id"));
                        Cursor c2 = db.rawQuery(sql, null);
                        c2.moveToFirst();
                        rowObject.put("dateOfFirstTransaction", c2.getString(1));
                        rowObject.put("dateOfLastTransaction", c2.getString(0));
                        //each account can have a timezone so you can have a balance at closing day               
                        rowObject.put("tz", String.valueOf(TimeZone.getDefault().getRawOffset()));
                    } else if (tableName.equals(DatabaseHelper.CATEGORY_TABLE)) {
                        //load parent id
                        Category cat = dba.getCategory(c.getInt(0)); // sql build/load parentId   
                        if (cat.getParentId() > KEY_CREATE) {
                            Category pcat = dba.load(Category.class, cat.getParentId());
                            rowObject.put("parent", pcat.remoteKey);
                            rowObject.put("parent_id", pcat.id);
                        }
                        String attrPushString = "";

                        for (Attribute attr : dba.getAttributesForCategory(c.getInt(0))) {
                            attrPushString = attrPushString + attr.remoteKey + ";";
                        }
                        if (attrPushString != "") {
                            rowObject.put("attributes", attrPushString);
                        }
                    } else if (tableName.equals(DatabaseHelper.TRANSACTION_TABLE)) {
                        Map<Long, String> attributesMap = dba.getAllAttributesForTransaction(c.getInt(0));
                        String transaction_attribute = "";
                        for (long attributeId : attributesMap.keySet()) {
                            transaction_attribute += dba.get(Attribute.class, attributeId).remoteKey + "="
                                    + attributesMap.get(attributeId) + ";";
                        }
                        rowObject.put("transaction_attribute", transaction_attribute);
                    }
                    /****/
                } else {
                    rowObject.put(colName, "");
                }
            } catch (JSONException e) {
                Log.d(TAG, e.getMessage());
            }
        }
    }
    return rowObject;
}

From source file:org.opendatakit.services.forms.provider.FormsProvider.java

@Override
public synchronized int update(@NonNull Uri uri, ContentValues values, String where, String[] whereArgs) {
    possiblyWaitForContentProviderDebugger();

    List<String> segments = uri.getPathSegments();

    PatchedFilter pf = extractUriFeatures(uri, segments, where, whereArgs);
    WebLoggerIf logger = WebLogger.getLogger(pf.appName);

    /*//from  w w w.j a v a  2s  . c  o  m
     * First, find out what records match this query. Replicate the 
     * ContentValues if there are multiple tableIds/formIds involved
     * and the contentValues do not have formId and tableId specified.
     * 
     * Otherwise, it is an error to specify the tableId or formId in
     * the ContentValues and have those not match the where results.
     * 
     */
    String contentTableId = (values != null && values.containsKey(FormsColumns.TABLE_ID))
            ? values.getAsString(FormsColumns.TABLE_ID)
            : null;
    String contentFormId = (values != null && values.containsKey(FormsColumns.FORM_ID))
            ? values.getAsString(FormsColumns.FORM_ID)
            : null;

    HashMap<FormSpec, HashMap<String, Object>> matchedValues = new HashMap<FormSpec, HashMap<String, Object>>();

    DbHandle dbHandleName = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface()
            .generateInternalUseDbHandle();
    OdkConnectionInterface db = null;
    try {
        // +1 referenceCount if db is returned (non-null)
        db = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().getConnection(pf.appName,
                dbHandleName);
        db.beginTransactionNonExclusive();
        Cursor c = null;
        try {
            c = db.query(DatabaseConstants.FORMS_TABLE_NAME, null, pf.whereId, pf.whereIdArgs, null, null, null,
                    null);

            if (c == null) {
                throw new SQLException(
                        "FAILED Update of " + uri + " -- query for existing row did not return a cursor");
            }
            if (c.moveToFirst()) {
                int idxId = c.getColumnIndex(FormsColumns._ID);
                int idxTableId = c.getColumnIndex(FormsColumns.TABLE_ID);
                int idxFormId = c.getColumnIndex(FormsColumns.FORM_ID);

                Integer idValue = null;
                String tableIdValue = null;
                String formIdValue = null;

                do {
                    idValue = CursorUtils.getIndexAsType(c, Integer.class, idxId);
                    tableIdValue = CursorUtils.getIndexAsString(c, idxTableId);
                    formIdValue = CursorUtils.getIndexAsString(c, idxFormId);

                    if (contentTableId != null && !contentTableId.equals(tableIdValue)) {
                        throw new SQLException("Modification of tableId for an existing form is prohibited");
                    }
                    if (contentFormId != null && !contentFormId.equals(formIdValue)) {
                        throw new SQLException("Modification of formId for an existing form is prohibited");
                    }

                    HashMap<String, Object> cv = new HashMap<String, Object>();
                    if (values != null) {
                        for (String key : values.keySet()) {
                            cv.put(key, values.get(key));
                        }
                    }
                    cv.put(FormsColumns.TABLE_ID, tableIdValue);
                    cv.put(FormsColumns.FORM_ID, formIdValue);
                    for (int idx = 0; idx < c.getColumnCount(); ++idx) {
                        String colName = c.getColumnName(idx);
                        if (colName.equals(FormsColumns._ID)) {
                            // don't insert the PK
                            continue;
                        }

                        if (c.isNull(idx)) {
                            cv.put(colName, null);
                        } else {
                            // everything else, we control...
                            Class<?> dataType = CursorUtils.getIndexDataType(c, idx);
                            if (dataType == String.class) {
                                cv.put(colName, CursorUtils.getIndexAsString(c, idx));
                            } else if (dataType == Long.class) {
                                cv.put(colName, CursorUtils.getIndexAsType(c, Long.class, idx));
                            } else if (dataType == Double.class) {
                                cv.put(colName, CursorUtils.getIndexAsType(c, Double.class, idx));
                            }
                        }
                    }

                    FormSpec formSpec = patchUpValues(pf.appName, cv);
                    formSpec._id = idValue.toString();
                    formSpec.success = false;
                    matchedValues.put(formSpec, cv);

                } while (c.moveToNext());
            } else {
                // no match on where clause...
                return 0;
            }
        } finally {
            if (c != null && !c.isClosed()) {
                c.close();
            }
        }

        // go through the entries and update the database with these patched-up values...

        for (Entry<FormSpec, HashMap<String, Object>> e : matchedValues.entrySet()) {
            FormSpec fs = e.getKey();
            HashMap<String, Object> cv = e.getValue();

            if (db.update(DatabaseConstants.FORMS_TABLE_NAME, cv, FormsColumns._ID + "=?",
                    new String[] { fs._id }) > 0) {
                fs.success = true;
            }
        }
        db.setTransactionSuccessful();

    } catch (Exception e) {
        logger.w(t, "FAILED Update of " + uri + " -- query for existing row failed: " + e.toString());

        if (e instanceof SQLException) {
            throw (SQLException) e;
        } else {
            throw new SQLException(
                    "FAILED Update of " + uri + " -- query for existing row failed: " + e.toString());
        }
    } finally {
        if (db != null) {
            try {
                if (db.inTransaction()) {
                    db.endTransaction();
                }
            } finally {
                try {
                    db.releaseReference();
                } finally {
                    // this closes the connection
                    OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface()
                            .removeConnection(pf.appName, dbHandleName);
                }
            }
        }
    }

    int failureCount = 0;
    for (FormSpec fs : matchedValues.keySet()) {
        if (fs.success) {
            Uri formUri = Uri
                    .withAppendedPath(
                            Uri.withAppendedPath(Uri.withAppendedPath(
                                    Uri.parse("content://" + getFormsAuthority()), pf.appName), fs.tableId),
                            fs.formId);
            getContext().getContentResolver().notifyChange(formUri, null);
            Uri idUri = Uri.withAppendedPath(
                    Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), pf.appName), fs._id);
            getContext().getContentResolver().notifyChange(idUri, null);
        } else {
            ++failureCount;
        }
    }
    getContext().getContentResolver().notifyChange(uri, null);

    int count = matchedValues.size();
    if (failureCount != 0) {
        throw new SQLiteException(
                "Unable to update all forms (" + (count - failureCount) + " of " + count + " updated)");
    }
    return count;
}

From source file:it.bradipao.berengar.DbTool.java

public static int db2xml(SQLiteDatabase mDB, File xmlFile) {
    // vars//from  w w w  . jav  a 2s.com
    final String XML_DATABASE = "database";
    final String XML_DBNAME = "dbname";
    final String XML_TABLES = "tables";
    final String XML_TABLE = "table";
    final String XML_TABLENAME = "tablename";
    final String XML_TABLESQL = "tablesql";
    final String XML_COLSNAME = "colsname";
    final String XML_ROWS = "rows";
    final String XML_ROW = "r";
    final String XML_COL = "c";

    // tables list query and cursor
    int iTableNum = 0;
    FileWriter fw = null;
    BufferedWriter bw = null;
    XmlSerializer sr = Xml.newSerializer();

    String tblquery = "select * from sqlite_master";
    Cursor tblcur = mDB.rawQuery(tblquery, null);
    String rowquery = "";
    Cursor rowcur = null;

    // file writers
    try {
        fw = new FileWriter(xmlFile);
        bw = new BufferedWriter(fw);
        sr.setOutput(bw);
    } catch (FileNotFoundException e) {
        Log.e(LOGTAG, "error in db2gson file writers", e);
    } catch (IOException e) {
        Log.e(LOGTAG, "error in db2gson file writers", e);
    }
    // xml serializer

    try {
        // prepare xml document
        sr.startDocument("UTF-8", true);
        sr.setFeature("http://xmlpull.org/v1/doc/features.html#indent-output", true);

        // start document
        sr.startTag("", XML_DATABASE);
        sr.startTag("", XML_DBNAME);
        sr.text(xmlFile.getName());
        sr.endTag("", XML_DBNAME);
        sr.startTag("", XML_TABLES);

        // iterate through tables
        String sTableName = "";
        String sTableSql = "";
        while (tblcur.moveToNext()) {
            sTableName = tblcur.getString(tblcur.getColumnIndex("name"));
            sTableSql = tblcur.getString(tblcur.getColumnIndex("sql"));
            if (GOLOG)
                Log.d(LOGTAG, "TABLE NAME : " + sTableName);
            // skip metadata, sequence, and uidx before exporting tables
            if (!sTableName.equals("android_metadata") && !sTableName.equals("sqlite_sequence")
                    && !sTableName.startsWith("uidx") && !sTableName.startsWith("idx_")
                    && !sTableName.startsWith("_idx")) {

                // table query and cursor
                iTableNum++;
                rowquery = "select * from " + sTableName;
                rowcur = mDB.rawQuery(rowquery, null);
                // exporting table
                sr.startTag("", XML_TABLE);
                sr.startTag("", XML_TABLENAME);
                sr.text(sTableName);
                sr.endTag("", XML_TABLENAME);
                if ((sTableSql != null) && (!sTableSql.isEmpty())) {
                    sr.startTag("", XML_TABLESQL);
                    sr.text(sTableSql);
                    sr.endTag("", XML_TABLESQL);
                }
                // iteratew through rows
                int i = -1;
                while (rowcur.moveToNext()) {
                    // at first element store column names
                    if (i == -1) {
                        sr.startTag("", XML_COLSNAME);
                        for (i = 0; i < rowcur.getColumnCount(); i++) {
                            sr.startTag("", XML_COL);
                            sr.text(rowcur.getColumnName(i));
                            sr.endTag("", XML_COL);
                        }
                        sr.endTag("", XML_COLSNAME);
                        sr.startTag("", XML_ROWS);
                    }
                    // get values
                    sr.startTag("", XML_ROW);
                    for (i = 0; i < rowcur.getColumnCount(); i++) {
                        sr.startTag("", XML_COL);
                        sr.text(rowcur.getString(i));
                        sr.endTag("", XML_COL);
                    }
                    sr.endTag("", XML_ROW);
                }
                // finishing table query
                rowcur.close();
                sr.endTag("", XML_ROWS);
                sr.endTag("", XML_TABLE);

            }
        }
        // finishing table query
        tblcur.close();
        sr.endTag("", XML_TABLES);
        sr.endTag("", XML_DATABASE);

        // finishing
        sr.endDocument();
        sr.flush();

    } catch (Exception e) {
        Log.e(LOGTAG, "error in db2xml", e);
    }

    return iTableNum;
}

From source file:it.bradipao.berengar.DbTool.java

public static int db2gson(SQLiteDatabase mDB, File jsonFile) {
    // vars//from ww  w .  j a  va  2 s .  c  o  m
    int iTableNum = 0;
    FileWriter fw = null;
    BufferedWriter bw = null;
    JsonWriter jw = null;
    String sqlquery = "";
    Cursor cur = null;

    String mTable = null;
    String mTableSql = null;
    ArrayList<String> aTable = new ArrayList<String>();
    ArrayList<String> aTableSql = new ArrayList<String>();

    // file writers
    try {
        fw = new FileWriter(jsonFile);
        bw = new BufferedWriter(fw);
        jw = new JsonWriter(bw);
    } catch (FileNotFoundException e) {
        Log.e(LOGTAG, "error in db2gson file writers", e);
    } catch (IOException e) {
        Log.e(LOGTAG, "error in db2gson file writers", e);
    }

    // read tables list and extract name and createsql
    sqlquery = "select * from sqlite_master";
    cur = mDB.rawQuery(sqlquery, null);
    while (cur.moveToNext()) {
        mTable = cur.getString(cur.getColumnIndex("name"));
        mTableSql = cur.getString(cur.getColumnIndex("sql"));
        // add new table, and skip metadata, sequence, and uidx before exporting tables
        if (!mTable.equals("android_metadata") && !mTable.equals("sqlite_sequence")
                && !mTable.startsWith("uidx") && !mTable.startsWith("idx_") && !mTable.startsWith("_idx")) {
            iTableNum++;
            aTable.add(mTable);
            aTableSql.add(mTableSql);
            if (GOLOG)
                Log.d(LOGTAG, "TABLE NAME : " + mTable);
        }
    }
    cur.close();

    // start writing json
    try {
        // open root {
        jw.beginObject();
        // header elements
        jw.name("tables_num").value(Integer.toString(iTableNum));
        jw.name("jsondb_format").value("1");
        // tables name
        jw.name("tables_name");
        jw.beginArray();
        for (int i = 0; i < aTable.size(); i++)
            jw.value(aTable.get(i));
        jw.endArray();

        // open tables array
        jw.name("tables");
        jw.beginArray();
        // iterate through tables
        for (int i = 0; i < aTable.size(); i++) {
            // open table object
            jw.beginObject();
            // table name and table sql
            jw.name("table_name").value(aTable.get(i));
            jw.name("table_sql").value(aTableSql.get(i));
            // iteratew through rows
            sqlquery = "select * from " + aTable.get(i);
            cur = mDB.rawQuery(sqlquery, null);
            int k = -1;
            while (cur.moveToNext()) {
                if (k == -1) {
                    // column names generated at very first row
                    jw.name("cols_name");
                    jw.beginArray();
                    for (k = 0; k < cur.getColumnCount(); k++)
                        jw.value(cur.getColumnName(k));
                    jw.endArray();
                    // open rows array
                    jw.name("rows");
                    jw.beginArray();
                }
                // get columns values in row
                jw.beginArray();
                for (k = 0; k < cur.getColumnCount(); k++)
                    jw.value(cur.getString(k));
                jw.endArray();
            }
            // close rows array
            jw.endArray();
            // close table object
            jw.endObject();
        }
        // close tables array
        jw.endArray();

        // close root {
        jw.endObject();
        jw.close();
    } catch (IOException e) {
        Log.e(LOGTAG, "error in db2gson file writers", e);
    }

    // return number of tables
    return iTableNum;
}

From source file:org.opendatakit.survey.android.provider.SubmissionProvider.java

/**
 * The incoming URI is of the form:// ww w . jav  a 2  s.com
 * ..../appName/tableId/instanceId?formId=&formVersion=
 *
 * where instanceId is the DataTableColumns._ID
 */
@SuppressWarnings("unchecked")
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
    final boolean asXml = uri.getAuthority().equalsIgnoreCase(XML_SUBMISSION_AUTHORITY);

    if (mode != null && !mode.equals("r")) {
        throw new IllegalArgumentException("Only read access is supported");
    }

    // URI == ..../appName/tableId/instanceId?formId=&formVersion=

    List<String> segments = uri.getPathSegments();

    if (segments.size() != 4) {
        throw new IllegalArgumentException("Unknown URI (incorrect number of path segments!) " + uri);
    }

    final String appName = segments.get(0);
    ODKFileUtils.verifyExternalStorageAvailability();
    ODKFileUtils.assertDirectoryStructure(appName);
    WebLogger log = WebLogger.getLogger(appName);

    final String tableId = segments.get(1);
    final String instanceId = segments.get(2);
    final String submissionInstanceId = segments.get(3);

    SQLiteDatabase db = null;
    try {
        db = DatabaseFactory.get().getDatabase(getContext(), appName);

        boolean success = false;
        try {
            success = ODKDatabaseUtils.get().hasTableId(db, tableId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new SQLException("Unknown URI (exception testing for tableId) " + uri);
        }
        if (!success) {
            throw new SQLException("Unknown URI (missing data table for tableId) " + uri);
        }

        final String dbTableName = "\"" + tableId + "\"";

        // Get the table properties specific to XML submissions

        String xmlInstanceName = null;
        String xmlRootElementName = null;
        String xmlDeviceIdPropertyName = null;
        String xmlUserIdPropertyName = null;
        String xmlBase64RsaPublicKey = null;

        try {

            Cursor c = null;
            try {
                c = db.query(DatabaseConstants.KEY_VALUE_STORE_ACTIVE_TABLE_NAME,
                        new String[] { KeyValueStoreColumns.KEY, KeyValueStoreColumns.VALUE },
                        KeyValueStoreColumns.TABLE_ID + "=? AND " + KeyValueStoreColumns.PARTITION + "=? AND "
                                + KeyValueStoreColumns.ASPECT + "=? AND " + KeyValueStoreColumns.KEY
                                + " IN (?,?,?,?,?)",
                        new String[] { tableId, KeyValueStoreConstants.PARTITION_TABLE,
                                KeyValueStoreConstants.ASPECT_DEFAULT, KeyValueStoreConstants.XML_INSTANCE_NAME,
                                KeyValueStoreConstants.XML_ROOT_ELEMENT_NAME,
                                KeyValueStoreConstants.XML_DEVICE_ID_PROPERTY_NAME,
                                KeyValueStoreConstants.XML_USER_ID_PROPERTY_NAME,
                                KeyValueStoreConstants.XML_BASE64_RSA_PUBLIC_KEY },
                        null, null, null);
                if (c.getCount() > 0) {
                    c.moveToFirst();
                    int idxKey = c.getColumnIndex(KeyValueStoreColumns.KEY);
                    int idxValue = c.getColumnIndex(KeyValueStoreColumns.VALUE);
                    do {
                        String key = c.getString(idxKey);
                        String value = c.getString(idxValue);
                        if (KeyValueStoreConstants.XML_INSTANCE_NAME.equals(key)) {
                            xmlInstanceName = value;
                        } else if (KeyValueStoreConstants.XML_ROOT_ELEMENT_NAME.equals(key)) {
                            xmlRootElementName = value;
                        } else if (KeyValueStoreConstants.XML_DEVICE_ID_PROPERTY_NAME.equals(key)) {
                            xmlDeviceIdPropertyName = value;
                        } else if (KeyValueStoreConstants.XML_USER_ID_PROPERTY_NAME.equals(key)) {
                            xmlUserIdPropertyName = value;
                        } else if (KeyValueStoreConstants.XML_BASE64_RSA_PUBLIC_KEY.equals(key)) {
                            xmlBase64RsaPublicKey = value;
                        }
                    } while (c.moveToNext());
                }
            } finally {
                c.close();
                c = null;
            }

            ArrayList<ColumnDefinition> orderedDefns = TableUtil.get().getColumnDefinitions(db, appName,
                    tableId);

            // Retrieve the values of the record to be emitted...

            HashMap<String, Object> values = new HashMap<String, Object>();

            // issue query to retrieve the most recent non-checkpoint data record
            // for the instanceId
            StringBuilder b = new StringBuilder();
            b.append("SELECT * FROM ").append(dbTableName).append(" as T WHERE ").append(DataTableColumns.ID)
                    .append("=?").append(" AND ").append(DataTableColumns.SAVEPOINT_TYPE)
                    .append(" IS NOT NULL AND ").append(DataTableColumns.SAVEPOINT_TIMESTAMP)
                    .append("=(SELECT max(V.").append(DataTableColumns.SAVEPOINT_TIMESTAMP).append(") FROM ")
                    .append(dbTableName).append(" as V WHERE V.").append(DataTableColumns.ID).append("=T.")
                    .append(DataTableColumns.ID).append(" AND V.").append(DataTableColumns.SAVEPOINT_TYPE)
                    .append(" IS NOT NULL").append(")");

            String[] selectionArgs = new String[] { instanceId };
            FileSet freturn = new FileSet(appName);

            String datestamp = null;

            try {
                c = db.rawQuery(b.toString(), selectionArgs);
                b.setLength(0);

                if (c.moveToFirst() && c.getCount() == 1) {
                    String rowETag = null;
                    String filterType = null;
                    String filterValue = null;
                    String formId = null;
                    String locale = null;
                    String savepointType = null;
                    String savepointCreator = null;
                    String savepointTimestamp = null;
                    String instanceName = null;

                    // OK. we have the record -- work through all the terms
                    for (int i = 0; i < c.getColumnCount(); ++i) {
                        ColumnDefinition defn = null;
                        String columnName = c.getColumnName(i);
                        try {
                            defn = ColumnDefinition.find(orderedDefns, columnName);
                        } catch (IllegalArgumentException e) {
                            // ignore...
                        }
                        if (defn != null && !c.isNull(i)) {
                            if (xmlInstanceName != null && defn.getElementName().equals(xmlInstanceName)) {
                                instanceName = ODKDatabaseUtils.get().getIndexAsString(c, i);
                            }
                            // user-defined column
                            ElementType type = defn.getType();
                            ElementDataType dataType = type.getDataType();

                            log.i(t, "element type: " + defn.getElementType());
                            if (dataType == ElementDataType.integer) {
                                Integer value = ODKDatabaseUtils.get().getIndexAsType(c, Integer.class, i);
                                putElementValue(values, defn, value);
                            } else if (dataType == ElementDataType.number) {
                                Double value = ODKDatabaseUtils.get().getIndexAsType(c, Double.class, i);
                                putElementValue(values, defn, value);
                            } else if (dataType == ElementDataType.bool) {
                                Integer tmp = ODKDatabaseUtils.get().getIndexAsType(c, Integer.class, i);
                                Boolean value = tmp == null ? null : (tmp != 0);
                                putElementValue(values, defn, value);
                            } else if (type.getElementType().equals("date")) {
                                String value = ODKDatabaseUtils.get().getIndexAsString(c, i);
                                String jrDatestamp = (value == null) ? null
                                        : (new SimpleDateFormat(ISO8601_DATE_ONLY_FORMAT, Locale.ENGLISH))
                                                .format(new Date(TableConstants.milliSecondsFromNanos(value)));
                                putElementValue(values, defn, jrDatestamp);
                            } else if (type.getElementType().equals("dateTime")) {
                                String value = ODKDatabaseUtils.get().getIndexAsString(c, i);
                                String jrDatestamp = (value == null) ? null
                                        : (new SimpleDateFormat(ISO8601_DATE_FORMAT, Locale.ENGLISH))
                                                .format(new Date(TableConstants.milliSecondsFromNanos(value)));
                                putElementValue(values, defn, jrDatestamp);
                            } else if (type.getElementType().equals("time")) {
                                String value = ODKDatabaseUtils.get().getIndexAsString(c, i);
                                putElementValue(values, defn, value);
                            } else if (dataType == ElementDataType.array) {
                                ArrayList<Object> al = ODKDatabaseUtils.get().getIndexAsType(c, ArrayList.class,
                                        i);
                                putElementValue(values, defn, al);
                            } else if (dataType == ElementDataType.string) {
                                String value = ODKDatabaseUtils.get().getIndexAsString(c, i);
                                putElementValue(values, defn, value);
                            } else /* unrecognized */ {
                                throw new IllegalStateException(
                                        "unrecognized data type: " + defn.getElementType());
                            }

                        } else if (columnName.equals(DataTableColumns.SAVEPOINT_TIMESTAMP)) {
                            savepointTimestamp = ODKDatabaseUtils.get().getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.ROW_ETAG)) {
                            rowETag = ODKDatabaseUtils.get().getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.FILTER_TYPE)) {
                            filterType = ODKDatabaseUtils.get().getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.FILTER_VALUE)) {
                            filterValue = ODKDatabaseUtils.get().getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.FORM_ID)) {
                            formId = ODKDatabaseUtils.get().getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.LOCALE)) {
                            locale = ODKDatabaseUtils.get().getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.FORM_ID)) {
                            formId = ODKDatabaseUtils.get().getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.SAVEPOINT_TYPE)) {
                            savepointType = ODKDatabaseUtils.get().getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.SAVEPOINT_CREATOR)) {
                            savepointCreator = ODKDatabaseUtils.get().getIndexAsString(c, i);
                        }
                    }

                    // OK got all the values into the values map -- emit
                    // contents
                    b.setLength(0);
                    File submissionXml = new File(ODKFileUtils.getInstanceFolder(appName, tableId, instanceId),
                            (asXml ? "submission.xml" : "submission.json"));
                    File manifest = new File(ODKFileUtils.getInstanceFolder(appName, tableId, instanceId),
                            "manifest.json");
                    submissionXml.delete();
                    manifest.delete();
                    freturn.instanceFile = submissionXml;

                    if (asXml) {
                        // Pre-processing -- collapse all geopoints into a
                        // string-valued representation
                        for (ColumnDefinition defn : orderedDefns) {
                            ElementType type = defn.getType();
                            ElementDataType dataType = type.getDataType();
                            if (dataType == ElementDataType.object && (type.getElementType().equals("geopoint")
                                    || type.getElementType().equals("mimeUri"))) {
                                Map<String, Object> parent = null;
                                List<ColumnDefinition> parents = new ArrayList<ColumnDefinition>();
                                ColumnDefinition d = defn.getParent();
                                while (d != null) {
                                    parents.add(d);
                                    d = d.getParent();
                                }
                                parent = values;
                                for (int i = parents.size() - 1; i >= 0; --i) {
                                    Object o = parent.get(parents.get(i).getElementName());
                                    if (o == null) {
                                        parent = null;
                                        break;
                                    }
                                    parent = (Map<String, Object>) o;
                                }
                                if (parent != null) {
                                    Object o = parent.get(defn.getElementName());
                                    if (o != null) {
                                        if (type.getElementType().equals("geopoint")) {
                                            Map<String, Object> geopoint = (Map<String, Object>) o;
                                            // OK. we have geopoint -- get the
                                            // lat, long, alt, etc.
                                            Double latitude = (Double) geopoint.get("latitude");
                                            Double longitude = (Double) geopoint.get("longitude");
                                            Double altitude = (Double) geopoint.get("altitude");
                                            Double accuracy = (Double) geopoint.get("accuracy");
                                            String gpt = "" + latitude + " " + longitude + " " + altitude + " "
                                                    + accuracy;
                                            parent.put(defn.getElementName(), gpt);
                                        } else if (type.getElementType().equals("mimeUri")) {
                                            Map<String, Object> mimeuri = (Map<String, Object>) o;
                                            String uriFragment = (String) mimeuri.get("uriFragment");
                                            String contentType = (String) mimeuri.get("contentType");

                                            if (uriFragment != null) {
                                                File f = ODKFileUtils.getAsFile(appName, uriFragment);
                                                if (f.equals(manifest)) {
                                                    throw new IllegalStateException(
                                                            "Unexpected collision with manifest.json");
                                                }
                                                freturn.addAttachmentFile(f, contentType);
                                                parent.put(defn.getElementName(), f.getName());
                                            }
                                        } else {
                                            throw new IllegalStateException("Unhandled transform case");
                                        }
                                    }
                                }
                            }
                        }

                        datestamp = (new SimpleDateFormat(ISO8601_DATE_FORMAT, Locale.ENGLISH))
                                .format(new Date(TableConstants.milliSecondsFromNanos(savepointTimestamp)));

                        // For XML, we traverse the map to serialize it
                        Document d = new Document();
                        d.setStandalone(true);
                        d.setEncoding(CharEncoding.UTF_8);
                        Element e = d.createElement(XML_DEFAULT_NAMESPACE,
                                (xmlRootElementName == null) ? "data" : xmlRootElementName);
                        e.setPrefix("jr", XML_OPENROSA_NAMESPACE);
                        e.setPrefix("", XML_DEFAULT_NAMESPACE);
                        d.addChild(0, Node.ELEMENT, e);
                        e.setAttribute("", "id", tableId);
                        DynamicPropertiesCallback cb = new DynamicPropertiesCallback(getContext(), appName,
                                tableId, instanceId);

                        int idx = 0;
                        Element meta = d.createElement(XML_OPENROSA_NAMESPACE, "meta");

                        Element v = d.createElement(XML_OPENROSA_NAMESPACE, "instanceID");
                        v.addChild(0, Node.TEXT, submissionInstanceId);
                        meta.addChild(idx++, Node.ELEMENT, v);
                        meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);

                        if (xmlDeviceIdPropertyName != null) {
                            String deviceId = propertyManager.getSingularProperty(xmlDeviceIdPropertyName, cb);
                            if (deviceId != null) {
                                v = d.createElement(XML_OPENROSA_NAMESPACE, "deviceID");
                                v.addChild(0, Node.TEXT, deviceId);
                                meta.addChild(idx++, Node.ELEMENT, v);
                                meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);
                            }
                        }
                        if (xmlUserIdPropertyName != null) {
                            String userId = propertyManager.getSingularProperty(xmlUserIdPropertyName, cb);
                            if (userId != null) {
                                v = d.createElement(XML_OPENROSA_NAMESPACE, "userID");
                                v.addChild(0, Node.TEXT, userId);
                                meta.addChild(idx++, Node.ELEMENT, v);
                                meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);
                            }
                        }
                        v = d.createElement(XML_OPENROSA_NAMESPACE, "timeEnd");
                        v.addChild(0, Node.TEXT, datestamp);
                        meta.addChild(idx++, Node.ELEMENT, v);
                        meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);

                        // these are extra metadata tags...
                        if (instanceName != null) {
                            v = d.createElement(XML_DEFAULT_NAMESPACE, "instanceName");
                            v.addChild(0, Node.TEXT, instanceName);
                            meta.addChild(idx++, Node.ELEMENT, v);
                            meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);
                        } else {
                            v = d.createElement(XML_DEFAULT_NAMESPACE, "instanceName");
                            v.addChild(0, Node.TEXT, savepointTimestamp);
                            meta.addChild(idx++, Node.ELEMENT, v);
                            meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);
                        }

                        // these are extra metadata tags...
                        // rowID
                        v = d.createElement(XML_DEFAULT_NAMESPACE, "rowID");
                        v.addChild(0, Node.TEXT, instanceId);
                        meta.addChild(idx++, Node.ELEMENT, v);
                        meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);

                        // rowETag
                        v = d.createElement(XML_DEFAULT_NAMESPACE, "rowETag");
                        if (rowETag != null) {
                            v.addChild(0, Node.TEXT, rowETag);
                        }
                        meta.addChild(idx++, Node.ELEMENT, v);
                        meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);

                        // filterType
                        v = d.createElement(XML_DEFAULT_NAMESPACE, "filterType");
                        if (filterType != null) {
                            v.addChild(0, Node.TEXT, filterType);
                        }
                        meta.addChild(idx++, Node.ELEMENT, v);
                        meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);

                        // filterValue
                        v = d.createElement(XML_DEFAULT_NAMESPACE, "filterValue");
                        if (filterValue != null) {
                            v.addChild(0, Node.TEXT, filterValue);
                        }
                        meta.addChild(idx++, Node.ELEMENT, v);
                        meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);

                        // formID
                        v = d.createElement(XML_DEFAULT_NAMESPACE, "formID");
                        v.addChild(0, Node.TEXT, formId);
                        meta.addChild(idx++, Node.ELEMENT, v);
                        meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);

                        // locale
                        v = d.createElement(XML_DEFAULT_NAMESPACE, "locale");
                        v.addChild(0, Node.TEXT, locale);
                        meta.addChild(idx++, Node.ELEMENT, v);
                        meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);

                        // savepointType
                        v = d.createElement(XML_DEFAULT_NAMESPACE, "savepointType");
                        v.addChild(0, Node.TEXT, savepointType);
                        meta.addChild(idx++, Node.ELEMENT, v);
                        meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);

                        // savepointCreator
                        v = d.createElement(XML_DEFAULT_NAMESPACE, "savepointCreator");
                        if (savepointCreator != null) {
                            v.addChild(0, Node.TEXT, savepointCreator);
                        }
                        meta.addChild(idx++, Node.ELEMENT, v);
                        meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);

                        // savepointTimestamp
                        v = d.createElement(XML_DEFAULT_NAMESPACE, "savepointTimestamp");
                        v.addChild(0, Node.TEXT, savepointTimestamp);
                        meta.addChild(idx++, Node.ELEMENT, v);
                        meta.addChild(idx++, Node.IGNORABLE_WHITESPACE, NEW_LINE);

                        // and insert the meta block into the XML

                        e.addChild(0, Node.IGNORABLE_WHITESPACE, NEW_LINE);
                        e.addChild(1, Node.ELEMENT, meta);
                        e.addChild(2, Node.IGNORABLE_WHITESPACE, NEW_LINE);

                        idx = 3;
                        ArrayList<String> entryNames = new ArrayList<String>();
                        entryNames.addAll(values.keySet());
                        Collections.sort(entryNames);
                        for (String name : entryNames) {
                            idx = generateXmlHelper(d, e, idx, name, values, log);
                        }

                        KXmlSerializer serializer = new KXmlSerializer();

                        ByteArrayOutputStream bo = new ByteArrayOutputStream();
                        serializer.setOutput(bo, CharEncoding.UTF_8);
                        // setting the response content type emits the
                        // xml header.
                        // just write the body here...
                        d.writeChildren(serializer);
                        serializer.flush();
                        bo.close();

                        b.append(bo.toString(CharEncoding.UTF_8));

                        // OK we have the document in the builder (b).
                        String doc = b.toString();

                        freturn.instanceFile = submissionXml;

                        // see if the form is encrypted and we can
                        // encrypt it...
                        EncryptedFormInformation formInfo = EncryptionUtils.getEncryptedFormInformation(appName,
                                tableId, xmlBase64RsaPublicKey, instanceId);
                        if (formInfo != null) {
                            File submissionXmlEnc = new File(submissionXml.getParentFile(),
                                    submissionXml.getName() + ".enc");
                            submissionXmlEnc.delete();
                            // if we are encrypting, the form cannot be
                            // reopened afterward
                            // and encrypt the submission (this is a
                            // one-way operation)...
                            if (!EncryptionUtils.generateEncryptedSubmission(freturn, doc, submissionXml,
                                    submissionXmlEnc, formInfo)) {
                                return null;
                            }
                            // at this point, the freturn object has
                            // been re-written with the encrypted media
                            // and xml files.
                        } else {
                            exportFile(doc, submissionXml, log);
                        }

                    } else {
                        // Pre-processing -- collapse all mimeUri into filename
                        for (ColumnDefinition defn : orderedDefns) {
                            ElementType type = defn.getType();
                            ElementDataType dataType = type.getDataType();

                            if (dataType == ElementDataType.object && type.getElementType().equals("mimeUri")) {
                                Map<String, Object> parent = null;
                                List<ColumnDefinition> parents = new ArrayList<ColumnDefinition>();
                                ColumnDefinition d = defn.getParent();
                                while (d != null) {
                                    parents.add(d);
                                    d = d.getParent();
                                }
                                parent = values;
                                for (int i = parents.size() - 1; i >= 0; --i) {
                                    Object o = parent.get(parents.get(i).getElementName());
                                    if (o == null) {
                                        parent = null;
                                        break;
                                    }
                                    parent = (Map<String, Object>) o;
                                }
                                if (parent != null) {
                                    Object o = parent.get(defn.getElementName());
                                    if (o != null) {
                                        if (dataType == ElementDataType.object
                                                && type.getElementType().equals("mimeUri")) {
                                            Map<String, Object> mimeuri = (Map<String, Object>) o;
                                            String uriFragment = (String) mimeuri.get("uriFragment");
                                            String contentType = (String) mimeuri.get("contentType");
                                            File f = ODKFileUtils.getAsFile(appName, uriFragment);
                                            if (f.equals(manifest)) {
                                                throw new IllegalStateException(
                                                        "Unexpected collision with manifest.json");
                                            }
                                            freturn.addAttachmentFile(f, contentType);
                                            parent.put(defn.getElementName(), f.getName());
                                        } else {
                                            throw new IllegalStateException("Unhandled transform case");
                                        }
                                    }
                                }
                            }
                        }

                        // For JSON, we construct the model, then emit model +
                        // meta + data
                        HashMap<String, Object> wrapper = new HashMap<String, Object>();
                        wrapper.put("tableId", tableId);
                        wrapper.put("instanceId", instanceId);
                        HashMap<String, Object> formDef = new HashMap<String, Object>();
                        formDef.put("table_id", tableId);
                        formDef.put("model", ColumnDefinition.getDataModel(orderedDefns));
                        wrapper.put("formDef", formDef);
                        wrapper.put("data", values);
                        wrapper.put("metadata", new HashMap<String, Object>());
                        HashMap<String, Object> elem = (HashMap<String, Object>) wrapper.get("metadata");
                        if (instanceName != null) {
                            elem.put("instanceName", instanceName);
                        }
                        elem.put("saved", "COMPLETE");
                        elem.put("timestamp", datestamp);

                        b.append(ODKFileUtils.mapper.writeValueAsString(wrapper));

                        // OK we have the document in the builder (b).
                        String doc = b.toString();
                        exportFile(doc, submissionXml, log);
                    }
                    exportFile(freturn.serializeUriFragmentList(getContext()), manifest, log);
                    return ParcelFileDescriptor.open(manifest, ParcelFileDescriptor.MODE_READ_ONLY);

                }
            } finally {
                if (c != null && !c.isClosed()) {
                    c.close();
                }
            }

        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    } finally {
        if (db != null) {
            db.close();
        }
    }
    return null;
}

From source file:org.opendatakit.services.database.utlities.ODKDatabaseImplUtils.java

private BaseTable buildBaseTable(OdkConnectionInterface db, Cursor c, String tableId, boolean canCreateRow) {

    HashMap<String, Integer> mElementKeyToIndex = null;
    String[] mElementKeyForIndex = null;

    if (!c.moveToFirst()) {

        // Attempt to retrieve the columns from the cursor.
        // These may not be available if there were no rows returned.
        // It depends upon the cursor implementation.
        try {/*  w  ww.ja  va2 s  .c  o  m*/
            int columnCount = c.getColumnCount();
            mElementKeyForIndex = new String[columnCount];
            mElementKeyToIndex = new HashMap<>(columnCount);
            int i;

            for (i = 0; i < columnCount; ++i) {
                String columnName = c.getColumnName(i);
                mElementKeyForIndex[i] = columnName;
                mElementKeyToIndex.put(columnName, i);
            }
        } catch (Exception e) {
            // ignore.
        }

        // if they were not available, declare an empty array.
        if (mElementKeyForIndex == null) {
            mElementKeyForIndex = new String[0];
        }
        c.close();

        // we have no idea what the table should contain because it has no rows...
        BaseTable table = new BaseTable(null, mElementKeyForIndex, mElementKeyToIndex, 0);
        table.setEffectiveAccessCreateRow(canCreateRow);
        return table;
    }

    int rowCount = c.getCount();
    int columnCount = c.getColumnCount();

    BaseTable table = null;

    // These maps will map the element key to the corresponding index in
    // either data or metadata. If the user has defined a column with the
    // element key _my_data, and this column is at index 5 in the data
    // array, dataKeyToIndex would then have a mapping of _my_data:5.
    // The sync_state column, if present at index 7, would have a mapping
    // in metadataKeyToIndex of sync_state:7.
    mElementKeyForIndex = new String[columnCount];
    mElementKeyToIndex = new HashMap<>(columnCount);

    int i;

    for (i = 0; i < columnCount; ++i) {
        String columnName = c.getColumnName(i);
        mElementKeyForIndex[i] = columnName;
        mElementKeyToIndex.put(columnName, i);
    }

    table = new BaseTable(null, mElementKeyForIndex, mElementKeyToIndex, rowCount);

    String[] rowData = new String[columnCount];
    do {
        // First get the user-defined data for this row.
        for (i = 0; i < columnCount; i++) {
            String value = CursorUtils.getIndexAsString(c, i);
            rowData[i] = value;
        }

        Row nextRow = new Row(rowData.clone(), table);
        table.addRow(nextRow);
    } while (c.moveToNext());
    c.close();

    table.setEffectiveAccessCreateRow(canCreateRow);

    if (tableId != null) {
        table.setMetaDataRev(getTableDefinitionRevId(db, tableId));
    }
    return table;
}