Example usage for android.net Uri toString

List of usage examples for android.net Uri toString

Introduction

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

Prototype

public abstract String toString();

Source Link

Document

Returns the encoded string representation of this URI.

Usage

From source file:com.owncloud.android.authentication.AuthenticatorActivity.java

/**
 * The redirection triggered by the OAuth authentication server as response
 * to the GET AUTHORIZATION request is caught here.
 * // w w  w  .j  a  v a  2  s  . c  om
 * To make this possible, this activity needs to be qualified with
 * android:launchMode = "singleTask" in the AndroidManifest.xml file.
 */
@Override
protected void onNewIntent(Intent intent) {
    Log_OC.d(TAG, "onNewIntent()");
    Uri data = intent.getData();
    if (data != null && data.toString().startsWith(getString(R.string.oauth2_redirect_uri))) {
        mNewCapturedUriFromOAuth2Redirection = data;
    }
}

From source file:com.fvd.nimbus.BrowseActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //overridePendingTransition( R.anim.slide_in_up, R.anim.slide_out_up );
    //overridePendingTransition(R.anim.carbon_slide_in,R.anim.carbon_slide_out);
    //overridePendingTransition(R.anim.activity_open_scale,R.anim.activity_close_translate);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    try {//from   w  w w .  ja va  2s. co m
        requestWindowFeature(Window.FEATURE_NO_TITLE);
    } catch (Exception e) {
        e.printStackTrace();
    }
    clipData = new DataExchange();
    isInitNow = true;
    setContentView(R.layout.screen_browser);
    serverHelper.getInstance().setCallback(this, this);
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    lastUrl = prefs.getString("LAST_URL", "");
    saveCSS = prefs.getString("clipStyle", "1").equals("1");
    ctx = this;

    //adapter = new TextAdapter(this);      

    /*Uri data = getIntent().getData();
    if(data!=null){
       lastUrl=data.toString();
    }*/
    Intent intent = getIntent();
    String action = intent.getAction();
    String type = intent.getType();
    if (Intent.ACTION_VIEW.equals(action) /*&& type != null*/) {
        Uri data = intent.getData();
        if (data != null) {
            lastUrl = data.toString();
            appSettings.appendLog("browse:onCreate  " + lastUrl);
        }
    } else if (Intent.ACTION_SEND.equals(action) /*&& type != null*/) {
        if ("text/plain".equals(type)) {
            String surl = intent.getStringExtra(Intent.EXTRA_TEXT);
            if (surl.contains(" ")) {
                String[] arr = surl.replace("\t", " ").split(" ");
                for (String s : arr) {
                    if (s.contains("://")) {
                        lastUrl = s.trim();
                        break;
                    }
                }
            } else if (surl.contains("://"))
                lastUrl = surl.trim();
            appSettings.appendLog("browse:onCreate  " + lastUrl);
        }
    }

    drawer = (DrawerLayout) findViewById(R.id.root);

    View v = findViewById(R.id.wv);
    wv = (fvdWebView) findViewById(R.id.wv);
    wv.setEventsHandler(this);
    //registerForContextMenu(wv); 
    urlField = (AutoCompleteTextView) findViewById(R.id.etAddess);
    urlField.setSelectAllOnFocus(true);
    urlField.setOnEditorActionListener(new EditText.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                /*InputMethodManager imm = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);*/
                onNavButtonClicked();
                return true;
            } else if (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
                onNavButtonClicked();
                return true;
            }
            return false;
        }
    });
    onViewCreated();

    handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case 0:
                findViewById(R.id.bZoomStack).setVisibility(View.VISIBLE);
                findViewById(R.id.bToggleMenu).setVisibility(View.GONE);

                break;

            default:
                break;
            }
        }
    };

    navButton = (ImageButton) findViewById(R.id.ibReloadWebPage);
    navButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            //Toast.makeText(getApplicationContext(), "You made a mess", Toast.LENGTH_LONG).show();
            onNavButtonClicked();
        }
    });

    findViewById(R.id.bSavePageFragment).setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            //toggleTools();
            floatMenu.collapse();
            if (!wv.getInjected())
                Toast.makeText(ctx, getString(R.string.wait_load), Toast.LENGTH_LONG).show();
            clipMode = 2;
            if (wv.getInjected()/* && !v.isSelected()*/) {
                wv.setCanClip(true);
                v.setSelected(true);
                Toast.makeText(ctx, ctx.getString(R.string.use_longtap), Toast.LENGTH_LONG).show();
            }

        }
    });

    (findViewById(R.id.bSaveFullPage)).setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

            floatMenu.collapse();
            if (wv.getInjected()) {
                wv.setCanClip(false);
                wv.saveArticle();
                clipMode = 1;
                progressDialog = ProgressDialog.show(v.getContext(), "Nimbus Clipper",
                        getString(R.string.please_wait), true, false);
            } else {
                Toast.makeText(ctx, getString(R.string.wait_load), Toast.LENGTH_LONG).show();
            }
        }
    });

    findViewById(R.id.bTakeScreenshot).setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            //toggleTools();
            floatMenu.collapse();
            findViewById(R.id.bSaveFullPage).setVisibility(View.GONE);
            findViewById(R.id.bSavePageFragment).setVisibility(View.GONE);
            findViewById(R.id.bTakeScreenshot).setVisibility(View.GONE);
            if (wv.getInjected()) {
                wv.setCanClip(false);
            }
            findViewById(R.id.bToggleMenu).setVisibility(View.GONE);
            /*screenCapture();
            findViewById(R.id.bToggleMenu).setVisibility(View.VISIBLE);*/

            findViewById(R.id.bTakeScreenshot).postDelayed(new Runnable() {
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    screenCapture();
                    findViewById(R.id.bToggleMenu).setVisibility(View.VISIBLE);
                    finish();
                }
            }, 10);

            //showDialog(DIALOG_CAPTURE);
        }
    });

    (findViewById(R.id.bDone)).setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            {
                try {

                    wv.setCanClip(false);
                    wv.endSelectionMode();
                    //findViewById(R.id.bSavePageFragment).setSelected(false);
                    clipMode = 2;
                    wv.endSelectionMode();
                    String selHtml = clipData.getContent();
                    if (selHtml.length() > 0) {
                        String ss = selHtml.substring(0, selHtml.indexOf(">") + 1).toLowerCase();
                        int j = ss.indexOf("<div");
                        if (j == 0) {
                            j = ss.indexOf("style");
                            if (j > 0) {
                                int k = ss.indexOf("\"", j + 11);
                                if (k > 0)
                                    selHtml = selHtml.replace(selHtml.substring(j, k + 1), "");
                            }
                            //selHtml="<DIV>"+selHtml.substring(ss.length());
                        }
                        clipData.setContent(selHtml);
                        clipData.setTitle(wv.getTitle());

                        /*if (true){
                                    
                            if(sessionId.length() == 0 || userPass.length()==0) showSettings();
                            else {
                               if(prefs.getBoolean("check_fast", false)){
                         sendNote(wv.getTitle(), clipData.getContent(), parent, tag);
                         clipData.setContent("");
                               }
                               else {
                               //serverHelper.getInstance().setCallback(this,this);
                               if(appSettings.sessionId.length()>0) {
                         serverHelper.getInstance().sendRequest("notes:getFolders", "","");
                         }
                               }
                            }
                            wv.endSelectionMode();
                         } */

                        Intent i = new Intent(getApplicationContext(), previewActivity.class);
                        i.putExtra("content", clipData);
                        startActivityForResult(i, 5);
                        //overridePendingTransition( R.anim.slide_in_up, R.anim.slide_out_up );
                        overridePendingTransition(R.anim.carbon_slide_in, R.anim.carbon_slide_out);
                    }
                    //clipData.setContent("");
                } catch (Exception e) {
                    BugReporter.Send("onEndSelection", e.getMessage());
                }
            }
            //showDialog(DIALOG_CAPTURE);
        }
    });

    findViewById(R.id.bZoomIn).setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            wv.ZoomInSelection();
        }
    });

    findViewById(R.id.bZoomOut).setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            wv.ZoomOutSelection();
        }
    });

    setNavButtonState(NavButtonState.NBS_GO);

    progressBar = (ProgressBar) findViewById(R.id.progressbar);

    //CookieSyncManager.createInstance(this);

    //webSettings.setLoadsImagesAutomatically(imgOn);
    userMail = prefs.getString("userMail", "");
    userPass = prefs.getString("userPass", "");
    sessionId = prefs.getString("sessionId", "");

    appSettings.sessionId = sessionId;
    appSettings.userMail = userMail;
    appSettings.userPass = userPass;

    if ("1".equals(prefs.getString("userAgent", "1"))) {
        wv.setUserAgent(null);
    } else
        wv.setUserAgent(deskAgent);

    final Activity activity = this;
    //lastUrl="file:///android_asset/android.html";
    if (lastUrl.length() > 0) {
        //wv.navigate(lastUrl);

        //if(!urlField.getText().toString().equals(wv.getUrl()))
        urlField.setText(lastUrl);
        openURL();
    }
    isInitNow = false;

    urlField.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            // TODO Auto-generated method stub
            /*String item = (String)parent.getItemAtPosition(position);
                    
            Toast.makeText(
                  getApplicationContext(),
                  "  "
                + item,
                  Toast.LENGTH_SHORT).show();*/
            openURL();

        }
    });

    urlField.addTextChangedListener(this);
    parent = prefs.getString("remFolderId", "default");

    /*ListView listView = (ListView) findViewById(R.id.left_drawer);
    listView.setAdapter(new DrawerMenuAdapter(this,getResources().getStringArray(R.array.lmenu_browser)));
    listView.setOnItemClickListener(this);*/
}

