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:net.hiroq.rxwsc.RxWebSocketClient.java

/**
 * Connect to WebSocketServer with additional Header.
 * When unsubscribe is called, the observable will disconnect automatically.
 * <p>/*from  w  w w .  jav  a2  s .  c  om*/
 * Caution: This method run on same thread of caller. So if you want to run on NOT UI THREAD,
 * you have to use subscribeOn to specify thread model.
 *
 * @param uri
 * @param extraHeaders
 * @return
 */
public Observable<Event> connect(Uri uri, List<Pair<String, String>> extraHeaders) {
    this.disconnect(false);

    this.mUri = uri;
    this.mExtraHeaders = extraHeaders;
    this.mParser = new HybiParser(this);

    this.mHandlerThread = new HandlerThread(getClass().getName());
    this.mHandlerThread.start();
    this.mHandler = new Handler(mHandlerThread.getLooper());

    return Observable.create(new Observable.OnSubscribe<Event>() {
        @Override
        public void call(Subscriber<? super Event> subscriber) {
            try {
                mSubscriber = subscriber;
                String secret = createSecret();
                String scheme = mUri.getScheme();

                // uri have invalid scheme throw MalformedURLException
                if (scheme == null || !(scheme.equals("ws") || scheme.equals("wss"))) {
                    new MalformedURLException("Url scheme has to be specified as \"ws\" or \"wss\".");
                }

                int port = (mUri.getPort() != -1) ? mUri.getPort() : (scheme.equals("wss") ? 443 : 80);
                String path = TextUtils.isEmpty(mUri.getPath()) ? "/" : mUri.getPath();
                if (!TextUtils.isEmpty(mUri.getQuery())) {
                    path += "?" + mUri.getQuery();
                }

                String originScheme = scheme.equals("wss") ? "https" : "http";
                Uri origin = Uri.parse(originScheme + "://" + mUri.getHost());

                SocketFactory factory = scheme.equals("wss") ? getSSLSocketFactory()
                        : SocketFactory.getDefault();
                mSocket = factory.createSocket(mUri.getHost(), port);

                PrintWriter out = new PrintWriter(mSocket.getOutputStream());
                out.print("GET " + path + " HTTP/1.1\r\n");
                out.print("Upgrade: websocket\r\n");
                out.print("Connection: Upgrade\r\n");
                out.print("Host: " + mUri.getHost() + "\r\n");
                out.print("Origin: " + origin.toString() + "\r\n");
                out.print("Sec-WebSocket-Key: " + secret + "\r\n");
                out.print("Sec-WebSocket-Version: 13\r\n");
                if (mExtraHeaders != null) {
                    for (Pair<String, String> pair : mExtraHeaders) {
                        out.print(String.format("%s: %s\r\n", pair.first, pair.second));
                    }
                }
                out.print("\r\n");
                out.flush();

                HybiParser.HappyDataInputStream stream = new HybiParser.HappyDataInputStream(
                        mSocket.getInputStream());

                // Read HTTP response status line.
                StatusLine statusLine = parseStatusLine(readLine(stream));
                if (statusLine == null) {
                    throw new ConnectException("Received no reply from server.");
                } else if (statusLine.getStatusCode() != HttpStatus.SC_SWITCHING_PROTOCOLS) {
                    throw new ProtocolException(
                            "Server sent invalid response code " + statusLine.getStatusCode()
                                    + ". WebSocket server must return " + HttpStatus.SC_SWITCHING_PROTOCOLS);
                }

                // Read HTTP response headers.
                String line;
                boolean validated = false;

                while (!TextUtils.isEmpty(line = readLine(stream))) {
                    Header header = parseHeader(line);
                    if (header.getName().equals("Sec-WebSocket-Accept")) {
                        String expected = createSecretValidation(secret);
                        String actual = header.getValue().trim();

                        if (!expected.equals(actual)) {
                            throw new ProtocolException("Bad Sec-WebSocket-Accept header value.");
                        }

                        validated = true;
                    }
                }

                if (!validated) {
                    throw new ProtocolException("No Sec-WebSocket-Accept header.");
                }

                mIsConnected = true;
                emitterOnNext(new Event(EventType.CONNECT));

                // Now decode websocket frames.
                mParser.start(stream);
            } catch (Exception e) {
                emitterOnError(e);
            }
        }
    }).doOnUnsubscribe(new Action0() {
        @Override
        public void call() {
            RxWebSocketClient.this.disconnect(false);
        }
    });
}

