Example usage for android.net Uri getAuthority

List of usage examples for android.net Uri getAuthority

Introduction

In this page you can find the example usage for android.net Uri getAuthority.

Prototype

@Nullable
public abstract String getAuthority();

Source Link

Document

Gets the decoded authority part of this URI.

Usage

From source file:net.sf.xfd.provider.ProviderBase.java

void assertAbsolute(Uri uri) throws FileNotFoundException {
    if (uri == null || !authority.equals(uri.getAuthority()) || uri.getPath() == null) {
        throw new FileNotFoundException();
    }/*w  w w .  j  a  va  2s.c  om*/

    assertAbsolute(uri.getPath());
}

From source file:com.supremainc.biostar2.user.MyProfileFragment.java

public void getImageUrlWithAuthority(Uri uri) {
    if (uri == null) {
        return;/*from ww  w. j  a  v  a 2  s . c o  m*/
    }
    InputStream is = null;
    if (uri.getAuthority() != null) {
        try {
            is = mContext.getContentResolver().openInputStream(uri);
            Bitmap bmp = BitmapFactory.decodeStream(is);
            setImage(ImageUtil.resizeBitmap(bmp, Setting.USER_PROFILE_IMAGE_SIZE, true));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return;
}

From source file:mobisocial.musubi.ui.FeedListActivity.java

protected void doHandleInput(Uri uri) {
    if (DBG)//from w  ww  . j av a  2s . co m
        Log.d(TAG, "Handling input uri " + uri);
    if (uri == null) {
        return;
    }

    if (uri.getScheme() == null) {
        Log.w(TAG, "Null uri scheme for " + uri);
        return;
    }

    //TODO: if there are URI's that are opened with the FeedListActivity that we want to 
    //handle, e.g. an NFC url, then we put that code here.  We used to have friend invites
    //but now we don't have to worry about that. 

    //If we want to share a URL that opens a specific Musubi feed, then we need to create a 
    //URL that links to it without giving away the secret feed capability.
    if (uri.getScheme().equals("content")) {
        if (uri.getAuthority().equals("vnd.mobisocial.db")) {
            if (uri.getPath().startsWith("/feed")) {
                //                    Intent view = new Intent(Intent.ACTION_VIEW, uri);
                //                    view.addCategory(Intent.CATEGORY_DEFAULT);
                //                    // TODO: fix in AndroidManifest.
                //                    //view.setClass(this, FeedActivity.class);
                //                    view.setClass(this, FeedHomeActivity.class);
                //                    startActivity(view);
                //                    finish();
                //                    return;
            }
        }
    }

    // Re-push the contact info ndef
    pushContactInfoViaNfc();
}

From source file:com.github.michalbednarski.intentslab.editor.IntentGeneralFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    super.onCreateView(inflater, container, savedInstanceState);

    View v = inflater.inflate(R.layout.intent_editor_general, container, false);

    // Prepare form
    mActionText = (AutoCompleteTextView) v.findViewById(R.id.action);
    mActionsSpinner = (Spinner) v.findViewById(R.id.action_spinner);
    mDataText = (AutoCompleteTextView) v.findViewById(R.id.data);
    mDataTextWrapper = v.findViewById(R.id.data_wrapper);
    mDataTextHeader = v.findViewById(R.id.data_header);
    mDataTypeHeader = v.findViewById(R.id.data_type_header);
    mDataTypeText = (TextView) v.findViewById(R.id.data_type);
    mDataTypeSpinner = (Spinner) v.findViewById(R.id.data_type_spinner);
    mDataTypeSpinnerWrapper = v.findViewById(R.id.data_type_spinner_wrapper);
    mDataTypeSlash = v.findViewById(R.id.data_type_slash);
    mDataSubtypeText = (TextView) v.findViewById(R.id.data_type_after_slash);
    mComponentText = (TextView) v.findViewById(R.id.component);

    mComponentTypeSpinner = (Spinner) v.findViewById(R.id.componenttype);
    mComponentTypeSpinner.setAdapter(new ArrayAdapter<String>(getActivity(),
            android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.componenttypes)));

    mMethodSpinner = (Spinner) v.findViewById(R.id.method);

    mCategoriesContainer = (ViewGroup) v.findViewById(R.id.categories);
    mAddCategoryButton = (Button) v.findViewById(R.id.category_add);
    mCategoriesHeader = v.findViewById(R.id.categories_header);
    mResponseCodeTextView = (TextView) v.findViewById(R.id.response_code);
    mPackageNameText = (AutoCompleteTextView) v.findViewById(R.id.package_name);

    mResultCodeWrapper = v.findViewById(R.id.result_intent_wrapper);
    mComponentTypeAndMethodSpinners = v.findViewById(R.id.component_and_method_spinners);
    mComponentHeader = v.findViewById(R.id.component_header);
    mComponentFieldWithButtons = v.findViewById(R.id.component_field_with_buttons);
    mPackageNameHeader = v.findViewById(R.id.package_name_header);
    mIntentTrackerSummary = (TextView) v.findViewById(R.id.intent_tracker_summary);
    mIntentTrackerSummary.setMovementMethod(LinkMovementMethod.getInstance());

    // Apparently using android:scrollHorizontally="true" does not work.
    // http://stackoverflow.com/questions/9011944/android-ice-cream-sandwich-edittext-disabling-spell-check-and-word-wrap
    mComponentText.setHorizontallyScrolling(true);

    // Bind button actions (android:onClick="" applies to hosting activity)
    mAddCategoryButton.setOnClickListener(new OnClickListener() {
        @Override//w  w  w .  j  ava 2s. c o  m
        public void onClick(View v) {
            addCategoryTextField("");
        }
    });
    v.findViewById(R.id.component_pick).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            pickComponent();
        }
    });
    v.findViewById(R.id.component_pick).setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            findComponent();
            return true;
        }
    });
    v.findViewById(R.id.component_clear).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            mComponentText.setText("");
        }
    });
    v.findViewById(R.id.data_query_button).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            getIntentEditor().updateIntent();
            startActivity(
                    new Intent(getActivity(), AdvancedQueryActivity.class).setData(mEditedIntent.getData()));
        }
    });
    v.findViewById(R.id.data_query_button)
            .setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
                @Override
                public void onCreateContextMenu(ContextMenu menu, View v,
                        ContextMenu.ContextMenuInfo menuInfo) {
                    getIntentEditor().updateIntent();
                    final Uri uri = mEditedIntent.getData();
                    if (uri != null) {
                        final String scheme = uri.getScheme();
                        final String authority = uri.getAuthority();
                        if ("content".equals(scheme) && authority != null) {
                            menu.add("Wrap").setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                                @Override
                                public boolean onMenuItemClick(MenuItem item) {
                                    mDataText.setText("content://" + ((mEditedIntent.getFlags()
                                            & (Intent.FLAG_GRANT_READ_URI_PERMISSION
                                                    | Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) != 0
                                                            ? ProxyProviderForGrantUriPermission.AUTHORITY
                                                            : ProxyProvider.AUTHORITY)
                                            + "/" + authority + uri.getPath());
                                    return true;
                                }
                            });
                        }
                    }
                }
            });

    // Set up autocomplete
    mUriAutocompleteAdapter = new UriAutocompleteAdapter(getActivity());
    mDataText.setAdapter(mUriAutocompleteAdapter);
    mPackageNameText.setAdapter(new PackageNameAutocompleteAdapter(getActivity()));

    // Get edited intent for form filling
    mEditedIntent = getEditedIntent();

    // Component field, affects options menu
    if (mEditedIntent.getComponent() != null) {
        mComponentText.setText(mEditedIntent.getComponent().flattenToShortString());
    }
    mComponentText.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            updateIntentComponent();
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });

    // Fill the form
    setupActionSpinnerOrField();
    updateNonActionIntentFilter(true);
    mDataText.setText(mEditedIntent.getDataString());
    mPackageNameText.setText(mEditedIntent.getPackage());

    showOrHideFieldsForResultIntent();
    showOrHideAdvancedFields();
    if (getComponentType() == IntentEditorConstants.RESULT) {
        mResponseCodeTextView.setText(String.valueOf(getIntentEditor().getMethodId()));
        mResponseCodeTextView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                try {
                    getIntentEditor().setMethodId(Integer.parseInt(s.toString()));
                    mResponseCodeTextView.setError(null);
                } catch (NumberFormatException e) {
                    mResponseCodeTextView.setError(getIntentEditor().getText(R.string.value_parse_error));
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    } else {
        initComponentAndMethodSpinners();
    }

    setupActionAutocomplete();

    // Prepare intent tracker
    {
        IntentTracker tracker = getIntentEditor().getIntentTracker();
        if (tracker != null) {
            tracker.setUpdateListener(this, true);
        } else {
            onNoTracker();
        }
    }

    return v;
}

