Example usage for android.net Uri getScheme

List of usage examples for android.net Uri getScheme

Introduction

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

Prototype

@Nullable
public abstract String getScheme();

Source Link

Document

Gets the scheme of this URI.

Usage

From source file:com.if3games.chessonline.DroidFish.java

/**
 * Return PGN/FEN data or filename from the Intent. Both can not be non-null.
 * @return Pair of PGN/FEN data and filename.
 *///w  ww. j  av  a 2 s .co m
private final Pair<String, String> getPgnOrFenIntent() {
    String pgnOrFen = null;
    String filename = null;
    try {
        Intent intent = getIntent();
        Uri data = intent.getData();
        if (data == null) {
            Bundle b = intent.getExtras();
            if (b != null) {
                Object strm = b.get(Intent.EXTRA_STREAM);
                if (strm instanceof Uri) {
                    data = (Uri) strm;
                    if ("file".equals(data.getScheme())) {
                        filename = data.getEncodedPath();
                        if (filename != null)
                            filename = Uri.decode(filename);
                    }
                }
            }
        }
        if (data == null) {
            if ((Intent.ACTION_SEND.equals(intent.getAction()) || Intent.ACTION_VIEW.equals(intent.getAction()))
                    && ("application/x-chess-pgn".equals(intent.getType())
                            || "application/x-chess-fen".equals(intent.getType())))
                pgnOrFen = intent.getStringExtra(Intent.EXTRA_TEXT);
        } else {
            String scheme = intent.getScheme();
            if ("file".equals(scheme)) {
                filename = data.getEncodedPath();
                if (filename != null)
                    filename = Uri.decode(filename);
            }
            if ((filename == null) && ("content".equals(scheme) || "file".equals(scheme))) {
                ContentResolver resolver = getContentResolver();
                InputStream in = resolver.openInputStream(intent.getData());
                StringBuilder sb = new StringBuilder();
                while (true) {
                    byte[] buffer = new byte[16384];
                    int len = in.read(buffer);
                    if (len <= 0)
                        break;
                    sb.append(new String(buffer, 0, len));
                }
                pgnOrFen = sb.toString();
            }
        }
    } catch (IOException e) {
        Toast.makeText(getApplicationContext(), R.string.failed_to_read_pgn_data, Toast.LENGTH_SHORT).show();
    }
    return new Pair<String, String>(pgnOrFen, filename);
}

From source file:carnero.cgeo.original.libs.Base.java

