Example usage for android.net Uri buildUpon

List of usage examples for android.net Uri buildUpon

Introduction

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

Prototype

public abstract Builder buildUpon();

Source Link

Document

Constructs a new builder, copying the attributes from this Uri.

Usage

From source file:com.box.androidlib.BoxSynchronous.java

/**
 * Executes an Http request and triggers response parsing by the specified parser.
 * //  w  ww.  j av a  2s .c o  m
 * @param parser
 *            A BoxResponseParser configured to consume the response and capture data that is of interest
 * @param uri
 *            The Uri of the request
 * @throws IOException
 *             Can be thrown if there is no connection, or if some other connection problem exists.
 */
protected static void saxRequest(final DefaultResponseParser parser, final Uri uri) throws IOException {
    Uri theUri = uri;
    List<BasicNameValuePair> customQueryParams = BoxConfig.getInstance().getCustomQueryParameters();
    if (customQueryParams != null && customQueryParams.size() > 0) {
        Uri.Builder builder = theUri.buildUpon();
        for (BasicNameValuePair param : customQueryParams) {
            builder.appendQueryParameter(param.getName(), param.getValue());
        }
        theUri = builder.build();
    }

    try {
        final XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
        xmlReader.setContentHandler(parser);
        HttpURLConnection conn = (HttpURLConnection) (new URL(theUri.toString())).openConnection();
        conn.setRequestProperty("User-Agent", BoxConfig.getInstance().getUserAgent());
        conn.setRequestProperty("Accept-Language", BoxConfig.getInstance().getAcceptLanguage());
        conn.setConnectTimeout(BoxConfig.getInstance().getConnectionTimeOut());
        if (mLoggingEnabled) {
            DevUtils.logcat("URL: " + theUri.toString());
            //                Iterator<String> keys = conn.getRequestProperties().keySet().iterator();
            //                while (keys.hasNext()) {
            //                    String key = keys.next();
            //                    DevUtils.logcat("Request Header: " + key + " => " + conn.getRequestProperties().get(key));
            //                }
        }

        int responseCode = -1;
        try {
            conn.connect();
            responseCode = conn.getResponseCode();
            if (mLoggingEnabled)
                DevUtils.logcat("Response Code: " + responseCode);
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = conn.getInputStream();
                xmlReader.parse(new InputSource(inputStream));
                inputStream.close();
            } else if (responseCode == -1) {
                parser.setStatus(ResponseListener.STATUS_UNKNOWN_HTTP_RESPONSE_CODE);
            }
        } catch (IOException e) {
            try {
                responseCode = conn.getResponseCode();
            } catch (NullPointerException ee) {
                // Honeycomb devices seem to throw a null pointer exception sometimes which traces to HttpURLConnectionImpl.
            }
            // Server returned a 503 Service Unavailable. Usually means a temporary unavailability.
            if (responseCode == HttpURLConnection.HTTP_UNAVAILABLE) {
                parser.setStatus(ResponseListener.STATUS_SERVICE_UNAVAILABLE);
            } else {
                throw e;
            }
        } finally {
            conn.disconnect();
        }
    } catch (final ParserConfigurationException e) {
        e.printStackTrace();
    } catch (final SAXException e) {
        e.printStackTrace();
    } catch (final FactoryConfigurationError e) {
        e.printStackTrace();
    }
}

From source file:org.andstatus.app.net.social.ConnectionTwitter.java

@Override
public List<MbTimelineItem> search(String searchQuery, int limit) throws ConnectionException {
    ApiRoutineEnum apiRoutine = ApiRoutineEnum.SEARCH_MESSAGES;
    String url = this.getApiPath(apiRoutine);
    Uri sUri = Uri.parse(url);
    Uri.Builder builder = sUri.buildUpon();
    if (fixedDownloadLimitForApiRoutine(limit, apiRoutine) > 0) {
        builder.appendQueryParameter("count",
                String.valueOf(fixedDownloadLimitForApiRoutine(limit, apiRoutine)));
    }/* ww  w  .j ava2 s. co m*/
    if (!TextUtils.isEmpty(searchQuery)) {
        builder.appendQueryParameter("q", searchQuery);
    }
    JSONArray jArr = http.getRequestAsArray(builder.build().toString());
    return jArrToTimeline(jArr, apiRoutine, url);
}