From source file:com.silentcircle.contacts.group.GroupEditorFragment.java

public void onSaveCompleted(boolean hadChanges, Uri groupUri) {
    boolean success = groupUri != null;
    Log.d(TAG, "onSaveCompleted(" + groupUri + ")");
    if (hadChanges) {
        Toast.makeText(mContext, success ? R.string.groupSavedToast : R.string.groupSavedErrorToast,
                Toast.LENGTH_SHORT).show();
    }/* ww  w.  j a  v  a2s . co m*/
    final Intent resultIntent;
    final int resultCode;
    if (success && groupUri != null) {
        final String requestAuthority = groupUri.getAuthority();

        resultIntent = new Intent();
        // Otherwise pass back the given Uri
        resultIntent.setData(groupUri);
        resultCode = Activity.RESULT_OK;
    } else {
        resultCode = Activity.RESULT_CANCELED;
        resultIntent = null;
    }
    // It is already saved, so prevent that it is saved again
    mStatus = Status.CLOSING;
    if (mListener != null) {
        mListener.onSaveFinished(resultCode, resultIntent);
    }
}

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

/**
 * The incoming URI is of the form://w ww.  j  av  a2s  .c o  m
 * ..../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:com.android.mail.browse.ConversationCursor.java

/**
 * Regenerate the original Uri from a forwarding (ConversationProvider) Uri
 * NOTE: See note above for uriToCachingUri
 * @param uri the forwarding Uri//  w ww.j a  v a2  s . c  om
 * @return the original Uri
 */