public Response request(boolean secure, String host, String path, String method, String params, int requestId,
        Boolean xContentType) {/*from   w ww  .j a v  a 2 s .  co m*/
    URL u = null;
    int httpCode = -1;
    String httpMessage = null;
    String httpLocation = null;

    if (requestId == 0) {
        requestId = (int) (Math.random() * 1000);
    }

    if (method == null
            || (method.equalsIgnoreCase("GET") == false && method.equalsIgnoreCase("POST") == false)) {
        method = "POST";
    } else {
        method = method.toUpperCase();
    }

    // https
    String scheme = "http://";
    if (secure) {
        scheme = "https://";
    }

    // prepare cookies
    String cookiesDone = null;
    if (cookies == null || cookies.isEmpty() == true) {
        if (cookies == null) {
            cookies = new HashMap<String, String>();
        }

        final Map<String, ?> prefsAll = prefs.getAll();
        final Set<String> prefsKeys = prefsAll.keySet();

        for (String key : prefsKeys) {
            if (key.matches("cookie_.+") == true) {
                final String cookieKey = key.substring(7);
                final String cookieValue = (String) prefsAll.get(key);

                cookies.put(cookieKey, cookieValue);
            }
        }
    }

    if (cookies != null && !cookies.isEmpty() && cookies.keySet().size() > 0) {
        final Object[] keys = cookies.keySet().toArray();
        final ArrayList<String> cookiesEncoded = new ArrayList<String>();

        for (int i = 0; i < keys.length; i++) {
            String value = cookies.get(keys[i].toString());
            cookiesEncoded.add(keys[i] + "=" + value);
        }

        if (cookiesEncoded.size() > 0) {
            cookiesDone = implode("; ", cookiesEncoded.toArray());
        }
    }

    if (cookiesDone == null) {
        Map<String, ?> prefsValues = prefs.getAll();

        if (prefsValues != null && prefsValues.size() > 0 && prefsValues.keySet().size() > 0) {
            final Object[] keys = prefsValues.keySet().toArray();
            final ArrayList<String> cookiesEncoded = new ArrayList<String>();
            final int length = keys.length;

            for (int i = 0; i < length; i++) {
                if (keys[i].toString().length() > 7
                        && keys[i].toString().substring(0, 7).equals("cookie_") == true) {
                    cookiesEncoded
                            .add(keys[i].toString().substring(7) + "=" + prefsValues.get(keys[i].toString()));
                }
            }

            if (cookiesEncoded.size() > 0) {
                cookiesDone = implode("; ", cookiesEncoded.toArray());
            }
        }
    }

    if (cookiesDone == null) {
        cookiesDone = "";
    }

    URLConnection uc = null;
    HttpURLConnection connection = null;
    Integer timeout = 30000;
    StringBuffer buffer = null;

    for (int i = 0; i < 5; i++) {
        if (i > 0) {
            Log.w(Settings.tag, "Failed to download data, retrying. Attempt #" + (i + 1));
        }

        buffer = new StringBuffer();
        timeout = 30000 + (i * 10000);

        try {
            if (method.equals("GET")) {
                // GET
                u = new URL(scheme + host + path + "?" + params);
                uc = u.openConnection();

                uc.setRequestProperty("Host", host);
                uc.setRequestProperty("Cookie", cookiesDone);
                if (xContentType == true) {
                    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                }

                if (settings.asBrowser == 1) {
                    uc.setRequestProperty("Accept",
                            "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
                    // uc.setRequestProperty("Accept-Encoding", "gzip"); // not supported via cellular network
                    uc.setRequestProperty("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7");
                    uc.setRequestProperty("Accept-Language", "en-US");
                    uc.setRequestProperty("User-Agent", idBrowser);
                    uc.setRequestProperty("Connection", "keep-alive");
                    uc.setRequestProperty("Keep-Alive", "300");
                }

                connection = (HttpURLConnection) uc;
                connection.setReadTimeout(timeout);
                connection.setRequestMethod(method);
                HttpURLConnection.setFollowRedirects(false);
                connection.setDoInput(true);
                connection.setDoOutput(false);
            } else {
                // POST
                u = new URL(scheme + host + path);
                uc = u.openConnection();

                uc.setRequestProperty("Host", host);
                uc.setRequestProperty("Cookie", cookiesDone);
                if (xContentType == true) {
                    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                }

                if (settings.asBrowser == 1) {
                    uc.setRequestProperty("Accept",
                            "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
                    // uc.setRequestProperty("Accept-Encoding", "gzip"); // not supported via cellular network
                    uc.setRequestProperty("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7");
                    uc.setRequestProperty("Accept-Language", "en-US");
                    uc.setRequestProperty("User-Agent", idBrowser);
                    uc.setRequestProperty("Connection", "keep-alive");
                    uc.setRequestProperty("Keep-Alive", "300");
                }

                connection = (HttpURLConnection) uc;
                connection.setReadTimeout(timeout);
                connection.setRequestMethod(method);
                HttpURLConnection.setFollowRedirects(false);
                connection.setDoInput(true);
                connection.setDoOutput(true);

                final OutputStream out = connection.getOutputStream();
                final OutputStreamWriter wr = new OutputStreamWriter(out);
                wr.write(params);
                wr.flush();
                wr.close();
            }

            String headerName = null;
            final SharedPreferences.Editor prefsEditor = prefs.edit();
            for (int j = 1; (headerName = uc.getHeaderFieldKey(j)) != null; j++) {
                if (headerName != null && headerName.equalsIgnoreCase("Set-Cookie")) {
                    int index;
                    String cookie = uc.getHeaderField(j);

                    index = cookie.indexOf(";");
                    if (index > -1) {
                        cookie = cookie.substring(0, cookie.indexOf(";"));
                    }

                    index = cookie.indexOf("=");
                    if (index > -1 && cookie.length() > (index + 1)) {
                        String name = cookie.substring(0, cookie.indexOf("="));
                        String value = cookie.substring(cookie.indexOf("=") + 1, cookie.length());

                        cookies.put(name, value);
                        prefsEditor.putString("cookie_" + name, value);
                    }
                }
            }
            prefsEditor.commit();

            final String encoding = connection.getContentEncoding();
            InputStream ins;

            if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
                ins = new GZIPInputStream(connection.getInputStream());
            } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
                ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true));
            } else {
                ins = connection.getInputStream();
            }
            final InputStreamReader inr = new InputStreamReader(ins);
            final BufferedReader br = new BufferedReader(inr);

            readIntoBuffer(br, buffer);

            httpCode = connection.getResponseCode();
            httpMessage = connection.getResponseMessage();
            httpLocation = uc.getHeaderField("Location");

            final String paramsLog = params.replaceAll(passMatch, "password=***");
            if (buffer != null && connection != null) {
                Log.i(Settings.tag + "|" + requestId,
                        "[" + method + " " + (int) (params.length() / 1024) + "k | " + httpCode + " | "
                                + (int) (buffer.length() / 1024) + "k] Downloaded " + scheme + host + path + "?"
                                + paramsLog);
            } else {
                Log.i(Settings.tag + "|" + requestId, "[" + method + " | " + httpCode + "] Failed to download "
                        + scheme + host + path + "?" + paramsLog);
            }

            connection.disconnect();
            br.close();
            ins.close();
            inr.close();
        } catch (IOException e) {
            Log.e(Settings.tag, "cgeoBase.request.IOException: " + e.toString());
        } catch (Exception e) {
            Log.e(Settings.tag, "cgeoBase.request: " + e.toString());
        }

        if (buffer != null && buffer.length() > 0) {
            break;
        }
    }

    Response response = new Response();
    String data = null;

    try {
        if (httpCode == 302 && httpLocation != null) {
            final Uri newLocation = Uri.parse(httpLocation);
            if (newLocation.isRelative() == true) {
                response = request(secure, host, path, "GET", new HashMap<String, String>(), requestId, false,
                        false, false);
            } else {
                boolean secureRedir = false;
                if (newLocation.getScheme().equals("https")) {
                    secureRedir = true;
                }
                response = request(secureRedir, newLocation.getHost(), newLocation.getPath(), "GET",
                        new HashMap<String, String>(), requestId, false, false, false);
            }
        } else {
            if (buffer != null && buffer.length() > 0) {
                data = replaceWhitespace(buffer);
                buffer = null;

                if (data != null) {
                    response.setData(data);
                } else {
                    response.setData("");
                }
                response.setStatusCode(httpCode);
                response.setStatusMessage(httpMessage);
                response.setUrl(u.toString());
            }
        }
    } catch (Exception e) {
        Log.e(Settings.tag, "cgeoBase.page: " + e.toString());
    }

    return response;
}