From source file:org.andstatus.app.net.social.ConnectionTwitter.java

@Override
public List<MbTimelineItem> getTimeline(ApiRoutineEnum apiRoutine, TimelinePosition sinceId, int limit,
        String userId) throws ConnectionException {
    String url = this.getApiPath(apiRoutine);
    Uri sUri = Uri.parse(url);
    Uri.Builder builder = sUri.buildUpon();
    if (!sinceId.isEmpty()) {
        builder.appendQueryParameter("since_id", sinceId.getPosition());
    }/*from  www.  ja v a2  s.  com*/
    if (fixedDownloadLimitForApiRoutine(limit, apiRoutine) > 0) {
        builder.appendQueryParameter("count",
                String.valueOf(fixedDownloadLimitForApiRoutine(limit, apiRoutine)));
    }
    if (!TextUtils.isEmpty(userId)) {
        builder.appendQueryParameter("user_id", userId);
    }
    JSONArray jArr = http.getRequestAsArray(builder.build().toString());
    return jArrToTimeline(jArr, apiRoutine, url);
}

From source file:org.andstatus.app.net.social.ConnectionTwitter.java

/**
 * @see <a//  www  .j a v a 2 s.  c o m
 *      href="https://dev.twitter.com/docs/api/1.1/get/users/show">GET users/show</a>
 */
@Override
public MbUser getUser(String userId) throws ConnectionException {
    Uri sUri = Uri.parse(getApiPath(ApiRoutineEnum.GET_USER));
    Uri.Builder builder = sUri.buildUpon();
    builder.appendQueryParameter("user_id", userId);
    JSONObject jso = http.getRequest(builder.build().toString());
    return userFromJson(jso);
}

From source file:org.andstatus.app.net.social.ConnectionTwitter.java

/**
 * Returns a single status, specified by the id parameter below.
 * The status's author will be returned inline.
 * @see <a/*from w  w  w. j a  va 2  s  . c  om*/
 *      href="https://dev.twitter.com/docs/api/1/get/statuses/show/%3Aid">Twitter
 *      REST API Method: statuses/destroy</a>
 * 
 * @throws ConnectionException
 */
@Override
public MbMessage getMessage1(String messageId) throws ConnectionException {
    Uri sUri = Uri.parse(getApiPath(ApiRoutineEnum.GET_MESSAGE));
    Uri.Builder builder = sUri.buildUpon();
    builder.appendQueryParameter("id", messageId);
    JSONObject message = http.getRequest(builder.build().toString());
    return messageFromJson(message);
}

From source file:org.andstatus.app.net.social.ConnectionTwitter.java

/**
 * Returns an array of numeric IDs for every user the specified user is following.
 * Current implementation is restricted to 5000 IDs (no paged cursors are used...)
 * @see <a/*w  ww.ja  va  2 s  .  c om*/
 *      href="https://dev.twitter.com/docs/api/1.1/get/friends/ids">GET friends/ids</a>
 * @throws ConnectionException
 */
@Override
public List<String> getIdsOfUsersFollowedBy(String userId) throws ConnectionException {
    String method = "getIdsOfUsersFollowedBy";
    Uri sUri = Uri.parse(getApiPath(ApiRoutineEnum.GET_FRIENDS_IDS));
    Uri.Builder builder = sUri.buildUpon();
    builder.appendQueryParameter("user_id", userId);
    List<String> list = new ArrayList<String>();
    JSONArray jArr = getRequestArrayInObject(builder.build().toString(), "ids");
    try {
        for (int index = 0; jArr != null && index < jArr.length(); index++) {
            list.add(jArr.getString(index));
        }
    } catch (JSONException e) {
        throw ConnectionException.loggedJsonException(this, method, e, jArr);
    }
    return list;
}

From source file:info.guardianproject.otr.app.im.app.WelcomeActivity.java