private static Uri uriFromCachingUri(Uri uri) {
    String authority = uri.getAuthority();
    // Don't modify uri's that aren't ours
    if (!authority.equals(ConversationProvider.AUTHORITY)) {
        return uri;
    }
    List<String> path = uri.getPathSegments();
    Uri.Builder builder = new Uri.Builder().scheme(uri.getScheme()).authority(path.get(0));
    for (int i = 1; i < path.size(); i++) {
        builder.appendPath(path.get(i));
    }
    return builder.build();
}

From source file:com.aniruddhc.acemusic.player.LauncherActivity.LauncherActivity.java

/** Given a URI, returns a map of campaign data that can be sent with
 * any GA hit.//from   w  w w.  j av  a 2  s  . com
 *
 * @param uri A hierarchical URI that may or may not have campaign data
 *     stored in query parameters.
 *
 * @return A map that may contain campaign or referrer
 *     that may be sent with any Google Analytics hit.
    */
private Map<String, String> getReferrerMapFromUri(Uri uri) {
    MapBuilder paramMap = new MapBuilder();

    //If no URI, return an empty Map.
    if (uri == null) {
        return paramMap.build();
    }

    /* Source is the only required campaign field. No need to continue if not
     * present. */
    if (uri.getQueryParameter(CAMPAIGN_SOURCE_PARAM) != null) {

        /* MapBuilder.setCampaignParamsFromUrl parses Google Analytics campaign
         * ("UTM") parameters from a string URL into a Map that can be set on
         * the Tracker. */
        paramMap.setCampaignParamsFromUrl(uri.toString());

        /* If no source parameter, set authority to source and medium to
         * "referral". */
    } else if (uri.getAuthority() != null) {
        paramMap.set(Fields.CAMPAIGN_MEDIUM, "referral");
        paramMap.set(Fields.CAMPAIGN_SOURCE, uri.getAuthority());
    }

    return paramMap.build();
}

From source file:org.opendatakit.services.submissions.provider.SubmissionProvider.java