From source file:com.tct.mail.compose.ComposeActivity.java

/**
 * Fill all the widgets with the content found in the Intent Extra, if any.
 * Also apply the same style to all widgets. Note: if initFromExtras is
 * called as a result of switching between reply, reply all, and forward per
 * the latest revision of Gmail, and the user has already made changes to
 * attachments on a previous incarnation of the message (as a reply, reply
 * all, or forward), the original attachments from the message will not be
 * re-instantiated. The user's changes will be respected. This follows the
 * web gmail interaction.//from w  w  w.  j a  v  a  2 s  .c  o m
 * @return {@code true} if the activity should not call {@link #finishSetup}.
 */
public boolean initFromExtras(Intent intent) {
    // If we were invoked with a SENDTO intent, the value
    // should take precedence
    final Uri dataUri = intent.getData();
    if (dataUri != null) {
        if (MAIL_TO.equals(dataUri.getScheme())) {
            initFromMailTo(dataUri.toString());
        } else {
            if (!mAccount.composeIntentUri.equals(dataUri)) {
                String toText = dataUri.getSchemeSpecificPart();
                // TS: junwei-xu 2015-03-23 EMAIL BUGFIX_980239 MOD_S
                //if (toText != null) {
                if (Address.isAllValid(toText)) {
                    // TS: junwei-xu 2015-04-23 EMAIL BUGFIX_980239 MOD_E
                    mTo.setText("");
                    addToAddresses(Arrays.asList(TextUtils.split(toText, ",")));
                }
            }
        }
    }

    String[] extraStrings = intent.getStringArrayExtra(Intent.EXTRA_EMAIL);
    if (extraStrings != null) {
        addToAddresses(Arrays.asList(extraStrings));
    }
    extraStrings = intent.getStringArrayExtra(Intent.EXTRA_CC);
    if (extraStrings != null) {
        addCcAddresses(Arrays.asList(extraStrings), null);
    }
    extraStrings = intent.getStringArrayExtra(Intent.EXTRA_BCC);
    if (extraStrings != null) {
        addBccAddresses(Arrays.asList(extraStrings));
    }

    String extraString = intent.getStringExtra(Intent.EXTRA_SUBJECT);
    if (extraString != null) {
        mSubject.setText(extraString);
    }

    for (String extra : ALL_EXTRAS) {
        if (intent.hasExtra(extra)) {
            String value = intent.getStringExtra(extra);
            if (EXTRA_TO.equals(extra)) {
                addToAddresses(Arrays.asList(TextUtils.split(value, ",")));
            } else if (EXTRA_CC.equals(extra)) {
                addCcAddresses(Arrays.asList(TextUtils.split(value, ",")), null);
            } else if (EXTRA_BCC.equals(extra)) {
                addBccAddresses(Arrays.asList(TextUtils.split(value, ",")));
            } else if (EXTRA_SUBJECT.equals(extra)) {
                mSubject.setText(value);
            } else if (EXTRA_BODY.equals(extra)) {
                //[BUGFIX]-Add-BEGINbySCDTABLET.yafang.wei,07/21/2016,2565329
                // Modifytofixsignatureshowsbeforebodyissuewhensharewebsitebyemail
                if (mBodyView.getText().toString().trim()
                        .equals(convertToPrintableSignature(mSignature).trim())) {
                    mBodyView.setText("");
                    setBody(value, true /* with signature */);
                    appendSignature();
                } else {
                    setBody(value, true /* with signature */);
                }
                //[BUGFIX]-Add-ENDbySCDTABLET.yafang.wei
            } else if (EXTRA_QUOTED_TEXT.equals(extra)) {
                initQuotedText(value, true /* shouldQuoteText */);
            }
        }
    }

    Bundle extras = intent.getExtras();
    //[BUGFIX]-MOD-BEGIN by TSNJ,wenlu.wu,10/20/2014,FR-739335
    if (extras != null && !mBodyAlreadySet) {
        //[BUGFIX]-MOD-END by TSNJ,wenlu.wu,10/20/2014,FR-739335
        CharSequence text = extras.getCharSequence(Intent.EXTRA_TEXT);
        //[BUGFIX]-Add-BEGINbySCDTABLET.yafang.wei,07/21/2016,2565329
        // Modifytofixsignatureshowsbeforebodyissuewhensharewebsitebyemail
        if (mBodyView.getText().toString().trim().equals(convertToPrintableSignature(mSignature).trim())) {
            mBodyView.setText("");
            setBody((text != null) ? text : "", true /* with signature */);
            appendSignature();
        } else {
            setBody((text != null) ? text : "", true /* with signature */);
        }
        //[BUGFIX]-Add-ENDbySCDTABLET.yafang.wei

        // TODO - support EXTRA_HTML_TEXT
    }

    mExtraValues = intent.getParcelableExtra(EXTRA_VALUES);
    if (mExtraValues != null) {
        LogUtils.d(LOG_TAG, "Launched with extra values: %s", mExtraValues.toString());
        initExtraValues(mExtraValues);
        return true;
    }

    return false;
}