From source file:bolts.AppLinkTest.java

public void testAppLinkURLNavigationNoTargets() throws Exception {
    String html = getHtmlWithMetaTags();
    Uri uri = getURLForData(html);

    Task<AppLinkNavigation.NavigationResult> task = AppLinkNavigation.navigateInBackground(activityInterceptor,
            uri);/*from   w  w w.j  a v  a  2  s  .c om*/
    waitForTask(task);
    AppLinkNavigation.NavigationResult navigationType = task.getResult();

    assertEquals(AppLinkNavigation.NavigationResult.WEB, navigationType);
    assertEquals(1, openedIntents.size());

    Intent openedIntent = openedIntents.get(0);
    assertTrue(openedIntent.getDataString().startsWith(uri.toString()));
}

From source file:com.google.android.apps.muzei.util.IOUtil.java

public static InputStream openUri(Context context, Uri uri, String reqContentTypeSubstring)
        throws OpenUriException {

    if (uri == null) {
        throw new IllegalArgumentException("Uri cannot be empty");
    }//from   www .  j a  v a2  s .  co m

    String scheme = uri.getScheme();
    InputStream in = null;
    if ("content".equals(scheme)) {
        try {
            in = context.getContentResolver().openInputStream(uri);
        } catch (FileNotFoundException e) {
            throw new OpenUriException(false, e);
        } catch (SecurityException e) {
            throw new OpenUriException(false, e);
        }

    } else if ("file".equals(scheme)) {
        List<String> segments = uri.getPathSegments();
        if (segments != null && segments.size() > 1 && "android_asset".equals(segments.get(0))) {
            AssetManager assetManager = context.getAssets();
            StringBuilder assetPath = new StringBuilder();
            for (int i = 1; i < segments.size(); i++) {
                if (i > 1) {
                    assetPath.append("/");
                }
                assetPath.append(segments.get(i));
            }
            try {
                in = assetManager.open(assetPath.toString());
            } catch (IOException e) {
                throw new OpenUriException(false, e);
            }
        } else {
            try {
                in = new FileInputStream(new File(uri.getPath()));
            } catch (FileNotFoundException e) {
                throw new OpenUriException(false, e);
            }
        }

    } else if ("http".equals(scheme) || "https".equals(scheme)) {
        OkHttpClient client = new OkHttpClient();
        HttpURLConnection conn = null;
        int responseCode = 0;
        String responseMessage = null;
        try {
            conn = client.open(new URL(uri.toString()));
            conn.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT);
            conn.setReadTimeout(DEFAULT_READ_TIMEOUT);
            responseCode = conn.getResponseCode();
            responseMessage = conn.getResponseMessage();
            if (!(responseCode >= 200 && responseCode < 300)) {
                throw new IOException("HTTP error response.");
            }
            if (reqContentTypeSubstring != null) {
                String contentType = conn.getContentType();
                if (contentType == null || contentType.indexOf(reqContentTypeSubstring) < 0) {
                    throw new IOException("HTTP content type '" + contentType + "' didn't match '"
                            + reqContentTypeSubstring + "'.");
                }
            }
            in = conn.getInputStream();

        } catch (MalformedURLException e) {
            throw new OpenUriException(false, e);

        } catch (IOException e) {
            if (conn != null && responseCode > 0) {
                throw new OpenUriException(500 <= responseCode && responseCode < 600, responseMessage, e);
            } else {
                throw new OpenUriException(false, e);
            }

        }
    }

    return in;
}

From source file:com.karura.framework.plugins.Capture.java

/**
 * Creates a JSONObject that represents a File from the Uri
 * /*  w  w  w  . java  2 s .com*/
 * @param data
 *            the Uri of the audio/image/video
 * @return a JSONObject that represents a File
 * @throws IOException
 */
