Example usage for org.apache.http.util ByteArrayBuffer append

List of usage examples for org.apache.http.util ByteArrayBuffer append

Introduction

In this page you can find the example usage for org.apache.http.util ByteArrayBuffer append.

Prototype

public void append(int i) 

Source Link

Usage

From source file:com.gvccracing.android.tttimer.Tabs.RaceInfoTab.java

public void postData() {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(
            "http://www.gvccracing.com/?page_id=2525&pass=com.gvccracing.android.tttimer");

    try {/*w ww .j a v  a  2s  . c om*/
        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

        InputStream is = response.getEntity().getContent();
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(20);

        int current = 0;

        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }

        /* Convert the Bytes read to a String. */
        String text = new String(baf.toByteArray());

        JSONObject mainJson = new JSONObject(text);
        JSONArray jsonArray = mainJson.getJSONArray("members");

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject json = jsonArray.getJSONObject(i);

            String firstName = json.getString("fname");
            String lastName = json.getString("lname");
            String licenseStr = json.getString("license");
            Integer license = 0;
            try {
                license = Integer.parseInt(licenseStr);
            } catch (Exception ex) {
                Log.e(LOG_TAG(), "Unable to parse license string");
            }
            long age = json.getLong("age");
            String categoryStr = json.getString("category");
            Integer category = 5;
            try {
                category = Integer.parseInt(categoryStr);
            } catch (Exception ex) {
                Log.e(LOG_TAG(), "Unable to parse category string");
            }
            String phone = json.getString("phone");
            long phoneNumber = 0;
            try {
                phoneNumber = Long.parseLong(phone.replace("-", "").replace("(", "").replace(")", "")
                        .replace(" ", "").replace(".", "").replace("*", ""));
            } catch (Exception e) {
                Log.e(LOG_TAG(), "Unable to parse phone number");
            }
            String gender = json.getString("gender");
            String econtact = json.getString("econtact");
            String econtactPhone = json.getString("econtact_phone");
            long eContactPhoneNumber = 0;
            try {
                eContactPhoneNumber = Long.parseLong(econtactPhone.replace("-", "").replace("(", "")
                        .replace(")", "").replace(" ", "").replace(".", "").replace("*", ""));
            } catch (Exception e) {
                Log.e(LOG_TAG(), "Unable to parse econtact phone number");
            }
            Long member_id = json.getLong("member_id");

            String gvccCategory;
            switch (category) {
            case 1:
            case 2:
            case 3:
                gvccCategory = "A";
                break;
            case 4:
                gvccCategory = "B4";
                break;
            case 5:
                gvccCategory = "B5";
                break;
            default:
                gvccCategory = "B5";
                break;
            }

            Log.w(LOG_TAG(), lastName);
            Cursor racerInfo = Racer.Instance().Read(getActivity(),
                    new String[] { Racer._ID, Racer.FirstName, Racer.LastName, Racer.USACNumber,
                            Racer.PhoneNumber, Racer.EmergencyContactName, Racer.EmergencyContactPhoneNumber },
                    Racer.USACNumber + "=?", new String[] { license.toString() }, null);
            if (racerInfo.getCount() > 0) {
                racerInfo.moveToFirst();
                Long racerID = racerInfo.getLong(racerInfo.getColumnIndex(Racer._ID));
                Racer.Instance().Update(getActivity(), racerID, firstName, lastName, license, 0l, phoneNumber,
                        econtact, eContactPhoneNumber, gender);
                Cursor racerClubInfo = RacerClubInfo.Instance().Read(getActivity(),
                        new String[] { RacerClubInfo._ID, RacerClubInfo.GVCCID, RacerClubInfo.RacerAge,
                                RacerClubInfo.Category },
                        RacerClubInfo.Racer_ID + "=? AND " + RacerClubInfo.Year + "=? AND "
                                + RacerClubInfo.Upgraded + "=?",
                        new String[] { racerID.toString(), "2013", "0" }, null);
                if (racerClubInfo.getCount() > 0) {
                    racerClubInfo.moveToFirst();
                    long racerClubInfoID = racerClubInfo
                            .getLong(racerClubInfo.getColumnIndex(RacerClubInfo._ID));
                    String rciCategory = racerClubInfo
                            .getString(racerClubInfo.getColumnIndex(RacerClubInfo.Category));

                    boolean upgraded = gvccCategory != rciCategory;
                    if (upgraded) {
                        RacerClubInfo.Instance().Update(getActivity(), racerClubInfoID, null, null, null, null,
                                null, null, null, null, null, upgraded);
                        RacerClubInfo.Instance().Create(getActivity(), racerID, null, 2013, gvccCategory, 0, 0,
                                0, age, member_id, false);
                    } else {
                        RacerClubInfo.Instance().Update(getActivity(), racerClubInfoID, null, null, null, null,
                                null, null, null, age, member_id, upgraded);
                    }

                } else {
                    RacerClubInfo.Instance().Create(getActivity(), racerID, null, 2013, gvccCategory, 0, 0, 0,
                            age, member_id, false);
                }
                if (racerClubInfo != null) {
                    racerClubInfo.close();
                }
            } else {
                // TODO: Better birth date
                Uri resultUri = Racer.Instance().Create(getActivity(), firstName, lastName, license, 0l,
                        phoneNumber, econtact, eContactPhoneNumber, gender);
                long racerID = Long.parseLong(resultUri.getLastPathSegment());
                RacerClubInfo.Instance().Create(getActivity(), racerID, null, 2013, gvccCategory, 0, 0, 0, age,
                        member_id, false);
            }
            if (racerInfo != null) {
                racerInfo.close();
            }
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        Log.e(LOG_TAG(), e.getMessage());
    }
}