From source file:com.tct.mail.compose.ComposeActivity.java

@SuppressLint("NewApi")
public String getFilePath(Uri uri) {
    Uri thisUri = null;
    String path = "";

    ContentResolver cr = this.getContentResolver();
    if (uri == null) {
        return path;
    }//from   ww w  .  j av  a  2 s .c  o  m
    thisUri = uri;

    try {

        String scheme = thisUri.getScheme();

        if (scheme == null) {
            path = thisUri.toString();
        } else if (scheme.equals("file")) {
            path = thisUri.getPath();
            path = changeDrmFileSuffix(path);
        }

        else if (DocumentsContract.isDocumentUri(this, uri)) {
            //ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {
                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris
                        .withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                return getDataColumn(this, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                contentUri = contentUri.withAppendedPath(contentUri, split[1]);
                return getDataColumn(this, contentUri, null, null);
            }
        }

        else if (scheme.equals("content")) {
            String[] projection = { "_data" };
            Cursor c = cr.query(thisUri, projection, null, null, null);
            if (c != null) {
                try {
                    if (c.moveToFirst()) {
                        path = c.getString(0);
                    }
                } finally {
                    c.close();
                }
            }

            if (path.endsWith("RAW")) {
                List<String> segments = thisUri.getPathSegments();
                String dbName = segments.get(0);
                String id = segments.get(1);
                path = this.getDatabasePath(dbName + "_att") + "/" + id;
            }

        }
    } catch (Exception e) {
    }
    return path;
}