private JSONObject createMediaFile(Uri data) {
    File fp = new File(getRealPathFromURI(data, getActivity()));
    JSONObject obj = new JSONObject();

    try {
        // File properties
        obj.put(MEDIA_FILE_NAME_FIELD, fp.getName());
        obj.put(FILE_PATH_FIELD, "file://" + fp.getAbsolutePath());
        // Because of an issue with MimeTypeMap.getMimeTypeFromExtension() all .3gpp files
        // are reported as video/3gpp. I'm doing this hacky check of the URI to see if it
        // is stored in the audio or video content store.
        if (fp.getAbsoluteFile().toString().endsWith(".3gp")
                || fp.getAbsoluteFile().toString().endsWith(".3gpp")) {
            if (data.toString().contains("/audio/")) {
                obj.put(FILE_TYPE_FIELD, AUDIO_3GPP);
            } else {
                obj.put(FILE_TYPE_FIELD, VIDEO_3GPP);
            }
        } else {
            obj.put(FILE_TYPE_FIELD, getMimeType(fp.getAbsolutePath()));
        }

        obj.put(FILE_MODIFIED_FIELD, fp.lastModified());
        obj.put(FILE_SIZE_FIELD, fp.length());
    } catch (JSONException e) {
        e.printStackTrace();
        return null;
    }

    return obj;
}

From source file:com.skywomantechnology.app.guildviewer.sync.GuildViewerSyncAdapter.java

/**
 * Retrieves the JSON data from the API for the Guild News Feed.
 *
 * @return number of news items obtained from API
 *
 * @see <a href="http://blizzard.github.io/api-wow-docs/">WOW API Documentation</a>
 *///from w  ww  .j av a2  s. c  o m
private int getNewsFromAPI() {

    // get the parameters we need to build the Uri
    String region = Utility.getRegion(mContext);
    String realm = Utility.getRealm(mContext);
    String guild = Utility.getGuildName(mContext);
    try {
        realm = URLEncoder.encode(realm, "UTF-8").replace(Constants.PLUS_SIGN, Constants.SPACE);
        guild = URLEncoder.encode(guild, "UTF-8").replace(Constants.PLUS_SIGN, Constants.SPACE);
    } catch (UnsupportedEncodingException e) {
        //do nothing so as not to crash app ... only no data will display
        e.printStackTrace();

    }

    // Construct the URL for the  query to the WOW APIs
    final String GUILD_NEWS_BASE_URL = "http://" + region + "/api/wow/guild/" + realm + "/" + guild + "?";

    Uri builtUri = Uri.parse(GUILD_NEWS_BASE_URL).buildUpon()
            .appendQueryParameter(Constants.FIELDS_PARAM, Constants.NEWS).build();
    //Log.v(LOG_TAG, "Built URI " + builtUri.toString());

    // get the JSON String and process the JSON objects created from the string
    return processJsonNews(getHTTPData(builtUri.toString()));
}

From source file:com.skywomantechnology.app.guildviewer.sync.GuildViewerSyncAdapter.java

private int getGuildMembersFromAPI() {

    // get the parameters we need to build the Uri
    String region = Utility.getRegion(mContext);
    String realm = Utility.getRealm(mContext);
    String guild = Utility.getGuildName(mContext);
    try {//from w ww . ja  v a  2  s  .  c o m
        realm = URLEncoder.encode(realm, "UTF-8").replace(Constants.PLUS_SIGN, Constants.SPACE);
        guild = URLEncoder.encode(guild, "UTF-8").replace(Constants.PLUS_SIGN, Constants.SPACE);
    } catch (UnsupportedEncodingException e) {
        // do nothing
    }

    // Construct the URL for the  query to the WOW APIs
    final String GUILD_NEWS_BASE_URL = "http://" + region + "/api/wow/guild/" + realm + "/" + guild + "?";

    Uri builtUri = Uri.parse(GUILD_NEWS_BASE_URL).buildUpon()
            .appendQueryParameter(Constants.FIELDS_PARAM, Constants.MEMBERS).build();
    //Log.v(LOG_TAG, "Built URI " + builtUri.toString());

    // get the JSON String and process the JSON objects created from the string
    return processGuildMembers(getHTTPData(builtUri.toString()));
}

From source file:com.flipzu.flipzu.Player.java