From source file:com.vkassin.mtrade.Common.java

public static String generalWebServiceCall(String urlStr, ContentHandler handler) {

    String errorMsg = "";

    try {//from  w w w.j  av a  2  s .c o  m
        URL url = new URL(urlStr);

        HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
        urlc.setRequestProperty("User-Agent", "Android Application: aMTrade");
        urlc.setRequestProperty("Connection", "close");
        // urlc.setRequestProperty("Accept-Charset", "windows-1251");
        // urlc.setRequestProperty("Accept-Charset",
        // "windows-1251,utf-8;q=0.7,*;q=0.7");
        urlc.setRequestProperty("Accept-Charset", "utf-8");

        urlc.setConnectTimeout(1000 * 5); // mTimeout is in seconds
        urlc.setDoInput(true);
        urlc.connect();

        if (urlc.getResponseCode() == HttpURLConnection.HTTP_OK) {
            // Get a SAXParser from the SAXPArserFactory.
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();

            // Get the XMLReader of the SAXParser we created.
            XMLReader xr = sp.getXMLReader();

            // Apply the handler to the XML-Reader
            xr.setContentHandler(handler);

            // Parse the XML-data from our URL.
            InputStream is = urlc.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            ByteArrayBuffer baf = new ByteArrayBuffer(500);
            int current = 0;
            while ((current = bis.read()) != -1) {
                baf.append((byte) current);
            }
            ByteArrayInputStream bais = new ByteArrayInputStream(baf.toByteArray());
            // Reader isr = new InputStreamReader(bais, "windows-1251");
            Reader isr = new InputStreamReader(bais, "utf-8");
            InputSource ist = new InputSource();
            // ist.setEncoding("UTF-8");
            ist.setCharacterStream(isr);
            xr.parse(ist);
            // Parsing has finished.

            bis.close();
            baf.clear();
            bais.close();
            is.close();
        }

        urlc.disconnect();

    } catch (SAXException e) {
        // All is OK :)
    } catch (MalformedURLException e) {
        Log.e(TAG, errorMsg = "MalformedURLException");
    } catch (IOException e) {
        Log.e(TAG, errorMsg = "IOException");
    } catch (ParserConfigurationException e) {
        Log.e(TAG, errorMsg = "ParserConfigurationException");
    } catch (ArrayIndexOutOfBoundsException e) {
        Log.e(TAG, errorMsg = "ArrayIndexOutOfBoundsException");
    }

    return errorMsg;
}

From source file:com.development.androrb.listfolders.java