From source file:net.bytten.comicviewer.ComicViewerActivity.java

public void loadComicImage(Uri uri) {
    webview.clearView();/*from   w w w  .  j a v  a  2s  . c o m*/
    final ProgressDialog pd = ProgressDialog.show(this, getStringAppName(), "Loading comic image...", false,
            true, new OnCancelListener() {
                public void onCancel(DialogInterface dialog) {
                    webview.stopLoading();
                    webview.requestFocus();
                }
            });
    pd.setProgress(0);
    webview.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            pd.dismiss();
            webview.requestFocus();
        }
    });
    webview.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            pd.setProgress(newProgress * 100);
        }
    });
    if ("".equals(uri.toString())) {
        failed("Couldn't identify image in post");
        webview.loadUrl("about:blank");
    } else {
        webview.loadUrl(uri.toString());
    }
}

From source file:edu.mit.mobile.android.locast.sync.SyncEngine.java

/**
 * @param toSync/*from   w  w w  .j  a va  2  s  .  co m*/
 * @param account
 * @param extras
 * @param provider
 * @param syncResult
 * @return true if the item was sync'd successfully. Soft errors will cause this to return
 *         false.
 * @throws RemoteException
 * @throws SyncException
 * @throws JSONException
 * @throws IOException
 * @throws NetworkProtocolException
 * @throws NoPublicPath
 * @throws OperationApplicationException
 * @throws InterruptedException
 */