private void sendPlay() {
    if (mUrl == null)
        return;/* ww w . j a  va2 s  .c  o m*/

    if (intent == null)
        intent = new Intent(this, FlipzuPlayerService.class);

    intent.setAction(FlipzuPlayerService.ACTION_PLAY);
    Uri data = Uri.parse(mUrl);
    debug.logV(TAG, "sendPlay, got data " + data.toString());
    intent.setData(data);
    intent.putExtra("title", mTitle);
    if (bcast.isLive()) {
        intent.putExtra("live", true);
    } else {
        intent.putExtra("live", false);
        if (!bcast.isLive()) {
            SeekBar seekBar = (SeekBar) findViewById(R.id.seekbar);
            seekBar.setVisibility(View.VISIBLE);
            seekBar.setOnSeekBarChangeListener(this);
        }
    }
    startService(intent);

}

From source file:com.ibuildapp.romanblack.WebPlugin.WebPlugin.java

public void processResult(Intent data, int resultCode) {
    if (null == mUploadMessage)
        nullValueHandler();/*  www  .  j av  a  2 s .c  o m*/

    Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();

    String filePath = result.getPath();

    Uri fileUri = Uri.fromFile(new File(filePath));
    if (isMedia) {
        ContentResolver cR = WebPlugin.this.getContentResolver();
        MimeTypeMap mime = MimeTypeMap.getSingleton();
        String type = mime.getExtensionFromMimeType(cR.getType(result));
        fileUri = Uri.parse(fileUri.toString() + "." + type);

        data.setData(fileUri);
        isMedia = false;
    }

    mUploadMessage.onReceiveValue(fileUri);
    mUploadMessage = null;
}

From source file:com.appsimobile.appsii.module.weather.ImageDownloadHelper.java

@Nullable
public JSONObject searchCityWeatherPhotos(String woeid, int conditionCode, boolean day) throws VolleyError {

    String tags = getTagForConditionCode(conditionCode) + "," + (day ? "day" : "night");

    Uri uri = Uri.parse("https://api.flickr.com/services/rest/").buildUpon()
            .appendQueryParameter("method", "flickr.photos.search")
            .appendQueryParameter("api_key", FLICKR_API_KEY).appendQueryParameter("sort", "relevance")
            .appendQueryParameter("tags", tags).appendQueryParameter("tag_mode", "all")
            .appendQueryParameter("privacy_filter", "1").appendQueryParameter("content_type", "1")
            .appendQueryParameter("group_id", "1463451@N25").
            //                appendQueryParameter("group_id", "1553326@N24").
            appendQueryParameter("woe_id", woeid).appendQueryParameter("media", "photos")
            .appendQueryParameter("extras", extras).appendQueryParameter("format", "json")
            .appendQueryParameter("nojsoncallback", "1").build();

    String url = uri.toString();

    RequestFuture<JSONObject> requestFuture = RequestFuture.newFuture();

    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, requestFuture, requestFuture);
    sRequestQueue.add(request);/*from www .  j a  v a 2s.  c  om*/

    return getResult(requestFuture);
}

From source file:com.safecell.HomeScreenActivity.java

Bitmap getImageFromURI(Uri uri) {
    Bitmap resizedBitmap = null;//from   w w  w . j a va  2  s  .c o m
    String abc = null;
    if (uri != null) {
        String str = uri.toString();
        abc = str.substring(0, 1);
        // Log.v("Safecell :" + "abc", str);
    }

    if (uri != null && abc.equalsIgnoreCase("c")) {
        Uri selectedImage = uri;
        // Log.v("Safecell :" + "Uri", selectedImage.toString());

        String[] proj = { MediaColumns.DATA };
        Cursor cursor = managedQuery(selectedImage, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
        cursor.moveToFirst();

        String path = cursor.getString(column_index);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 4;
        resizedBitmap = BitmapFactory.decodeFile(path, options);
        imageStoreInDatabase(resizedBitmap);

        cursor.close();

        return resizedBitmap;
    } else if (uri != null && abc.equalsIgnoreCase("/")) {

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 4;
        resizedBitmap = BitmapFactory.decodeFile(uri.getPath(), options);
        imageStoreInDatabase(resizedBitmap);
        return resizedBitmap;

    }
    return resizedBitmap;

}