private String loaddata(String Urli) {
    try {/*from  w ww . j  a va2s.  c o  m*/
        URLConnection conn;
        conn = new URL(Urli).openConnection();

        InputStream is = conn.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(8192);

        // loading part
        int current = 0;

        while ((current = bis.read()) != -1) {

            baf.append((byte) current);
        }
        //Log.i(TAG, " *------ after while -----*: "+current);
        html = EncodingUtils.getString(baf.toByteArray(), "UTF-8");

    } catch (Exception e) {
        TextUpdate = "Ups, check your Connection ...";
        runOnUiThread(showTextUpdate);

        //Toast.makeText(this, "Shit, Loading Error!", Toast.LENGTH_SHORT).show();
    }

    return html;
}

From source file:org.golang.app.WViewActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //Fixed Portrait orientation
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    /*this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
    WindowManager.LayoutParams.FLAG_FULLSCREEN);*/

    setContentView(R.layout.webview);/* w  w w .j a v  a 2  s .co  m*/
    WebView webView = (WebView) findViewById(R.id.webView1);

    initWebView(webView);
    webView.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            Log.d("JavaGoWV: ", url);

            final Pattern p = Pattern.compile("dcoinKey&password=(.*)$");
            final Matcher m = p.matcher(url);
            if (m.find()) {
                try {
                    Thread thread = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                //File root = android.os.Environment.getExternalStorageDirectory();
                                File dir = Environment
                                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
                                Log.d("JavaGoWV", "dir " + dir);

                                URL keyUrl = new URL(
                                        "http://127.0.0.1:8089/ajax?controllerName=dcoinKey&first=1"); //you can write here any link
                                //URL keyUrl = new URL("http://yandex.ru/"); //you can write here any link
                                File file = new File(dir, "dcoin-key.png");

                                long startTime = System.currentTimeMillis();
                                Log.d("JavaGoWV", "download begining");
                                Log.d("JavaGoWV", "download keyUrl:" + keyUrl);

                                /* Open a connection to that URL. */
                                URLConnection ucon = keyUrl.openConnection();

                                Log.d("JavaGoWV", "0");
                                /*
                                * Define InputStreams to read from the URLConnection.
                                */
                                InputStream is = ucon.getInputStream();

                                Log.d("JavaGoWV", "01");

                                BufferedInputStream bis = new BufferedInputStream(is);

                                Log.d("JavaGoWV", "1");
                                /*
                                * Read bytes to the Buffer until there is nothing more to read(-1).
                                */
                                ByteArrayBuffer baf = new ByteArrayBuffer(5000);
                                int current = 0;
                                while ((current = bis.read()) != -1) {
                                    baf.append((byte) current);
                                }

                                Log.d("JavaGoWV", "2");
                                /* Convert the Bytes read to a String. */
                                FileOutputStream fos = new FileOutputStream(file);
                                fos.write(baf.toByteArray());
                                fos.flush();
                                fos.close();

                                Log.d("JavaGoWV", "3");
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                                    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                                    Uri contentUri = Uri.fromFile(file);
                                    mediaScanIntent.setData(contentUri);
                                    WViewActivity.this.sendBroadcast(mediaScanIntent);
                                } else {
                                    sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                                            Uri.parse("file://" + Environment.getExternalStorageDirectory())));
                                }

                                Log.d("JavaGoWV", "4");
                            } catch (Exception e) {
                                Log.e("JavaGoWV error 0", e.toString());
                                e.printStackTrace();
                            }
                        }
                    });
                    thread.start();

                } catch (Exception e) {
                    Log.e("JavaGoWV error", e.toString());
                    e.printStackTrace();
                }
            }
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            Log.e("JavaGoWV", "shouldOverrideUrlLoading " + url);

            if (url.endsWith(".mp4")) {
                Intent in = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(in);
                return true;
            } else {
                return false;
            }
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            Log.d("JavaGoWV",
                    "failed: " + failingUrl + ", error code: " + errorCode + " [" + description + "]");
        }
    });

    SystemClock.sleep(1500);
    //if (MyService.DcoinStarted(8089)) {
    webView.loadUrl("http://localhost:8089/");
    //}

}

From source file:com.attentec.AttentecService.java

/**
 * Fetch image from server.//from  w w  w. jav a2 s  .  c  o  m
 * @param path to the image
 * @return return png image as an ByteArray
 * @throws GetImageException on failure of any kind
 */