public boolean sync(Uri toSync, Account account, Bundle extras, ContentProviderClient provider,
        SyncResult syncResult) throws RemoteException, SyncException, JSONException, IOException,
        NetworkProtocolException, NoPublicPath, OperationApplicationException, InterruptedException {

    String pubPath = null;

    //
    // Handle http or https uris separately. These require the
    // destination uri.
    //
    if ("http".equals(toSync.getScheme()) || "https".equals(toSync.getScheme())) {
        pubPath = toSync.toString();

        if (!extras.containsKey(EXTRA_DESTINATION_URI)) {
            throw new IllegalArgumentException("missing EXTRA_DESTINATION_URI when syncing HTTP URIs");
        }
        toSync = Uri.parse(extras.getString(EXTRA_DESTINATION_URI));
    }

    final String type = provider.getType(toSync);
    final boolean isDir = type.startsWith(CONTENT_TYPE_PREFIX_DIR);

    final boolean manualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);

    // skip any items already sync'd
    if (!manualSync && mLastUpdated.isUpdatedRecently(toSync)) {
        if (DEBUG) {
            Log.d(TAG, "not syncing " + toSync + " as it's been updated recently");
        }
        syncResult.stats.numSkippedEntries++;
        return false;
    }

    // the sync map will convert the json data to ContentValues
    final SyncMap syncMap = MediaProvider.getSyncMap(provider, toSync);

    final Uri toSyncWithoutQuerystring = toSync.buildUpon().query(null).build();

    final HashMap<String, SyncStatus> syncStatuses = new HashMap<String, SyncEngine.SyncStatus>();
    final ArrayList<ContentProviderOperation> cpo = new ArrayList<ContentProviderOperation>();
    final LinkedList<String> cpoPubUris = new LinkedList<String>();

    //
    // first things first, upload any content that needs to be
    // uploaded.
    //

    try {
        uploadUnpublished(toSync, account, provider, syncMap, syncStatuses, syncResult);

        if (Thread.interrupted()) {
            throw new InterruptedException();
        }

        // this should ensure that all items have a pubPath when we
        // query it below.

        if (pubPath == null) {
            // we should avoid calling this too much as it
            // can be expensive
            pubPath = MediaProvider.getPublicPath(mContext, toSync);
        }
    } catch (final NoPublicPath e) {
        // TODO this is a special case and this is probably not the best place to handle this.
        // Ideally, this should be done in such a way as to reduce any extra DB queries -
        // perhaps by doing a join with the parent.
        if (syncMap.isFlagSet(SyncMap.FLAG_PARENT_MUST_SYNC_FIRST)) {
            if (DEBUG) {
                Log.d(TAG, "skipping " + toSync + " whose parent hasn't been sync'd first");
            }
            syncResult.stats.numSkippedEntries++;
            return false;
        }

        // if it's an item, we can handle it.
        if (isDir) {
            throw e;
        }
    }

    if (pubPath == null) {

        // this should have been updated already by the initial
        // upload, so something must be wrong
        throw new SyncException("never got a public path for " + toSync);
    }

    if (DEBUG) {
        Log.d(TAG, "sync(toSync=" + toSync + ", account=" + account + ", extras=" + extras + ", manualSync="
                + manualSync + ",...)");
        Log.d(TAG, "pubPath: " + pubPath);
    }

    final long request_time = System.currentTimeMillis();

    HttpResponse hr = mNetworkClient.get(pubPath);

    final long response_time = System.currentTimeMillis();

    // the time compensation below allows a time-based synchronization to function even if the
    // local clock is entirely wrong. The server's time is extracted using the Date header and
    // all are compared relative to the respective clock reference. Any data that's stored on
    // the mobile should be stored relative to the local clock and the server will respect the
    // same.
    long serverTime;

    try {
        serverTime = getServerTime(hr);
    } catch (final DateParseException e) {
        Log.w(TAG, "could not retrieve date from server. Using local time, which may be incorrect.", e);
        serverTime = System.currentTimeMillis();
    }

    // TODO check out
    // http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html
    final long response_delay = response_time - request_time;
    if (DEBUG) {
        Log.d(TAG, "request took " + response_delay + "ms");
    }
    final long localTime = request_time;

    // add this to the server time to get the local time
    final long localOffset = (localTime - serverTime);

    if (Math.abs(localOffset) > 30 * 60 * 1000) {
        Log.w(TAG, "local clock is off by " + localOffset + "ms");
    }

    if (Thread.interrupted()) {
        throw new InterruptedException();
    }

    final HttpEntity ent = hr.getEntity();

    String selection;
    String selectionInverse;
    String[] selectionArgs;

    if (isDir) {

        final JSONArray ja = new JSONArray(StreamUtils.inputStreamToString(ent.getContent()));
        ent.consumeContent();

        final int len = ja.length();
        selectionArgs = new String[len];

        // build the query to see which items are already in the
        // database
        final StringBuilder sb = new StringBuilder();

        sb.append("(");

        for (int i = 0; i < len; i++) {
            if (Thread.interrupted()) {
                throw new InterruptedException();
            }

            final SyncStatus syncStatus = loadItemFromJsonObject(ja.getJSONObject(i), syncMap, serverTime);

            syncStatuses.put(syncStatus.remote, syncStatus);

            selectionArgs[i] = syncStatus.remote;

            // add in a placeholder for the query
            sb.append('?');
            if (i != (len - 1)) {
                sb.append(',');
            }

        }
        sb.append(")");

        final String placeholders = sb.toString();
        selection = JsonSyncableItem._PUBLIC_URI + " IN " + placeholders;
        selectionInverse = JsonSyncableItem._PUBLIC_URI + " NOT IN " + placeholders;
    } else {

        final JSONObject jo = new JSONObject(StreamUtils.inputStreamToString(ent.getContent()));
        ent.consumeContent();
        final SyncStatus syncStatus = loadItemFromJsonObject(jo, syncMap, serverTime);

        syncStatuses.put(syncStatus.remote, syncStatus);

        selection = JsonSyncableItem._PUBLIC_URI + "=?";
        selectionInverse = JsonSyncableItem._PUBLIC_URI + "!=?";
        selectionArgs = new String[] { syncStatus.remote };
    }

    // first check without the querystring. This will ensure that we
    // properly mark things that we already have in the database.
    final Cursor check = provider.query(toSyncWithoutQuerystring, SYNC_PROJECTION, selection, selectionArgs,
            null);

    // these items are on both sides
    try {
        final int pubUriCol = check.getColumnIndex(JsonSyncableItem._PUBLIC_URI);
        final int idCol = check.getColumnIndex(JsonSyncableItem._ID);

        // All the items in this cursor should be found on both
        // the client and the server.
        for (check.moveToFirst(); !check.isAfterLast(); check.moveToNext()) {
            if (Thread.interrupted()) {
                throw new InterruptedException();
            }

            final long id = check.getLong(idCol);
            final Uri localUri = ContentUris.withAppendedId(toSync, id);

            final String pubUri = check.getString(pubUriCol);

            final SyncStatus itemStatus = syncStatuses.get(pubUri);

            itemStatus.state = SyncState.BOTH_UNKNOWN;

            itemStatus.local = localUri;

            // make the status searchable by both remote and
            // local uri
            syncStatuses.put(localUri.toString(), itemStatus);
        }
    } finally {
        check.close();
    }

    Cursor c = provider.query(toSync, SYNC_PROJECTION, selection, selectionArgs, null);

    // these items are on both sides
    try {
        final int pubUriCol = c.getColumnIndex(JsonSyncableItem._PUBLIC_URI);
        final int localModifiedCol = c.getColumnIndex(JsonSyncableItem._MODIFIED_DATE);
        final int serverModifiedCol = c.getColumnIndex(JsonSyncableItem._SERVER_MODIFIED_DATE);
        final int idCol = c.getColumnIndex(JsonSyncableItem._ID);

        // All the items in this cursor should be found on both
        // the client and the server.
        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
            if (Thread.interrupted()) {
                throw new InterruptedException();
            }

            final long id = c.getLong(idCol);
            final Uri localUri = ContentUris.withAppendedId(toSync, id);

            final String pubUri = c.getString(pubUriCol);

            final SyncStatus itemStatus = syncStatuses.get(pubUri);

            if (itemStatus.state == SyncState.ALREADY_UP_TO_DATE
                    || itemStatus.state == SyncState.NOW_UP_TO_DATE) {
                if (DEBUG) {
                    Log.d(TAG, localUri + "(" + pubUri + ")" + " is already up to date.");
                }
                continue;
            }

            itemStatus.local = localUri;

            // make the status searchable by both remote and local uri
            syncStatuses.put(localUri.toString(), itemStatus);

            // last modified as stored in the DB, in phone time
            final long itemLocalModified = c.getLong(localModifiedCol);

            // last modified as stored in the DB, in server time
            final long itemServerModified = c.getLong(serverModifiedCol);
            final long localAge = localTime - itemLocalModified;

            final long remoteAge = serverTime - itemStatus.remoteModifiedTime;

            final long ageDifference = Math.abs(localAge - remoteAge);

            // up to date, as far remote -> local goes
            if (itemServerModified == itemStatus.remoteModifiedTime) {
                itemStatus.state = SyncState.ALREADY_UP_TO_DATE;
                if (DEBUG) {
                    Log.d(TAG, pubUri + " is up to date.");
                }

                // need to download
            } else if (localAge > remoteAge) {
                if (DEBUG) {
                    final long serverModified = itemStatus.remoteModifiedTime;

                    Log.d(TAG,
                            pubUri + " : local is " + ageDifference + "ms older ("
                                    + android.text.format.DateUtils.formatDateTime(mContext, itemLocalModified,
                                            FORMAT_ARGS_DEBUG)
                                    + ") than remote (" + android.text.format.DateUtils.formatDateTime(mContext,
                                            serverModified, FORMAT_ARGS_DEBUG)
                                    + "); updating local copy...");
                }

                itemStatus.state = SyncState.REMOTE_DIRTY;

                final ContentProviderOperation.Builder b = ContentProviderOperation.newUpdate(localUri);

                // update this so it's in the local timescale
                correctServerOffset(itemStatus.remoteCVs, JsonSyncableItem._CREATED_DATE,
                        JsonSyncableItem._CREATED_DATE, localOffset);
                correctServerOffset(itemStatus.remoteCVs, JsonSyncableItem._SERVER_MODIFIED_DATE,
                        JsonSyncableItem._MODIFIED_DATE, localOffset);

                b.withValues(itemStatus.remoteCVs);
                b.withExpectedCount(1);

                cpo.add(b.build());
                cpoPubUris.add(pubUri);

                syncResult.stats.numUpdates++;

                // need to upload
            } else if (localAge < remoteAge) {
                if (DEBUG) {
                    final long serverModified = itemStatus.remoteModifiedTime;

                    Log.d(TAG,
                            pubUri + " : local is " + ageDifference + "ms newer ("
                                    + android.text.format.DateUtils.formatDateTime(mContext, itemLocalModified,
                                            FORMAT_ARGS_DEBUG)
                                    + ") than remote (" + android.text.format.DateUtils.formatDateTime(mContext,
                                            serverModified, FORMAT_ARGS_DEBUG)
                                    + "); publishing to server...");
                }
                itemStatus.state = SyncState.LOCAL_DIRTY;

                mNetworkClient.putJson(pubPath, JsonSyncableItem.toJSON(mContext, localUri, c, syncMap));
            }

            mLastUpdated.markUpdated(localUri);

            syncResult.stats.numEntries++;
        } // end for
    } finally {

        c.close();
    }

    /*
     * Apply updates in bulk
     */
    if (cpo.size() > 0) {
        if (DEBUG) {
            Log.d(TAG, "applying " + cpo.size() + " bulk updates...");
        }

        final ContentProviderResult[] r = provider.applyBatch(cpo);
        if (DEBUG) {
            Log.d(TAG, "Done applying updates. Running postSync handler...");
        }

        for (int i = 0; i < r.length; i++) {
            final ContentProviderResult res = r[i];
            final SyncStatus ss = syncStatuses.get(cpoPubUris.get(i));
            if (ss == null) {
                Log.e(TAG, "can't get sync status for " + res.uri);
                continue;
            }
            syncMap.onPostSyncItem(mContext, account, ss.local, ss.remoteJson,
                    res.count != null ? res.count == 1 : true);

            ss.state = SyncState.NOW_UP_TO_DATE;
        }

        if (DEBUG) {
            Log.d(TAG, "done running postSync handler.");
        }

        cpo.clear();
        cpoPubUris.clear();
    }

    if (Thread.interrupted()) {
        throw new InterruptedException();
    }

    /*
     * Look through the SyncState.state values and find ones that need to be stored.
     */

    for (final Map.Entry<String, SyncStatus> entry : syncStatuses.entrySet()) {
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }

        final String pubUri = entry.getKey();
        final SyncStatus status = entry.getValue();
        if (status.state == SyncState.REMOTE_ONLY) {
            if (DEBUG) {
                Log.d(TAG, pubUri + " is not yet stored locally, adding...");
            }

            // update this so it's in the local timescale
            correctServerOffset(status.remoteCVs, JsonSyncableItem._CREATED_DATE,
                    JsonSyncableItem._CREATED_DATE, localOffset);
            correctServerOffset(status.remoteCVs, JsonSyncableItem._SERVER_MODIFIED_DATE,
                    JsonSyncableItem._MODIFIED_DATE, localOffset);

            final ContentProviderOperation.Builder b = ContentProviderOperation.newInsert(toSync);
            b.withValues(status.remoteCVs);

            cpo.add(b.build());
            cpoPubUris.add(pubUri);
            syncResult.stats.numInserts++;

        }
    }

    /*
     * Execute the content provider operations in bulk.
     */
    if (cpo.size() > 0) {
        if (DEBUG) {
            Log.d(TAG, "bulk inserting " + cpo.size() + " items...");
        }
        final ContentProviderResult[] r = provider.applyBatch(cpo);
        if (DEBUG) {
            Log.d(TAG, "applyBatch completed. Processing results...");
        }

        int successful = 0;
        for (int i = 0; i < r.length; i++) {
            final ContentProviderResult res = r[i];
            if (res.uri == null) {
                syncResult.stats.numSkippedEntries++;
                Log.e(TAG, "result from content provider bulk operation returned null");
                continue;
            }
            final String pubUri = cpoPubUris.get(i);
            final SyncStatus ss = syncStatuses.get(pubUri);

            if (ss == null) {
                syncResult.stats.numSkippedEntries++;
                Log.e(TAG, "could not find sync status for " + cpoPubUris.get(i));
                continue;
            }

            ss.local = res.uri;
            if (DEBUG) {
                Log.d(TAG, "onPostSyncItem(" + res.uri + ", ...); pubUri: " + pubUri);
            }

            syncMap.onPostSyncItem(mContext, account, res.uri, ss.remoteJson,
                    res.count != null ? res.count == 1 : true);

            ss.state = SyncState.NOW_UP_TO_DATE;
            successful++;
        }
        if (DEBUG) {
            Log.d(TAG, successful + " batch inserts successfully applied.");
        }
    } else {
        if (DEBUG) {
            Log.d(TAG, "no updates to perform.");
        }
    }

    /**
     * Look through all the items that we didn't already find on the server side, but which
     * still have a public uri. They should be checked to make sure they're not deleted.
     */
    c = provider.query(toSync, SYNC_PROJECTION,
            ProviderUtils.addExtraWhere(selectionInverse, JsonSyncableItem._PUBLIC_URI + " NOT NULL"),
            selectionArgs, null);

    try {
        final int idCol = c.getColumnIndex(JsonSyncableItem._ID);
        final int pubUriCol = c.getColumnIndex(JsonSyncableItem._PUBLIC_URI);

        cpo.clear();

        for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
            final String pubUri = c.getString(pubUriCol);
            SyncStatus ss = syncStatuses.get(pubUri);

            final Uri item = isDir ? ContentUris.withAppendedId(toSyncWithoutQuerystring, c.getLong(idCol))
                    : toSync;

            if (ss == null) {
                ss = syncStatuses.get(item.toString());
            }

            if (DEBUG) {
                Log.d(TAG, item + " was not found in the main list of items on the server (" + pubPath
                        + "), but appears to be a child of " + toSync);

                if (ss != null) {
                    Log.d(TAG, "found sync status for " + item + ": " + ss);
                }
            }

            if (ss != null) {
                switch (ss.state) {
                case ALREADY_UP_TO_DATE:
                case NOW_UP_TO_DATE:
                    if (DEBUG) {
                        Log.d(TAG, item + " is already up to date. No need to see if it was deleted.");
                    }
                    continue;

                case BOTH_UNKNOWN:
                    if (DEBUG) {
                        Log.d(TAG,
                                item + " was found on both sides, but has an unknown sync status. Skipping...");
                    }
                    continue;

                default:

                    Log.w(TAG, "got an unexpected state for " + item + ": " + ss);
                }

            } else {
                ss = new SyncStatus(pubUri, SyncState.LOCAL_ONLY);
                ss.local = item;

                hr = mNetworkClient.head(pubUri);

                switch (hr.getStatusLine().getStatusCode()) {
                case 200:
                    if (DEBUG) {
                        Log.d(TAG, "HEAD " + pubUri + " returned 200");
                    }
                    ss.state = SyncState.BOTH_UNKNOWN;
                    break;

                case 404:
                    if (DEBUG) {
                        Log.d(TAG, "HEAD " + pubUri + " returned 404. Deleting locally...");
                    }
                    ss.state = SyncState.DELETED_REMOTELY;
                    final ContentProviderOperation deleteOp = ContentProviderOperation
                            .newDelete(ContentUris.withAppendedId(toSyncWithoutQuerystring, c.getLong(idCol)))
                            .build();
                    cpo.add(deleteOp);

                    break;

                default:
                    syncResult.stats.numIoExceptions++;
                    Log.w(TAG, "HEAD " + pubUri + " got unhandled result: " + hr.getStatusLine());
                }
            }
            syncStatuses.put(pubUri, ss);
        } // for cursor

        if (cpo.size() > 0) {
            final ContentProviderResult[] results = provider.applyBatch(cpo);

            for (final ContentProviderResult result : results) {
                if (result.count != 1) {
                    throw new SyncException("Error deleting item");
                }
            }
        }

    } finally {
        c.close();
    }

    syncStatuses.clear();

    mLastUpdated.markUpdated(toSync);

    return true;
}