@SuppressWarnings("deprecation")
private boolean cursorUnlocked(String pKey, boolean allowCreate) {
    try {/*w w  w.java  2  s  . c  o m*/
        Uri uri = Imps.Provider.CONTENT_URI_WITH_ACCOUNT;

        Builder builder = uri.buildUpon();
        if (pKey != null)
            builder.appendQueryParameter(ImApp.CACHEWORD_PASSWORD_KEY, pKey);
        if (!allowCreate)
            builder = builder.appendQueryParameter(ImApp.NO_CREATE_KEY, "1");
        uri = builder.build();

        mProviderCursor = managedQuery(uri, PROVIDER_PROJECTION, Imps.Provider.CATEGORY + "=?" /* selection */,
                new String[] { ImApp.IMPS_CATEGORY } /* selection args */, Imps.Provider.DEFAULT_SORT_ORDER);

        if (mProviderCursor != null) {
            ImPluginHelper.getInstance(this).loadAvailablePlugins();

            mProviderCursor.moveToFirst();

            return true;
        } else {
            return false;
        }

    } catch (Exception e) {
        // Only complain if we thought this password should succeed
        if (allowCreate) {
            Log.e(ImApp.LOG_TAG, e.getMessage(), e);

            Toast.makeText(this, getString(R.string.error_welcome_database), Toast.LENGTH_LONG).show();
            finish();
        }

        // needs to be unlocked
        return false;
    }
}

From source file:com.example.android.todolist.AddTaskActivity.java

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_task);
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

    toolbar = (Toolbar) findViewById(R.id.archive_toolbar);
    add_btn = (FloatingActionButton) findViewById(R.id.addButton);
    delete_btn = (FloatingActionButton) findViewById(R.id.fab_delete);
    picked_color = (FloatingActionButton) findViewById(R.id.pick_color);

    formated_time = (TextView) findViewById(R.id.pickedTime);
    edt_title = (EditText) findViewById(R.id.editTextTaskDescription);
    edt_description = (EditText) findViewById(R.id.TaskDescription);
    choosenTime = (TextView) findViewById(R.id.pickedTime);

    contentValues = new ContentValues();

    delete_btn.setVisibility(View.INVISIBLE);

    Intent intent = getIntent();//from   ww  w .j a  v a2  s .c o  m
    mCurrentUri = intent.getData();
    isFromArchive = intent.getBooleanExtra("FROM_ARCHIVE", false);

    //   /tasks/1
    //  /tasks
    if (mCurrentUri == null) { // add a new task
        setTitle("add task");
        //  Toast.makeText(AddTaskActivity.this, "" + mCurrentUri, Toast.LENGTH_LONG).show();
        add_btn.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_send));

    } else if (isFromArchive) { // add task from archive
        add_btn.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_send));
        getSupportLoaderManager().initLoader(1, null, this); // archive

    } else {
        setTitle("update task"); // update task
        add_btn.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_done_black_24dp));
        delete_btn.setVisibility(View.VISIBLE);

        int row = Integer.valueOf(mCurrentUri.getLastPathSegment());
        String match = TaskContract.TaskEntry.CONTENT_URI.getPath() + "/" + row;

        if (mCurrentUri.getPath().equals(match)) {
            isTaskUri = true;
            getSupportLoaderManager().initLoader(0, null, this);

        } /* else {
          getSupportLoaderManager().initLoader(1, null, this);
                  
          }*/

    }

    picked_color.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            new SpectrumDialog.Builder(AddTaskActivity.this).setColors(R.array.color_array)
                    //    .setSelectedColorRes(R.color.md_blue_500)
                    .setDismissOnColorSelected(false)
                    //   .setOutlineWidth(2)

                    .setOnColorSelectedListener(new SpectrumDialog.OnColorSelectedListener() {
                        @Override
                        public void onColorSelected(boolean positiveResult, @ColorInt int color) {
                            if (positiveResult) {
                                isColorPicked = true;
                                color_posiotion = color;
                                //  Toast.makeText(getApplicationContext(), "" + color, Toast.LENGTH_LONG).show();

                                //  Toast.makeText(AddTaskActivity.this, "Color selected: #" + Integer.toHexString(color).toUpperCase(), Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(AddTaskActivity.this, "No color selected", Toast.LENGTH_SHORT)
                                        .show();
                            }
                        }
                    }).build().show(getSupportFragmentManager(), "hi");
        }
    });

    fabTime = (FloatingActionButton) findViewById(R.id.time_picked);
    fabTime.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Calendar now = Calendar.getInstance();
            DatePickerDialog dpd = DatePickerDialog.newInstance(AddTaskActivity.this, now.get(Calendar.YEAR),
                    now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH));
            dpd.show(getFragmentManager(), "Datepickerdialog");
            dpd.setVersion(DatePickerDialog.Version.VERSION_1);
            dpd.setThemeDark(false);
        }
    });

    add_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (mCurrentUri == null || isFromArchive) {
                onClickAddTask();

            } else {
                updateTask();

            }
        }
    });

    delete_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            // notify app widget to be updated
            sendBroadcast(new Intent("ACTION_DATA_UPDATED"));

            String stringId = Integer.toString(id);
            Uri uri = TaskContract.TaskEntry.CONTENT_URI;
            uri = uri.buildUpon().appendPath(stringId).build();
            getContentResolver().delete(uri, null, null);

            finish();
        }
    });

}