private byte[] getImage(final String path) throws GetImageException {
    URL url;
    try {
        url = new URL(PreferencesHelper.getServerUrlbase(ctx) + path.replaceAll(" ", "%20"));
    } catch (MalformedURLException e) {
        throw new GetImageException("Could not parse URL: " + e.getMessage());
    }
    Log.d(TAG, "Getting image with URL: " + url.toString());

    //Open connection
    URLConnection ucon;
    try {
        ucon = url.openConnection();
    } catch (IOException e) {
        throw new GetImageException("Could not open URL-connection: " + e.getMessage());
    }

    //Get Image
    InputStream is;
    try {
        is = ucon.getInputStream();
    } catch (IOException e) {
        throw new GetImageException("Could not get InputStream: " + e.getMessage());
    }
    //Setup buffers
    BufferedInputStream bis = new BufferedInputStream(is, INPUT_BUFFER_SIZE);
    ByteArrayBuffer baf = new ByteArrayBuffer(INPUT_BUFFER_SIZE);

    //Put content into bytearray
    int current = 0;
    try {
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }
    } catch (IOException e) {
        throw new GetImageException("Could not read from BufferedInputStream(bis): " + e.getMessage());
    }

    return baf.toByteArray();
}

From source file:com.juick.android.WsClient.java

public void readLoop() {
    try {//from  w w w. j  a v a 2 s.c om
        int b;
        int byteCnt = 0;
        boolean bigPacket = false;
        int PacketLength = 0;
        ByteArrayBuffer buf = new ByteArrayBuffer(16);
        boolean flagInside = false;
        while (!terminated) {
            try {
                b = is.read();
                if (b == -1)
                    break;
                if (terminated)
                    break;
            } catch (SocketTimeoutException e) {
                if (beforePausedCounter-- < 0) {
                    sock.setSoTimeout(3 * 60 * 1000);
                }
                Log.w("UgnichWS", "inst=" + toString() + ": read sotimeout, terminated=" + terminated);
                continue;
            }

            if (flagInside) {
                byteCnt++;
                if (byteCnt == 1) {
                    if (b < 126) {
                        PacketLength = b + 1;
                        bigPacket = false;
                    } else {
                        bigPacket = true;
                    }
                } else {
                    if (byteCnt == 2 && bigPacket) {
                        PacketLength = b << 8;
                    }
                    if (byteCnt == 3 && bigPacket) {
                        PacketLength |= b;
                        PacketLength += 3;
                    }

                    if (byteCnt > 3 || !bigPacket) {
                        buf.append((char) b);
                    }
                }

                if (byteCnt == PacketLength && listener != null) {
                    if (PacketLength > 2) {
                        if (listener != null) {
                            String incomingData = new String(buf.toByteArray(), "utf-8");
                            final ArrayList<JuickMessage> messages = convertMessages(incomingData);
                            if (messages.size() > 0) {
                                listener.onNewMessages(messages);
                            }
                        }
                    } else {
                        os.write(keepAlive);
                        os.flush();
                    }
                    flagInside = false;
                }
            } else if (b == 0x81) {
                buf.clear();
                flagInside = true;
                byteCnt = 0;
            }
        }
    } catch (Exception e) {
        Log.e("UgnichWS", "inst=" + toString(), e);

    } finally {
        Log.w("UgnichWS", "inst=" + toString() + " DISCONNECTED readLoop");
    }
}

From source file:com.racoon.ampdroid.Mp3PlayerService.java

public void DownloadFromUrl(String DownloadURL, String LocalFileName, String User, String Password) {
    try {/* w w w  .  j av a2s  .c o m*/
        URL url = new URL(DownloadURL);
        File file = new File(LocalFileName);

        long startTime = System.currentTimeMillis();
        //Log.d("bugs", "download begining");
        //Log.d("bugs", "download url:" + url);
        //Log.d("bugs", "download to file:" + fileName);

        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        String credentials = User + ":" + Password;
        credentials = Base64.encodeToString(credentials.getBytes(), Base64.DEFAULT);
        con.setRequestMethod("POST");
        con.setDoOutput(true);
        con.setRequestProperty("Authorization", "Basic " + credentials);
        con.connect();

        InputStream is = con.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);

        //Read bytes to the Buffer until there is nothing more to read(-1).
        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }

        //Convert the Bytes read to a String.
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(baf.toByteArray());
        fos.close();
        Log.d("bugs", "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");

        con.disconnect();

    } catch (IOException e) {
        Log.d("bugs", "Error: " + e);
    }

}