/**
 * The incoming URI is of the form://w  w  w.  j  a v a  2s  . c  o  m
 * ..../appName/tableId/instanceId?formId=&formVersion=
 *
 * where instanceId is the DataTableColumns._ID
 */
@SuppressWarnings("unchecked")
@Override
public ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode) throws FileNotFoundException {

    possiblyWaitForContentProviderDebugger();

    final boolean asXml = uri.getAuthority().equalsIgnoreCase(ProviderConsts.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);
    }

    PropertyManager propertyManager = new PropertyManager(getContext());

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

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

    PropertiesSingleton props = CommonToolProperties.get(getContext(), appName);
    String userEmail = props.getProperty(CommonToolProperties.KEY_ACCOUNT);
    String username = props.getProperty(CommonToolProperties.KEY_USERNAME);
    String activeUser = props.getActiveUser();
    String rolesList = props.getProperty(CommonToolProperties.KEY_ROLES_LIST);
    String currentLocale = props.getLocale();

    DbHandle dbHandleName = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface()
            .generateInternalUseDbHandle();
    OdkConnectionInterface db = null;
    try {
        // +1 referenceCount if db is returned (non-null)
        db = OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().getConnection(appName,
                dbHandleName);

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

        // 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, null);
                c.moveToFirst();

                if (c.getCount() > 0) {
                    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;
            }

            OrderedColumns orderedDefns = ODKDatabaseImplUtils.get().getUserDefinedColumns(db, 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(tableId).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(tableId).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 {

                ODKDatabaseImplUtils.AccessContext accessContext = ODKDatabaseImplUtils.get()
                        .getAccessContext(db, tableId, activeUser, rolesList);

                c = ODKDatabaseImplUtils.get().rawQuery(db, b.toString(), selectionArgs, null, accessContext);
                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 = orderedDefns.find(columnName);
                        } catch (IllegalArgumentException e) {
                            // ignore...
                        }
                        if (defn != null && !c.isNull(i)) {
                            if (xmlInstanceName != null && defn.getElementName().equals(xmlInstanceName)) {
                                instanceName = CursorUtils.getIndexAsString(c, i);
                            }
                            // user-defined column
                            ElementType type = defn.getType();
                            ElementDataType dataType = type.getDataType();

                            logger.i(t, "element type: " + defn.getElementType());
                            if (dataType == ElementDataType.integer) {
                                Integer value = CursorUtils.getIndexAsType(c, Integer.class, i);
                                putElementValue(values, defn, value);
                            } else if (dataType == ElementDataType.number) {
                                Double value = CursorUtils.getIndexAsType(c, Double.class, i);
                                putElementValue(values, defn, value);
                            } else if (dataType == ElementDataType.bool) {
                                Integer tmp = CursorUtils.getIndexAsType(c, Integer.class, i);
                                Boolean value = tmp == null ? null : (tmp != 0);
                                putElementValue(values, defn, value);
                            } else if (type.getElementType().equals("date")) {
                                String value = CursorUtils.getIndexAsString(c, i);
                                String jrDatestamp = (value == null) ? null
                                        : (new SimpleDateFormat(ISO8601_DATE_ONLY_FORMAT, Locale.US))
                                                .format(new Date(TableConstants.milliSecondsFromNanos(value)));
                                putElementValue(values, defn, jrDatestamp);
                            } else if (type.getElementType().equals("dateTime")) {
                                String value = CursorUtils.getIndexAsString(c, i);
                                String jrDatestamp = (value == null) ? null
                                        : (new SimpleDateFormat(ISO8601_DATE_FORMAT, Locale.US))
                                                .format(new Date(TableConstants.milliSecondsFromNanos(value)));
                                putElementValue(values, defn, jrDatestamp);
                            } else if (type.getElementType().equals("time")) {
                                String value = CursorUtils.getIndexAsString(c, i);
                                putElementValue(values, defn, value);
                            } else if (dataType == ElementDataType.array) {
                                ArrayList<Object> al = CursorUtils.getIndexAsType(c, ArrayList.class, i);
                                putElementValue(values, defn, al);
                            } else if (dataType == ElementDataType.string) {
                                String value = CursorUtils.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 = CursorUtils.getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.ROW_ETAG)) {
                            rowETag = CursorUtils.getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.FILTER_TYPE)) {
                            filterType = CursorUtils.getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.FILTER_VALUE)) {
                            filterValue = CursorUtils.getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.FORM_ID)) {
                            formId = CursorUtils.getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.LOCALE)) {
                            locale = CursorUtils.getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.FORM_ID)) {
                            formId = CursorUtils.getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.SAVEPOINT_TYPE)) {
                            savepointType = CursorUtils.getIndexAsString(c, i);
                        } else if (columnName.equals(DataTableColumns.SAVEPOINT_CREATOR)) {
                            savepointCreator = CursorUtils.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.getColumnDefinitions()) {
                            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.US))
                                .format(new Date(TableConstants.milliSecondsFromNanos(savepointTimestamp)));

                        // For XML, we traverse the map to serialize it
                        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                        DocumentBuilder docBuilder = dbf.newDocumentBuilder();

                        Document d = docBuilder.newDocument();

                        d.setXmlStandalone(true);

                        Element e = d.createElement((xmlRootElementName == null) ? "data" : xmlRootElementName);
                        d.appendChild(e);
                        e.setAttribute("id", tableId);
                        DynamicPropertiesCallback cb = new DynamicPropertiesCallback(appName, tableId,
                                instanceId, activeUser, currentLocale, username, userEmail);

                        int idx = 0;
                        Element meta = d.createElementNS(XML_OPENROSA_NAMESPACE, "meta");
                        meta.setPrefix("jr");

                        Element v = d.createElementNS(XML_OPENROSA_NAMESPACE, "instanceID");
                        Text txtNode = d.createTextNode(submissionInstanceId);
                        v.appendChild(txtNode);
                        meta.appendChild(v);

                        if (xmlDeviceIdPropertyName != null) {
                            String deviceId = propertyManager.getSingularProperty(xmlDeviceIdPropertyName, cb);
                            if (deviceId != null) {
                                v = d.createElementNS(XML_OPENROSA_NAMESPACE, "deviceID");
                                txtNode = d.createTextNode(deviceId);
                                v.appendChild(txtNode);
                                meta.appendChild(v);
                            }
                        }
                        if (xmlUserIdPropertyName != null) {
                            String userId = propertyManager.getSingularProperty(xmlUserIdPropertyName, cb);
                            if (userId != null) {
                                v = d.createElementNS(XML_OPENROSA_NAMESPACE, "userID");
                                txtNode = d.createTextNode(userId);
                                v.appendChild(txtNode);
                                meta.appendChild(v);
                            }
                        }
                        v = d.createElementNS(XML_OPENROSA_NAMESPACE, "timeEnd");
                        txtNode = d.createTextNode(datestamp);
                        v.appendChild(txtNode);
                        meta.appendChild(v);

                        // these are extra metadata tags...
                        if (instanceName != null) {
                            v = d.createElement("instanceName");
                            txtNode = d.createTextNode(instanceName);
                            v.appendChild(txtNode);
                            meta.appendChild(v);
                        } else {
                            v = d.createElement("instanceName");
                            txtNode = d.createTextNode(savepointTimestamp);
                            v.appendChild(txtNode);
                            meta.appendChild(v);
                        }

                        // these are extra metadata tags...
                        // rowID
                        v = d.createElement("rowID");
                        txtNode = d.createTextNode(instanceId);
                        v.appendChild(txtNode);
                        meta.appendChild(v);

                        // rowETag
                        v = d.createElement("rowETag");
                        if (rowETag != null) {
                            txtNode = d.createTextNode(rowETag);
                            v.appendChild(txtNode);
                        }
                        meta.appendChild(v);

                        // filterType
                        v = d.createElement("filterType");
                        if (filterType != null) {
                            txtNode = d.createTextNode(filterType);
                            v.appendChild(txtNode);
                        }
                        meta.appendChild(v);

                        // filterValue
                        v = d.createElement("filterValue");
                        if (filterValue != null) {
                            txtNode = d.createTextNode(filterValue);
                            v.appendChild(txtNode);
                        }
                        meta.appendChild(v);

                        // formID
                        v = d.createElement("formID");
                        txtNode = d.createTextNode(formId);
                        v.appendChild(txtNode);
                        meta.appendChild(v);

                        // locale
                        v = d.createElement("locale");
                        txtNode = d.createTextNode(locale);
                        v.appendChild(txtNode);
                        meta.appendChild(v);

                        // savepointType
                        v = d.createElement("savepointType");
                        txtNode = d.createTextNode(savepointType);
                        v.appendChild(txtNode);
                        meta.appendChild(v);

                        // savepointCreator
                        v = d.createElement("savepointCreator");
                        if (savepointCreator != null) {
                            txtNode = d.createTextNode(savepointCreator);
                            v.appendChild(txtNode);
                        }
                        meta.appendChild(v);

                        // savepointTimestamp
                        v = d.createElement("savepointTimestamp");
                        txtNode = d.createTextNode(savepointTimestamp);
                        v.appendChild(txtNode);
                        meta.appendChild(v);

                        // and insert the meta block into the XML

                        e.appendChild(meta);

                        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, logger);
                        }

                        TransformerFactory factory = TransformerFactory.newInstance();
                        Transformer transformer = factory.newTransformer();
                        Properties outFormat = new Properties();
                        outFormat.setProperty(OutputKeys.INDENT, "no");
                        outFormat.setProperty(OutputKeys.METHOD, "xml");
                        outFormat.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                        outFormat.setProperty(OutputKeys.VERSION, "1.0");
                        outFormat.setProperty(OutputKeys.ENCODING, "UTF-8");
                        transformer.setOutputProperties(outFormat);

                        ByteArrayOutputStream out = new ByteArrayOutputStream();

                        DOMSource domSource = new DOMSource(d.getDocumentElement());
                        StreamResult result = new StreamResult(out);
                        transformer.transform(domSource, result);

                        out.flush();
                        out.close();

                        b.append(out.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, logger);
                        }

                    } else {
                        // Pre-processing -- collapse all mimeUri into filename
                        for (ColumnDefinition defn : orderedDefns.getColumnDefinitions()) {
                            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", orderedDefns.getDataModel());
                        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, logger);
                    }
                    exportFile(freturn.serializeUriFragmentList(getContext()), manifest, logger);
                    return ParcelFileDescriptor.open(manifest, ParcelFileDescriptor.MODE_READ_ONLY);

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

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

    } finally {
        if (db != null) {
            try {
                // release the reference...
                // this does not necessarily close the db handle
                // or terminate any pending transaction
                db.releaseReference();
            } finally {
                // this will release the final reference and close the database
                OdkConnectionFactorySingleton.getOdkConnectionFactoryInterface().removeConnection(appName,
                        dbHandleName);
            }
        }
    }
    return null;
}