From source file:org.andstatus.app.net.social.ConnectionPumpio.java

@Override
public List<MbUser> getUsersFollowedBy(String userId) throws ConnectionException {
    int limit = 200;
    ApiRoutineEnum apiRoutine = ApiRoutineEnum.GET_FRIENDS;
    ConnectionAndUrl conu = getConnectionAndUrl(apiRoutine, userId);
    Uri sUri = Uri.parse(conu.url);
    Uri.Builder builder = sUri.buildUpon();
    if (fixedDownloadLimitForApiRoutine(limit, apiRoutine) > 0) {
        builder.appendQueryParameter("count",
                String.valueOf(fixedDownloadLimitForApiRoutine(limit, apiRoutine)));
    }// w w w  .  j  a va 2 s.c  om
    String url = builder.build().toString();
    JSONArray jArr = conu.httpConnection.getRequestAsArray(url);
    List<MbUser> followedUsers = new ArrayList<MbUser>();
    if (jArr != null) {
        for (int index = 0; index < jArr.length(); index++) {
            try {
                JSONObject jso = jArr.getJSONObject(index);
                MbUser item = userFromJson(jso);
                followedUsers.add(item);
            } catch (JSONException e) {
                throw ConnectionException.loggedJsonException(this, "Parsing list of users", e, null);
            }
        }
    }
    MyLog.d(TAG, "getUsersFollowedBy '" + url + "' " + followedUsers.size() + " users");
    return followedUsers;
}

From source file:org.andstatus.app.net.social.ConnectionPumpio.java

@Override
public List<MbTimelineItem> getTimeline(ApiRoutineEnum apiRoutine, TimelinePosition sinceId, int limit,
        String userId) throws ConnectionException {
    ConnectionAndUrl conu = getConnectionAndUrl(apiRoutine, userId);
    Uri sUri = Uri.parse(conu.url);
    Uri.Builder builder = sUri.buildUpon();
    if (!sinceId.isEmpty()) {
        // The "since" should point to the "Activity" on the timeline, not to the message
        // Otherwise we will always get "not found"
        builder.appendQueryParameter("since", sinceId.getPosition());
    }//from w w w  .j  a  va2  s  .c o m
    if (fixedDownloadLimitForApiRoutine(limit, apiRoutine) > 0) {
        builder.appendQueryParameter("count",
                String.valueOf(fixedDownloadLimitForApiRoutine(limit, apiRoutine)));
    }
    String url = builder.build().toString();
    JSONArray jArr = conu.httpConnection.getRequestAsArray(url);
    List<MbTimelineItem> timeline = new ArrayList<MbTimelineItem>();
    if (jArr != null) {
        // Read the activities in chronological order
        for (int index = jArr.length() - 1; index >= 0; index--) {
            try {
                JSONObject jso = jArr.getJSONObject(index);
                MbTimelineItem item = timelineItemFromJson(jso);
                timeline.add(item);
            } catch (JSONException e) {
                throw ConnectionException.loggedJsonException(this, "Parsing timeline", e, null);
            }
        }
    }
    MyLog.d(TAG, "getTimeline '" + url + "' " + timeline.size() + " messages");
    return timeline;
}