From source file:org.thomnichols.android.gmarks.BookmarksQueryService.java

public void delete(String googleId) throws AuthException, NotFoundException, IOException {
    Uri requestURI = Uri.parse("https://www.google.com/bookmarks/api/thread").buildUpon()
            .appendQueryParameter("xt", getXtParam()).appendQueryParameter("op", "DeleteItems").build();
    //      final String deleteURL = "https://www.google.com/bookmarks/api/thread?"
    //         + "xt=" + URLEncoder.encode( getXtParam(), "UTF-8" )  
    //         + "&op=DeleteItems";
    //  td   {"deleteAllBookmarks":false,"deleteAllThreads":false,"urls":[],"ids":["____"]}

    JSONObject requestObj = new JSONObject();
    try {//from  ww w  . j av a 2 s  .c o  m
        requestObj.put("deleteAllBookmarks", false);
        requestObj.put("deleteAllThreads", false);
        requestObj.put("urls", new JSONArray());
        JSONArray elementIDs = new JSONArray();
        elementIDs.put(googleId);
        requestObj.put("ids", elementIDs);
    } catch (JSONException ex) {
        throw new IOException("JSON error while creating request");
    }

    String postString = "{\"deleteAllBookmarks\":false,\"deleteAllThreads\":false,\"urls\":[],\"ids\":[\""
            + googleId + "\"]}";

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    //      params.add( new BasicNameValuePair("td", requestObj.toString()) );
    params.add(new BasicNameValuePair("td", postString));

    //      Log.v(TAG,"DELETE: " + requestObj.toString());
    Log.v(TAG, "DELETE: " + requestURI);
    Log.v(TAG, "DELETE: " + postString);

    HttpPost post = new HttpPost(requestURI.toString());
    //      HttpPost post = new HttpPost( deleteURL );      
    post.setEntity(new UrlEncodedFormEntity(params));
    HttpResponse resp = http.execute(post, this.ctx);

    int respCode = resp.getStatusLine().getStatusCode();
    if (respCode == 401)
        throw new AuthException();
    if (respCode > 299)
        throw new IOException("Unexpected response code: " + respCode);

    try { // always assume a single item is created or updated.
        JSONObject respObj = parseJSON(resp);
        int deletedCount = respObj.getInt("numDeletedBookmarks");

        if (deletedCount < 1)
            throw new NotFoundException("Bookmark could not be found; " + googleId);
        if (deletedCount > 1)
            throw new IOException("Expected 1 deleted bookmark but got " + deletedCount);
    } catch (JSONException ex) {
        throw new IOException("Response parse error", ex);
    }
}