From source file:org.awesomeapp.messenger.ui.AccountViewFragment.java

private void initFragment() {

    Intent i = getIntent();/* w w  w  . j av  a2s. c o m*/

    mApp = (ImApp) getActivity().getApplication();

    String action = i.getAction();

    if (i.hasExtra("isSignedIn"))
        isSignedIn = i.getBooleanExtra("isSignedIn", false);

    final ProviderDef provider;

    mSignInHelper = new SignInHelper(getActivity(), new SimpleAlertHandler(getActivity()));
    SignInHelper.SignInListener signInListener = new SignInHelper.SignInListener() {
        @Override
        public void connectedToService() {
        }

        @Override
        public void stateChanged(int state, long accountId) {
            if (state == ImConnection.LOGGED_IN) {
                //  mSignInHelper.goToAccount(accountId);
                // finish();
                isSignedIn = true;
            } else {
                isSignedIn = false;
            }

        }
    };

    mSignInHelper.setSignInListener(signInListener);

    ContentResolver cr = getActivity().getContentResolver();

    Uri uri = i.getData();
    // check if there is account information and direct accordingly
    if (Intent.ACTION_INSERT_OR_EDIT.equals(action)) {
        if ((uri == null) || !Imps.Account.CONTENT_ITEM_TYPE.equals(cr.getType(uri))) {
            action = Intent.ACTION_INSERT;
        } else {
            action = Intent.ACTION_EDIT;
        }
    }

    if (Intent.ACTION_INSERT.equals(action) && uri.getScheme().equals("ima")) {
        ImPluginHelper helper = ImPluginHelper.getInstance(getActivity());
        String authority = uri.getAuthority();
        String[] userpass_host = authority.split("@");
        String[] user_pass = userpass_host[0].split(":");
        mUserName = user_pass[0].toLowerCase(Locale.getDefault());
        String pass = user_pass[1];
        mDomain = userpass_host[1].toLowerCase(Locale.getDefault());
        mPort = 0;
        final boolean regWithTor = i.getBooleanExtra("useTor", false);

        Cursor cursor = openAccountByUsernameAndDomain(cr);
        boolean exists = cursor.moveToFirst();
        long accountId;
        if (exists) {
            accountId = cursor.getLong(0);
            mAccountUri = ContentUris.withAppendedId(Imps.Account.CONTENT_URI, accountId);
            pass = cursor.getString(ACCOUNT_PASSWORD_COLUMN);

            setAccountKeepSignedIn(true);
            mSignInHelper.activateAccount(mProviderId, accountId);
            mSignInHelper.signIn(pass, mProviderId, accountId, true);
            //  setResult(RESULT_OK);
            cursor.close();
            // finish();
            return;

        } else {
            mProviderId = helper.createAdditionalProvider(helper.getProviderNames().get(0)); //xmpp FIXME
            accountId = ImApp.insertOrUpdateAccount(cr, mProviderId, -1, mUserName, mUserName, pass);
            mAccountUri = ContentUris.withAppendedId(Imps.Account.CONTENT_URI, accountId);
            mSignInHelper.activateAccount(mProviderId, accountId);
            createNewAccount(mUserName, pass, accountId, regWithTor);
            cursor.close();
            return;
        }

    } else if (Intent.ACTION_INSERT.equals(action)) {

        mOriginalUserAccount = "";
        // TODO once we implement multiple IM protocols
        mProviderId = ContentUris.parseId(uri);
        provider = mApp.getProvider(mProviderId);

    } else if (Intent.ACTION_EDIT.equals(action)) {

        if ((uri == null) || !Imps.Account.CONTENT_ITEM_TYPE.equals(cr.getType(uri))) {
            LogCleaner.warn(ImApp.LOG_TAG, "<AccountActivity>Bad data");
            return;
        }

        isEdit = true;

        Cursor cursor = cr.query(uri, ACCOUNT_PROJECTION, null, null, null);

        if (cursor == null) {

            return;
        }

        if (!cursor.moveToFirst()) {
            cursor.close();

            return;
        }

        mAccountId = cursor.getLong(cursor.getColumnIndexOrThrow(BaseColumns._ID));

        mProviderId = cursor.getLong(ACCOUNT_PROVIDER_COLUMN);
        provider = mApp.getProvider(mProviderId);

        Cursor pCursor = cr.query(Imps.ProviderSettings.CONTENT_URI,
                new String[] { Imps.ProviderSettings.NAME, Imps.ProviderSettings.VALUE },
                Imps.ProviderSettings.PROVIDER + "=?", new String[] { Long.toString(mProviderId) }, null);

        Imps.ProviderSettings.QueryMap settings = new Imps.ProviderSettings.QueryMap(pCursor, cr, mProviderId,
                false /* don't keep updated */, null /* no handler */);

        try {
            mOriginalUserAccount = cursor.getString(ACCOUNT_USERNAME_COLUMN) + "@" + settings.getDomain();
            mEditUserAccount.setText(mOriginalUserAccount);
            mEditPass.setText(cursor.getString(ACCOUNT_PASSWORD_COLUMN));
            //mRememberPass.setChecked(!cursor.isNull(ACCOUNT_PASSWORD_COLUMN));
            //mUseTor.setChecked(settings.getUseTor());
            mBtnQrDisplay.setVisibility(View.VISIBLE);
        } finally {
            settings.close();
            cursor.close();
        }

    } else {
        LogCleaner.warn(ImApp.LOG_TAG, "<AccountActivity> unknown intent action " + action);
        return;
    }

    setupUIPost();

}