From source file:carnero.cgeo.cgBase.java

public cgResponse request(boolean secure, String host, String path, String method, String params, int requestId,
        Boolean xContentType) {/*from ww  w . jav a 2s.c o  m*/
    URL u = null;
    int httpCode = -1;
    String httpMessage = null;
    String httpLocation = null;

    if (requestId == 0) {
        requestId = (int) (Math.random() * 1000);
    }

    if (method == null
            || (method.equalsIgnoreCase("GET") == false && method.equalsIgnoreCase("POST") == false)) {
        method = "POST";
    } else {
        method = method.toUpperCase();
    }

    // https
    String scheme = "http://";
    if (secure) {
        scheme = "https://";
    }

    // prepare cookies
    String cookiesDone = null;
    if (cookies == null || cookies.isEmpty() == true) {
        if (cookies == null) {
            cookies = new HashMap<String, String>();
        }

        final Map<String, ?> prefsAll = prefs.getAll();
        final Set<String> prefsKeys = prefsAll.keySet();

        for (String key : prefsKeys) {
            if (key.matches("cookie_.+") == true) {
                final String cookieKey = key.substring(7);
                final String cookieValue = (String) prefsAll.get(key);

                cookies.put(cookieKey, cookieValue);
            }
        }
    }

    if (cookies != null && !cookies.isEmpty() && cookies.keySet().size() > 0) {
        final Object[] keys = cookies.keySet().toArray();
        final ArrayList<String> cookiesEncoded = new ArrayList<String>();

        for (int i = 0; i < keys.length; i++) {
            String value = cookies.get(keys[i].toString());
            cookiesEncoded.add(keys[i] + "=" + value);
        }

        if (cookiesEncoded.size() > 0) {
            cookiesDone = implode("; ", cookiesEncoded.toArray());
        }
    }

    if (cookiesDone == null) {
        Map<String, ?> prefsValues = prefs.getAll();

        if (prefsValues != null && prefsValues.size() > 0 && prefsValues.keySet().size() > 0) {
            final Object[] keys = prefsValues.keySet().toArray();
            final ArrayList<String> cookiesEncoded = new ArrayList<String>();
            final int length = keys.length;

            for (int i = 0; i < length; i++) {
                if (keys[i].toString().length() > 7
                        && keys[i].toString().substring(0, 7).equals("cookie_") == true) {
                    cookiesEncoded
                            .add(keys[i].toString().substring(7) + "=" + prefsValues.get(keys[i].toString()));
                }
            }

            if (cookiesEncoded.size() > 0) {
                cookiesDone = implode("; ", cookiesEncoded.toArray());
            }
        }
    }

    if (cookiesDone == null) {
        cookiesDone = "";
    }

    URLConnection uc = null;
    HttpURLConnection connection = null;
    Integer timeout = 30000;
    StringBuffer buffer = null;

    for (int i = 0; i < 5; i++) {
        if (i > 0) {
            Log.w(cgSettings.tag, "Failed to download data, retrying. Attempt #" + (i + 1));
        }

        buffer = new StringBuffer();
        timeout = 30000 + (i * 10000);

        try {
            if (method.equals("GET")) {
                // GET
                u = new URL(scheme + host + path + "?" + params);
                uc = u.openConnection();

                uc.setRequestProperty("Host", host);
                uc.setRequestProperty("Cookie", cookiesDone);
                if (xContentType == true) {
                    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                }

                if (settings.asBrowser == 1) {
                    uc.setRequestProperty("Accept",
                            "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
                    // uc.setRequestProperty("Accept-Encoding", "gzip"); // not supported via cellular network
                    uc.setRequestProperty("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7");
                    uc.setRequestProperty("Accept-Language", "en-US");
                    uc.setRequestProperty("User-Agent", idBrowser);
                    uc.setRequestProperty("Connection", "keep-alive");
                    uc.setRequestProperty("Keep-Alive", "300");
                }

                connection = (HttpURLConnection) uc;
                connection.setReadTimeout(timeout);
                connection.setRequestMethod(method);
                HttpURLConnection.setFollowRedirects(false);
                connection.setDoInput(true);
                connection.setDoOutput(false);
            } else {
                // POST
                u = new URL(scheme + host + path);
                uc = u.openConnection();

                uc.setRequestProperty("Host", host);
                uc.setRequestProperty("Cookie", cookiesDone);
                if (xContentType == true) {
                    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                }

                if (settings.asBrowser == 1) {
                    uc.setRequestProperty("Accept",
                            "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
                    // uc.setRequestProperty("Accept-Encoding", "gzip"); // not supported via cellular network
                    uc.setRequestProperty("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7");
                    uc.setRequestProperty("Accept-Language", "en-US");
                    uc.setRequestProperty("User-Agent", idBrowser);
                    uc.setRequestProperty("Connection", "keep-alive");
                    uc.setRequestProperty("Keep-Alive", "300");
                }

                connection = (HttpURLConnection) uc;
                connection.setReadTimeout(timeout);
                connection.setRequestMethod(method);
                HttpURLConnection.setFollowRedirects(false);
                connection.setDoInput(true);
                connection.setDoOutput(true);

                final OutputStream out = connection.getOutputStream();
                final OutputStreamWriter wr = new OutputStreamWriter(out);
                wr.write(params);
                wr.flush();
                wr.close();
            }

            String headerName = null;
            final SharedPreferences.Editor prefsEditor = prefs.edit();
            for (int j = 1; (headerName = uc.getHeaderFieldKey(j)) != null; j++) {
                if (headerName != null && headerName.equalsIgnoreCase("Set-Cookie")) {
                    int index;
                    String cookie = uc.getHeaderField(j);

                    index = cookie.indexOf(";");
                    if (index > -1) {
                        cookie = cookie.substring(0, cookie.indexOf(";"));
                    }

                    index = cookie.indexOf("=");
                    if (index > -1 && cookie.length() > (index + 1)) {
                        String name = cookie.substring(0, cookie.indexOf("="));
                        String value = cookie.substring(cookie.indexOf("=") + 1, cookie.length());

                        cookies.put(name, value);
                        prefsEditor.putString("cookie_" + name, value);
                    }
                }
            }
            prefsEditor.commit();

            final String encoding = connection.getContentEncoding();
            InputStream ins;

            if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
                ins = new GZIPInputStream(connection.getInputStream());
            } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
                ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true));
            } else {
                ins = connection.getInputStream();
            }
            final InputStreamReader inr = new InputStreamReader(ins);
            final BufferedReader br = new BufferedReader(inr);

            readIntoBuffer(br, buffer);

            httpCode = connection.getResponseCode();
            httpMessage = connection.getResponseMessage();
            httpLocation = uc.getHeaderField("Location");

            final String paramsLog = params.replaceAll(passMatch, "password=***");
            if (buffer != null && connection != null) {
                Log.i(cgSettings.tag + "|" + requestId,
                        "[" + method + " " + (int) (params.length() / 1024) + "k | " + httpCode + " | "
                                + (int) (buffer.length() / 1024) + "k] Downloaded " + scheme + host + path + "?"
                                + paramsLog);
            } else {
                Log.i(cgSettings.tag + "|" + requestId, "[" + method + " | " + httpCode
                        + "] Failed to download " + scheme + host + path + "?" + paramsLog);
            }

            connection.disconnect();
            br.close();
            ins.close();
            inr.close();
        } catch (IOException e) {
            Log.e(cgSettings.tag, "cgeoBase.request.IOException: " + e.toString());
        } catch (Exception e) {
            Log.e(cgSettings.tag, "cgeoBase.request: " + e.toString());
        }

        if (buffer != null && buffer.length() > 0) {
            break;
        }
    }

    cgResponse response = new cgResponse();
    String data = null;

    try {
        if (httpCode == 302 && httpLocation != null) {
            final Uri newLocation = Uri.parse(httpLocation);
            if (newLocation.isRelative() == true) {
                response = request(secure, host, path, "GET", new HashMap<String, String>(), requestId, false,
                        false, false);
            } else {
                boolean secureRedir = false;
                if (newLocation.getScheme().equals("https")) {
                    secureRedir = true;
                }
                response = request(secureRedir, newLocation.getHost(), newLocation.getPath(), "GET",
                        new HashMap<String, String>(), requestId, false, false, false);
            }
        } else {
            if (buffer != null && buffer.length() > 0) {
                data = replaceWhitespace(buffer);
                buffer = null;

                if (data != null) {
                    response.setData(data);
                } else {
                    response.setData("");
                }
                response.setStatusCode(httpCode);
                response.setStatusMessage(httpMessage);
                response.setUrl(u.toString());
            }
        }
    } catch (Exception e) {
        Log.e(cgSettings.tag, "cgeoBase.page: " + e.toString());
    }

    return response;
}