From source file:com.siahmsoft.soundroid.sdk7.provider.tracks.TracksStore.java

public void shareTrack(String idTrack, ArrayList<String> mails, ResultListener<Track> listener) {
    final Uri uri = buildShareTrackQuery(idTrack);

    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
            Charset.forName(HTTP.UTF_8));

    for (String mail : mails) {
        if (mail != null && !"".equals(mail)) {
            ContentBody sharedTo;//from w  w  w  .j a v a 2  s . co  m
            try {
                sharedTo = new StringBody(mail.trim());
                entity.addPart("track[shared_to][emails][][address]", sharedTo);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }

    final HttpPut put = new HttpPut(uri.toString());
    signRequest(put);
    put.setEntity(entity);

    try {
        executeRequestNotSigned(put, new ResponseHandler() {
            public void handleResponse(InputStream in) throws IOException {
                parseSingleResponse(in, new ResponseParserSingle() {
                    @Override
                    public void parseResponse(JSONObject parser) throws JSONException {
                        int i = 0;
                        i++;
                    }
                });
            }
        });

    } catch (IOException e) {
        android.util.Log.e(LOG_TAG, "Could not perform search with query: ", e);
        listener.onError(e);
    }

}

From source file:com.androidclub.source.XmlDocumentProvider.java

/**
 * Creates an XmlPullParser for the provided local resource. Can be overloaded to provide your
 * own parser.//from   w w w .jav a2 s . c  o m
 * @param resourceUri A fully qualified resource name referencing a local XML resource.
 * @return An XmlPullParser on this resource.
 */
protected XmlPullParser getResourceXmlPullParser(Uri resourceUri) {
    //OpenResourceIdResult resourceId;
    try {
        String authority = resourceUri.getAuthority();
        Resources r;
        if (TextUtils.isEmpty(authority)) {
            throw new FileNotFoundException("No authority: " + resourceUri);
        } else {
            try {
                r = getContext().getPackageManager().getResourcesForApplication(authority);
            } catch (NameNotFoundException ex) {
                throw new FileNotFoundException("No package found for authority: " + resourceUri);
            }
        }
        List<String> path = resourceUri.getPathSegments();
        if (path == null) {
            throw new FileNotFoundException("No path: " + resourceUri);
        }
        int len = path.size();
        int id;
        if (len == 1) {
            try {
                id = Integer.parseInt(path.get(0));
            } catch (NumberFormatException e) {
                throw new FileNotFoundException("Single path segment is not a resource ID: " + resourceUri);
            }
        } else if (len == 2) {
            id = r.getIdentifier(path.get(1), path.get(0), authority);
        } else {
            throw new FileNotFoundException("More than two path segments: " + resourceUri);
        }
        if (id == 0) {
            throw new FileNotFoundException("No resource found for: " + resourceUri);
        }

        return r.getXml(id);
    } catch (FileNotFoundException e) {
        Log.w(LOG_TAG, "XML resource not found: " + resourceUri.toString(), e);
        return null;
    }
}

From source file:com.apptentive.android.sdk.model.FileMessage.java

/**
 * This method stores an image, and compresses it in the process so it doesn't fill up the disk. Therefore, do not use
 * it to store an exact copy of the file in question.
 *//*from  ww w.  j av a 2 s  . co  m*/
public boolean internalCreateStoredImage(Context context, String uriString) {
    Uri uri = Uri.parse(uriString);

    ContentResolver resolver = context.getContentResolver();
    String mimeType = resolver.getType(uri);
    MimeTypeMap mime = MimeTypeMap.getSingleton();
    String extension = mime.getExtensionFromMimeType(mimeType);
    setFileName(uri.getLastPathSegment() + "." + extension);
    setMimeType(mimeType);

    // Create a file to save locally.
    String localFileName = getStoredFileId();
    File localFile = new File(localFileName);

    // Copy the file contents over.
    InputStream is = null;
    CountingOutputStream cos = null;
    try {
        is = new BufferedInputStream(context.getContentResolver().openInputStream(uri));
        cos = new CountingOutputStream(
                new BufferedOutputStream(context.openFileOutput(localFile.getPath(), Context.MODE_PRIVATE)));
        System.gc();
        Bitmap smaller = ImageUtil.createScaledBitmapFromStream(is, MAX_STORED_IMAGE_EDGE,
                MAX_STORED_IMAGE_EDGE, null);
        // TODO: Is JPEG what we want here?
        smaller.compress(Bitmap.CompressFormat.JPEG, 95, cos);
        cos.flush();
        Log.d("Bitmap saved, size = " + (cos.getBytesWritten() / 1024) + "k");
        smaller.recycle();
        System.gc();
    } catch (FileNotFoundException e) {
        Log.e("File not found while storing image.", e);
        return false;
    } catch (Exception e) {
        Log.a("Error storing image.", e);
        return false;
    } finally {
        Util.ensureClosed(is);
        Util.ensureClosed(cos);
    }

    // Create a StoredFile database entry for this locally saved file.
    StoredFile storedFile = new StoredFile();
    storedFile.setId(getStoredFileId());
    storedFile.setOriginalUri(uri.toString());
    storedFile.setLocalFilePath(localFile.getPath());
    storedFile.setMimeType("image/jpeg");
    FileStore db = ApptentiveDatabase.getInstance(context);
    return db.putStoredFile(storedFile);
}

From source file:com.stikyhive.stikyhive.ChattingActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Log.i(TAG, " ON ACTivyiy result");
    super.onActivityResult(requestCode, resultCode, data);
    Log.i("Result code ", " ^^ " + requestCode);
    if (requestCode == FILE_SELECT_CODE && resultCode == RESULT_OK) {
        Log.i(TAG, " ON ACTivyiy result ^^ 2");
        // Get the Uri of the selected file
        Uri uri = data.getData();
        Log.d("TAG", "File Uri: " + uri.toString());
        // Get the path
        String path;/*w  w  w  .j a  v  a 2  s . c o m*/
        try {
            calcualteTodayDate();
            path = getPath(this, uri);
            documentFile = new File(path);

            String extension = "";
            int index = documentFile.getName().lastIndexOf(".");
            if (index != -1) {
                extension = documentFile.getName().substring(index + 1);
            }
            Bitmap bmImg = BitmapFactory.decodeFile(path);
            //   Bitmap resBm = getResizedBitmap(bmImg, 500);
            adapter.add(new StikyChat("", "<img", false, timeSend, "file" + path, 0, 0, "", "", "", null,
                    documentFile.getPath()));
            adapter.notifyDataSetChanged();
            lv.setSelection(adapter.getCount() - 1);
            Log.i("Document File ", " %%%% " + documentFile.getAbsolutePath());
            upLoadServerUri = getApplicationContext().getResources().getString(R.string.url)
                    + "/androidstikyhive/filetransfer.php?fromStikyBee=" + pref.getString("stkid", "")
                    + "&toStikyBee=" + recipientStkid + "&message=photo" + "&extension=" + extension
                    + "&type=file" + "&dateTime=" + URLEncoder.encode(timeSendServer) + "&url="
                    + URLEncoder.encode(getResources().getString(R.string.url));
            new Thread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    int serverResponseCode = uploadFile(documentFile);
                    if (serverResponseCode == 200) {
                        Log.i("Success", " is done! ");
                        flagChatting = false;
                        flagTransfer = true;
                        messageServer = "<img";
                        msg = "File transfer.";
                        recipientStkidGCM = recipientStkid;
                        new regTask().execute("GCM");
                        new regTask2().execute("Last Message!");
                    }
                }
            }).start();
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else if (resultCode == Activity.RESULT_OK && requestCode == GALLERY_ACTIVITY_CODE) {
        Log.i(TAG, " Gallery is clicked..");
        calcualteTodayDate();
        imagePath = data.getStringExtra("picturePath");
        SDFile1 = new File(imagePath);

        String extension = "";
        int index = SDFile1.getName().lastIndexOf(".");
        if (index != -1) {
            extension = SDFile1.getName().substring(index + 1);
        }
        Bitmap bmImg = BitmapFactory.decodeFile(imagePath);
        Bitmap resBm = getResizedBitmap(bmImg, 500);
        adapter.add(new StikyChat("", "<img", false, timeSend, "bitmap" + imagePath, 0, 0, "", "", "", resBm,
                SDFile1.getPath()));
        adapter.notifyDataSetChanged();
        lv.setSelection(adapter.getCount() - 1);
        Log.i("SDFile ", " $$$ " + SDFile1.getAbsolutePath());
        upLoadServerUri = getApplicationContext().getResources().getString(R.string.url)
                + "/androidstikyhive/filetransfer.php?fromStikyBee=" + pref.getString("stkid", "")
                + "&toStikyBee=" + recipientStkid + "&message=photo" + "&extension=" + extension + "&type=image"
                + "&dateTime=" + URLEncoder.encode(timeSendServer) + "&url="
                + URLEncoder.encode(getResources().getString(R.string.url));
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                int serverResponseCode = uploadFile(SDFile1);
                if (serverResponseCode == 200) {
                    Log.i("Success", " is done! ");
                    flagChatting = false;
                    flagTransfer = true;
                    messageServer = "<img";
                    msg = "Image Transfer";
                    recipientStkidGCM = recipientStkid;
                    new regTask().execute("GCM");
                    new regTask2().execute("Last Message!");
                }
            }
        }).start();
        //performCrop(picturePath);
    } else if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
        convertImageUriToFile(imageUri, this);
        SDFile1 = new File(imagePath);

        String extension = "";
        int index = SDFile1.getName().lastIndexOf(".");
        if (index != -1) {
            extension = SDFile1.getName().substring(index + 1);
        }
        Bitmap bmImg = BitmapFactory.decodeFile(imagePath);
        Bitmap resBm = getResizedBitmap(bmImg, 500);
        adapter.add(new StikyChat("", "<img", false, timeSend, "bitmap" + imagePath, 0, 0, "", "", "", resBm,
                SDFile1.getPath()));
        adapter.notifyDataSetChanged();
        lv.setSelection(adapter.getCount() - 1);
        Log.i("SDFile ", " $$$ " + SDFile1.getAbsolutePath());
        upLoadServerUri = getApplicationContext().getResources().getString(R.string.url)
                + "/androidstikyhive/filetransfer.php?fromStikyBee=" + pref.getString("stkid", "")
                + "&toStikyBee=" + recipientStkid + "&message=photo" + "&extension=" + extension + "&type=image"
                + "&dateTime=" + URLEncoder.encode(timeSendServer) + "&url="
                + URLEncoder.encode(getResources().getString(R.string.url));
        new Thread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                int serverResponseCode = uploadFile(SDFile1);
                if (serverResponseCode == 200) {
                    Log.i("Success", " is done! ");
                    flagChatting = false;
                    flagTransfer = true;
                    messageServer = "<img";
                    msg = "Image Transfer";
                    recipientStkidGCM = recipientStkid;
                    new regTask().execute("GCM");
                    new regTask2().execute("Last Message!");
                }
            }
        }).start();
    }
}