From source file:com.codename1.impl.android.AndroidImplementation.java

private String getImageFilePath(Uri uri) {

    File file = new File(uri.getPath());
    String scheme = uri.getScheme();
    //String[] filePaths = file.getPath().split(":");
    //String image_id = filePath[filePath.length - 1];
    String[] filePathColumn = { MediaStore.Images.Media.DATA };
    Cursor cursor = getContext().getContentResolver().query(
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            new String[] { MediaStore.Images.Media.DATA }, null, null, null);
    cursor.moveToFirst();/*from ww  w  .  j  a v a2s. com*/
    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
    String filePath = cursor.getString(columnIndex);
    cursor.close();

    if (filePath == null || "content".equals(scheme)) {
        //if the file is not on the filesystem download it and save it
        //locally
        try {
            InputStream inputStream = getContext().getContentResolver().openInputStream(uri);
            if (inputStream != null) {
                String name = new File(uri.toString()).getName();//getContentName(getContext().getContentResolver(), uri);
                if (name != null) {
                    String homePath = getAppHomePath();
                    if (homePath.endsWith("/")) {
                        homePath = homePath.substring(0, homePath.length() - 1);
                    }
                    filePath = homePath + getFileSystemSeparator() + name;
                    File f = new File(removeFilePrefix(filePath));
                    OutputStream tmp = createFileOuputStream(f);
                    byte[] buffer = new byte[1024];
                    int read = -1;
                    while ((read = inputStream.read(buffer)) > -1) {
                        tmp.write(buffer, 0, read);
                    }
                    tmp.close();
                    inputStream.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //long len = new com.codename1.io.File(filePath).length();
    return filePath;
}

From source file:com.codename1.impl.android.AndroidImplementation.java

@Override
public String getAppArg() {
    if (super.getAppArg() != null) {
        // This just maintains backward compatibility in case people are manually
        // setting the AppArg in their properties.  It reproduces the general
        // behaviour the existed when AppArg was just another Display property.
        return super.getAppArg();
    }//from ww w  .ja  v a2  s.  c  o  m
    if (getActivity() == null) {
        return null;
    }

    android.content.Intent intent = getActivity().getIntent();
    if (intent != null) {
        Uri u = intent.getData();
        String scheme = intent.getScheme();
        if (u == null && intent.getExtras() != null) {
            if (intent.getExtras().keySet().contains("android.intent.extra.STREAM")) {
                try {
                    u = (Uri) intent.getParcelableExtra("android.intent.extra.STREAM");
                    scheme = u.getScheme();
                    System.out.println("u=" + u);
                } catch (Exception ex) {
                    Log.d("Codename One", "Failed to load parcelable extra from intent: " + ex.getMessage());
                }
            }

        }
        if (u != null) {
            //String scheme = intent.getScheme();
            intent.setData(null);
            if ("content".equals(scheme)) {
                try {
                    InputStream attachment = getActivity().getContentResolver().openInputStream(u);
                    if (attachment != null) {
                        String name = getContentName(getActivity().getContentResolver(), u);
                        if (name != null) {
                            String filePath = getAppHomePath() + getFileSystemSeparator() + name;
                            File f = new File(filePath);
                            OutputStream tmp = createFileOuputStream(f);
                            byte[] buffer = new byte[1024];
                            int read = -1;
                            while ((read = attachment.read(buffer)) > -1) {
                                tmp.write(buffer, 0, read);
                            }
                            tmp.close();
                            attachment.close();
                            setAppArg(filePath);
                            return filePath;
                        }
                    }
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    return null;
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                } catch (Exception e) {
                    e.printStackTrace();
                    return null;
                }
            } else {

                /*
                // Why do we need this special case?  u.toString()
                // will include the full URL including query string.
                // This special case causes urls like myscheme://part1/part2
                // to only return "/part2" which is obviously problematic and
                // is inconsistent with iOS.  Is this special case necessary
                // in some versions of Android?
                String encodedPath = u.getEncodedPath();
                if (encodedPath != null && encodedPath.length() > 0) {
                String query = u.getQuery();
                if(query != null && query.length() > 0){
                    encodedPath += "?" + query;
                }
                setAppArg(encodedPath);
                return encodedPath;
                }
                */
                setAppArg(u.toString());
                return u.toString();
            }
        }
    }
    return null;
}