From source file:com.vuze.android.remote.SessionInfo.java

private void openTorrent_perms(Activity activity, Uri uri) {
    try {//from www  .j  a v  a 2 s .  c om
        InputStream stream = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            String realPath = PaulBurkeFileUtils.getPath(activity, uri);
            if (realPath != null) {
                String meh = realPath.startsWith("/") ? "file://" + realPath : realPath;
                stream = activity.getContentResolver().openInputStream(Uri.parse(meh));
            }
        }
        if (stream == null) {
            ContentResolver contentResolver = activity.getContentResolver();
            stream = contentResolver.openInputStream(uri);
        }
        openTorrent(activity, uri.toString(), stream);
    } catch (SecurityException e) {
        if (AndroidUtils.DEBUG) {
            e.printStackTrace();
        }
        VuzeEasyTracker.getInstance(activity).logError(e);
        String s = "Security Exception trying to access <b>" + uri + "</b>";
        Toast.makeText(activity, Html.fromHtml(s), Toast.LENGTH_LONG).show();
    } catch (FileNotFoundException e) {
        if (AndroidUtils.DEBUG) {
            e.printStackTrace();
        }
        VuzeEasyTracker.getInstance(activity).logError(e);
        String s = "<b>" + uri + "</b> not found";
        if (e.getCause() != null) {
            s += ". " + e.getCause().getMessage();
        }
        Toast.makeText(activity, Html.fromHtml(s), Toast.LENGTH_LONG).show();
    }
}