byte[] getResponseData(HttpEntity entity) throws IOException {
   byte[] responseBody = null;
   if (entity != null) {
     InputStream instream = entity.getContent();
     if (instream != null) {
       long contentLength = entity.getContentLength();
       if (contentLength > Integer.MAX_VALUE) {
         throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
       }
       if (contentLength < 0) {
         contentLength = BUFFER_SIZE;
       }
       try {
         ByteArrayBuffer buffer = new ByteArrayBuffer((int) contentLength);
         try {
           byte[] tmp = new byte[BUFFER_SIZE];
           int l, count = 0;
           // do not send messages if request has been cancelled
           while ((l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) {
             count += l;
             buffer.append(tmp, 0, l);
             sendProgressMessage(count, (int) contentLength);
           }
         } finally {
           instream.close();
         }
         responseBody = buffer.toByteArray();
       } catch (OutOfMemoryError e) {
         System.gc();
         throw new IOException("File too large to fit into available memory");
       }
     }
   }
   return responseBody;
 }
 public static byte[] httpEntityToByteArray(final HttpEntity entity) throws IOException {
   if (entity == null) {
     throw new IllegalArgumentException("HTTP entity may not be null");
   }
   InputStream instream = entity.getContent();
   if (instream == null) {
     return new byte[] {};
   }
   if (entity.getContentLength() > Integer.MAX_VALUE) {
     throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
   }
   int i = (int) entity.getContentLength();
   if (i < 0) {
     i = 4096;
   }
   ByteArrayBuffer buffer = new ByteArrayBuffer(i);
   try {
     byte[] tmp = new byte[4096];
     int l;
     while ((l = instream.read(tmp)) != -1) {
       if (Thread.interrupted())
         throw new InterruptedIOException("File download process was canceled");
       buffer.append(tmp, 0, l);
     }
   } finally {
     instream.close();
   }
   return buffer.toByteArray();
 }
  public static String makeCall(String url) {

    // string buffers the url
    StringBuffer buffer_string = new StringBuffer(url);
    String replyString = "";

    // instanciate an HttpClient
    HttpClient httpclient = new DefaultHttpClient();
    // instanciate an HttpGet
    HttpGet httpget = new HttpGet(buffer_string.toString());

    try {
      // get the responce of the httpclient execution of the url
      HttpResponse response = httpclient.execute(httpget);
      InputStream is = response.getEntity().getContent();

      // buffer input stream the result
      BufferedInputStream bis = new BufferedInputStream(is);
      ByteArrayBuffer baf = new ByteArrayBuffer(20);
      int current = 0;
      while ((current = bis.read()) != -1) {
        baf.append((byte) current);
      }
      // the result as a string is ready for parsing
      replyString = new String(baf.toByteArray());
    } catch (Exception e) {
      e.printStackTrace();
    }
    // trim the whitespaces
    return replyString.trim();
  }
Example #4
0
 private static final byte[] toByteArray(
     final HttpEntity entity, int maxContent, MutableBoolean trimmed) throws IOException {
   Args.notNull(entity, "Entity");
   final InputStream instream = entity.getContent();
   if (instream == null) {
     return null;
   }
   try {
     Args.check(
         entity.getContentLength() <= Integer.MAX_VALUE,
         "HTTP entity too large to be buffered in memory");
     int i = (int) entity.getContentLength();
     if (i < 0) {
       i = 4096;
     }
     final ByteArrayBuffer buffer = new ByteArrayBuffer(i);
     final byte[] tmp = new byte[4096];
     int l;
     int total = 0;
     while ((l = instream.read(tmp)) != -1) {
       // check whether we need to trim
       if (maxContent != -1 && total + l > maxContent) {
         buffer.append(tmp, 0, maxContent - total);
         trimmed.setValue(true);
         break;
       }
       buffer.append(tmp, 0, l);
       total += l;
     }
     return buffer.toByteArray();
   } finally {
     instream.close();
   }
 }
    private Bitmap DownloadImage(URL url, String fileSavePath) {

      Bitmap bmImg = null;
      try {
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);
        conn.connect();
        InputStream is = conn.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);
        }

        FileOutputStream fos = new FileOutputStream(fileSavePath);
        fos.write(baf.toByteArray());
        fos.close();
        bmImg = BitmapFactory.decodeStream(is);
        //	    int nh = (int) ( bmImg.getHeight() * (512.0 / bmImg.getWidth()) );
        //		 bmImg = Bitmap.createScaledBitmap(bmImg, 512, nh, true);

      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
      }

      return bmImg;
    }
Example #6
0
  public String postData(String conexion, List nameValuePairs) {
    // Create a new HttpClient and Post Header
    String cadena = "";
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(conexion);

    try {
      // Add your data
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

      // 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. */
      cadena = new String(baf.toByteArray());
      httpclient.getConnectionManager().shutdown();
    } catch (ClientProtocolException e) {
      // TODO Auto-generated catch block
      cadena = "error";
    } catch (IOException e) {
      // TODO Auto-generated catch block
      cadena = "error";
    }

    return cadena;
  }
    @Override
    protected String doInBackground(String... sUrl) {
      HttpURLConnection requestection = null;
      FileOutputStream fos = null;
      File file = new File(fileName);
      try {
        requestection = (HttpURLConnection) url.openConnection();
        requestection.connect();
        InputStream is = requestection.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(1024);
        int current = 0;
        while ((current = bis.read()) != -1) {
          baf.append((byte) current);
        }
        fos = new FileOutputStream(file);
        fos.write(baf.toByteArray());
      } catch (IOException e) {

        Log.d(
            "Exception ",
            "Message :" + e.getMessage() + "\n StackTrace: " + Log.getStackTraceString(e));
      } finally {
        try {
          fos.close();
        } catch (IOException e) {

          Log.d(
              "Exception ",
              "Message :" + e.getMessage() + "\n StackTrace: " + Log.getStackTraceString(e));
        }
      }

      return null;
    }
  public long httpDownload(String strUrl, String path) {
    int length = 0;

    try {
      URL url = new URL(strUrl);
      File file = new File(path);

      URLConnection ucon = url.openConnection();
      InputStream is = ucon.getInputStream();
      BufferedInputStream bis = new BufferedInputStream(is);
      ByteArrayBuffer baf = new ByteArrayBuffer(50);
      int current = 0;
      while ((current = bis.read()) != -1) {
        baf.append((byte) current);
        length++;
      }

      FileOutputStream fos = new FileOutputStream(file);
      fos.write(baf.toByteArray());
      fos.close();

    } catch (Exception e) {
      Log.d(MyApp.TAG, e.getMessage().toString());
    }

    Log.d(MyApp.TAG, "Downloaded " + length + " bytes");
    return length;
  }
  @Override
  protected String doInBackground(String... arg0) {

    File dir = new File(this.dirName);
    if (dir.isDirectory()) {
      String[] children = dir.list();
      for (int i = 0; i < children.length; i++) {
        new File(dir, children[i]).delete();
      }
    }

    String urlAdress = this.pathName;
    String jString = null;
    try {

      File root = new File("/sdcard/Vatan");
      root.mkdir();
      File directory = new File(this.dirName);
      directory.mkdir();
      URL url;
      url = new URL(urlAdress);
      URLConnection ucon = url.openConnection();
      InputStream is = ucon.getInputStream();
      BufferedInputStream bis = new BufferedInputStream(is);
      ByteArrayBuffer baf = new ByteArrayBuffer(50);
      int current = 0;
      while ((current = bis.read()) != -1) {
        baf.append((byte) current);
      }
      jString = new String(baf.toByteArray());

      Gson gson = new Gson();
      SearchResponse response = gson.fromJson(jString, SearchResponse.class);
      List<Result> results = response.root;

      String[] urlAdress1 = null;
      for (Result result : results) {
        // values[0][0][0]=result.ImageURL;
        if (!result.ImageURL.equals("")) {
          urlAdress1 = result.ImageURL.split("/");
          Global.DownloadFile(
              Global.resizeImageURL(result.ImageURL, "133", "0"),
              urlAdress1[urlAdress1.length - 1],
              this.dirName);
        }
      }

      return jString;
    } catch (MalformedURLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return "hata1";
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      return "hata1";
    }
  }
 private void trimBuffer() {
   int bufLen = buffer.length();
   int boundaryLen = getBoundary().length;
   if (bufLen > boundaryLen) {
     // Leave enough bytes in _buffer that we can find an incomplete boundary string
     delegate.appendToPart(buffer.buffer(), 0, bufLen - boundaryLen);
     deleteUpThrough(bufLen - boundaryLen);
   }
 }
Example #11
0
  private String storeImage(String imageUrl, String fileName) {
    Log.d("HIP-URL", "The image url is " + imageUrl);
    try {

      File dir =
          new File(
              android.os.Environment.getExternalStorageDirectory().getAbsolutePath()
                  + "/hipstacast/img");
      if (dir.exists() == false) {
        dir.mkdirs();
      }

      URL url = new URL(imageUrl); // you can write here any link
      File file = new File(dir, fileName);

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

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

      /*
       * Define InputStreams to read from the URLConnection.
       */
      InputStream is = ucon.getInputStream();
      BufferedInputStream bis = new BufferedInputStream(is);

      /*
       * 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);
      }

      /* Convert the Bytes read to a String. */
      FileOutputStream fos = new FileOutputStream(file);
      fos.write(baf.toByteArray());
      fos.flush();
      fos.close();
      bis.close();

      Log.d(
          "DownloadManager",
          "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
      Log.d("HIP-DW", file.getAbsolutePath());
      return file.getAbsolutePath();

    } catch (IOException e) {
      Log.d("DownloadManager", "Error: " + e);
      Log.d("HIP-URL-IMG", imageUrl);
      return "";
    }
  }
 public Range searchFor(byte[] pattern, int start) {
   KMPMatch searcher = new KMPMatch();
   int buffLen = Math.min(buffer.length(), buffer.buffer().length);
   int matchIndex = searcher.indexOf(buffer.buffer(), buffLen, pattern, start);
   if (matchIndex != -1) {
     return new Range(matchIndex, pattern.length);
   } else {
     return new Range(matchIndex, 0);
   }
 }
Example #13
0
  /**
   * This method is Safe replica version of org.apache.http.util.EntityUtils.toByteArray. The try
   * block embedding 'instream.read' has a corresponding catch block for 'EOFException' (that's
   * Ignored) and all other IOExceptions are let pass.
   *
   * @param entity
   * @return byte array containing the entity content. May be empty/null.
   * @throws IOException if an error occurs reading the input stream
   */
  public byte[] toByteArraySafe(final HttpEntity entity) throws IOException {
    if (entity == null) {
      return null;
    }

    InputStream instream = entity.getContent();
    if (instream == null) {
      return new byte[] {};
    }
    Preconditions.checkArgument(
        entity.getContentLength() < Integer.MAX_VALUE,
        "HTTP entity too large to be buffered in memory");

    // The raw data stream (inside JDK) is read in a buffer of size '512'. The original code
    // org.apache.http.util.EntityUtils.toByteArray reads the unzipped data in a buffer of
    // 4096 byte. For any data stream that has a compression ratio lesser than 1/8, this may
    // result in the buffer/array overflow. Increasing the buffer size to '16384'. It's highly
    // unlikely to get data compression ratios lesser than 1/32 (3%).
    final int bufferLength = 16384;
    int i = (int) entity.getContentLength();
    if (i < 0) {
      i = bufferLength;
    }
    ByteArrayBuffer buffer = new ByteArrayBuffer(i);
    try {
      byte[] tmp = new byte[bufferLength];
      int l;
      while ((l = instream.read(tmp)) != -1) {
        buffer.append(tmp, 0, l);
      }
    } catch (EOFException eofe) {
      /**
       * Ref: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4040920 Due to a bug in JDK ZLIB
       * (InflaterInputStream), unexpected EOF error can occur. In such cases, even if the input
       * stream is finished reading, the 'Inflater.finished()' call erroneously returns 'false' and
       * 'java.util.zip.InflaterInputStream.fill' throws the 'EOFException'. So for such case,
       * ignore the Exception in case Exception Cause is 'Unexpected end of ZLIB input stream'.
       *
       * <p>Also, ignore this exception in case the exception has no message body as this is the
       * case where {@link GZIPInputStream#readUByte} throws EOFException with empty message. A bug
       * has been filed with Sun and will be mentioned here once it is accepted.
       */
      if (instream.available() == 0
          && (eofe.getMessage() == null
              || eofe.getMessage().equals("Unexpected end of ZLIB input stream"))) {
        LOG.log(Level.FINE, "EOFException: ", eofe);
      } else {
        throw eofe;
      }
    } finally {
      instream.close();
    }
    return buffer.toByteArray();
  }
  public static String getImage(String imageLink) {

    if (!imageLink.equals(""))
      try {
        String urlBase =
            Constants.ROOT_SCHOOLAPP_URL + "img/" + Constants.ACTIVE_ID + "/" + imageLink;

        URL url = new URL(urlBase);

        long startTime = System.currentTimeMillis();
        Log.d("ImageManager", "download begining");
        Log.d("ImageManager", "download url:" + url);
        /* Open a connection to that URL. */
        URLConnection ucon = url.openConnection();

        /*
         * Define InputStreams to read from the URLConnection.
         */
        InputStream is = ucon.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);
        }

        File file = new File("");

        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
          File sdCard = Environment.getExternalStorageDirectory();
          File dir = new File(sdCard.getAbsolutePath() + "/com.optimo.quakertown/images/");
          Log.d("Make dir?:", "" + dir.mkdirs());
          file = new File(dir, imageLink);
          FileOutputStream f = new FileOutputStream(file);
          f.write(baf.toByteArray());
          f.close();
        } else {
          return "Need SD-Card for images";
        }

        Log.d(
            "ImageManager",
            "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");

      } catch (IOException e) {
        Log.d("ImageManager", "Error: " + e);
        return "ERROR";
      }
    return "OK";
  }
  public static void downloadDB(String urlString) {
    try {
      rootDir =
          Environment.getExternalStorageDirectory().getAbsolutePath() + "/Your Language Friend";

      String fileDir = rootDir;
      File fd = new File(fileDir);
      if (!fd.exists()) {
        fd.mkdir();
      }

      URL url = new URL(urlString);
      // String fileName = urlString.substring(urlString.lastIndexOf('/')+1,
      // urlString.lastIndexOf('.')) + ".db";
      String fileName = "test.db";
      File file = new File(fileDir + "/" + fileName);

      // Log.d("open connection", "before connect ");
      URLConnection ucon = url.openConnection();
      // Log.d("open connection", "after connect");

      //            URL url = new URL(urlString);
      //            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
      //
      //            urlConnection.setRequestMethod("GET");
      //            urlConnection.setDoOutput(true);
      //
      //            //connect
      //            urlConnection.connect();

      InputStream is = ucon.getInputStream();
      // Log.d("open connection", "after get inputstream");
      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);
      }

      FileOutputStream fos = new FileOutputStream(file);
      fos.write(baf.toByteArray());
      fos.close();

    } catch (IOException e) {
      Log.d("download exception", e.toString());
    }
  }
Example #16
0
  @Override
  protected Integer doInBackground(TsumegoSource... params) {

    int download_count = 0;
    for (TsumegoSource src : params) {

      boolean finished = false;
      int pos = 10;

      while (!finished) {

        while (new File(src.local_path + src.getFnameByPos(pos)).exists()) {
          this.publishProgress("Processing " + src.getFnameByPos(pos));
          pos++;
        }

        if (pos >= LIMITER) {
          finished = true;
        } else
          try {
            // new File().exists()
            URL url = new URL(src.remote_path + src.getFnameByPos(pos));
            URLConnection ucon = url.openConnection();
            BufferedInputStream bis = new BufferedInputStream(ucon.getInputStream());

            ByteArrayBuffer baf = new ByteArrayBuffer(50);
            int current = 0;
            while ((current = bis.read()) != -1) baf.append((byte) current);

            FileOutputStream fos =
                new FileOutputStream(new File(src.local_path + src.getFnameByPos(pos)));
            fos.write(baf.toByteArray());
            fos.close();

            download_count++;

          } catch (Exception e) {
            Log.i("", e);
            finished = true;
          }
      }

      try {
        Thread.sleep(199);
      } catch (InterruptedException e) {
      }
    }
    return download_count;
  }
  private void deleteUpThrough(int location) {
    // int start = location + 1;  // start at the first byte after the location

    if (location <= 0) return;

    byte[] b = buffer.buffer();
    int len = buffer.length();

    int j = 0;
    int i = location;
    while (i < len) {
      b[j++] = b[i++];
    }
    buffer.setLength(j);
  }
Example #18
0
  public void DownloadFromUrl(String DownloadUrl, String fileName) {

    try {
      File root = android.os.Environment.getExternalStorageDirectory();

      File dir = new File(root.getAbsolutePath() + "/" + Imageurl.facebookpage);
      if (dir.exists() == false) {
        dir.mkdirs();
      }

      URL url = new URL(DownloadUrl); // you can write here any link
      File file = new File(dir, fileName);

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

      /*
       * Define InputStreams to read from the URLConnection.
       */
      InputStream is = ucon.getInputStream();
      BufferedInputStream bis = new BufferedInputStream(is);

      /*
       * 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);
      }

      /* Convert the Bytes read to a String. */
      FileOutputStream fos = new FileOutputStream(file);
      fos.write(baf.toByteArray());
      fos.flush();
      fos.close();
      LoginActivity.statsofdownload++;

      Log.d("DownloadManager", "file://" + file.getAbsolutePath());

    } catch (IOException e) {
      Imageurl.pagestat = "space";
      Log.d("DownloadManager", "Error: " + e);
    }
  }
  private String downloadFile(String urlFont) {
    String path = Environment.getExternalStorageDirectory() + "/cloud4AllFont/";
    String fileName = "newType.ttf";
    try {
      URL url = new URL(urlFont);
      File myDir = new File(path);
      myDir.mkdir();
      File file = new File(path, fileName);
      Log.d("PREFERENCES", "Run hilo");
      Log.i("PREFERENCES", "filename:" + fileName);

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

      /*
       * Define InputStreams to read from the URLConnection.
       */
      InputStream is = ucon.getInputStream();
      BufferedInputStream bis = new BufferedInputStream(is);

      /*
       * 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);
      }

      /* Convert the Bytes read to a String. */
      file.createNewFile();
      FileOutputStream fos = new FileOutputStream(file);
      fos.write(baf.toByteArray());
      fos.close();
      String down = file.toURI().toString();
      Log.d("PREFERENCES", "Descargado fichero en " + down.substring(5));

      return down.substring(5);

    } catch (Exception e) {

      e.printStackTrace();
    }
    return null;
  }
Example #20
0
  public static byte[] hexToBytes(String hex) {
    ByteArrayBuffer bytes = new ByteArrayBuffer(hex.length() / 2);
    for (int i = 0; i < hex.length(); i++) {
      if (hex.charAt(i) == ' ') {
        continue;
      }

      String hexByte;
      if (i + 1 < hex.length()) {
        hexByte = hex.substring(i, i + 2).trim();
        i++;
      } else {
        hexByte = hex.substring(i, i + 1);
      }

      bytes.append(Integer.parseInt(hexByte, 16));
    }
    return bytes.buffer();
  }
Example #21
0
 public static String post(String url, Map<String, String> requestParameters) {
   HttpURLConnection connection = null;
   InputStream is = null;
   BufferedInputStream bis = null;
   try {
     byte[] parametersUrlByte = initRequestParameters(requestParameters);
     URL requestUrl = new URL(url);
     connection = (HttpURLConnection) requestUrl.openConnection();
     connection.setRequestMethod("POST");
     connection.setConnectTimeout(CONNECTION_TIMEOUT);
     connection.setReadTimeout(READ_TIMEOUT);
     connection.setDoOutput(true);
     connection.getOutputStream().write(parametersUrlByte, 0, parametersUrlByte.length);
     connection.getOutputStream().flush();
     connection.getOutputStream().close();
     is = connection.getInputStream();
     bis = new BufferedInputStream(is);
     ByteArrayBuffer bab = new ByteArrayBuffer(32);
     int current = 0;
     while ((current = bis.read()) != -1) {
       bab.append((byte) current);
     }
     return EncodingUtils.getString(bab.toByteArray(), HTTP.UTF_8);
   } catch (Exception e) {
     LOGGER.error(e);
     return null;
   } finally {
     try {
       if (bis != null) {
         bis.close();
       }
       if (is != null) {
         is.close();
       }
     } catch (IOException e) {
       LOGGER.error(e);
     }
     if (connection != null) {
       connection.disconnect();
     }
   }
 }
  byte[] getResponseData(HttpEntity entity) throws IOException {
    byte[] responseBody = null;
    if (entity != null) {
      InputStream instream = entity.getContent();
      if (instream != null) {
        long contentLength = entity.getContentLength();
        if (contentLength > 2147483647L) {
          throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
        }

        if (contentLength < 0L) {
          contentLength = 4096L;
        }

        try {
          ByteArrayBuffer e = new ByteArrayBuffer((int) contentLength);

          try {
            byte[] tmp = new byte[4096];
            byte count = 0;

            int l;
            while ((l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) {
              e.append(tmp, 0, l);
              this.sendProgressDataMessage(copyOfRange(tmp, 0, l));
              this.sendProgressMessage((long) count, contentLength);
            }
          } finally {
            AsyncHttpClient.silentCloseInputStream(instream);
          }

          responseBody = e.toByteArray();
        } catch (OutOfMemoryError var14) {
          System.gc();
          throw new IOException("File too large to fit into available memory");
        }
      }
    }

    return responseBody;
  }
 private Bitmap downloadBitmap(String url) {
   Bitmap ret = null;
   InputStream s = null;
   try {
     if (url.startsWith("/")) {
       ret = MediaUtils.readFileBitmap(url, true);
       if (ret != null) return ret;
     }
     Logger.LogDebug("Trying to download " + url);
     HttpURLConnection uc = (HttpURLConnection) new URL(url).openConnection();
     uc.setConnectTimeout(15000);
     uc.connect();
     publishProgress(0);
     if (uc.getResponseCode() >= 400) throw new IOException(uc.getResponseCode() + " on " + url);
     Integer length = uc.getContentLength();
     Logger.LogInfo("Response received. " + length + " bytes.");
     publishProgress(-2);
     s = new BufferedInputStream(uc.getInputStream(), WallChanger.DOWNLOAD_CHUNK_SIZE);
     ByteArrayBuffer bab = new ByteArrayBuffer(length <= 0 ? 32 : length);
     byte[] b = new byte[WallChanger.DOWNLOAD_CHUNK_SIZE];
     int read = 0;
     int position = 0;
     while ((read = s.read(b, 0, WallChanger.DOWNLOAD_CHUNK_SIZE)) > 0) {
       position += read;
       bab.append(b, 0, read);
       publishProgress(position, length > position ? length : position + s.available());
     }
     b = bab.toByteArray();
     MediaUtils.writeFile(url.substring(url.lastIndexOf("/") + 1), b, true);
     ret = BitmapFactory.decodeByteArray(b, 0, b.length);
   } catch (IOException ex) {
     Logger.LogError("Couldn't download base image. " + url, ex);
   } finally {
     try {
       if (s != null) s.close();
     } catch (IOException ex) {
       Logger.LogError("Error closing stream while downloading base image.", ex);
     }
   }
   return ret;
 }
Example #24
0
  /**
   * Add a proto location object to the hash
   *
   * @param md
   * @param loc
   */
  @SuppressWarnings("unused")
  private static void updateLocationDigest(MessageDigest md, Location loc) {
    ByteArrayBuffer bab = new ByteArrayBuffer(100);

    bab.append((int) (loc.getAccuracy() * 1000000));
    bab.append((int) (loc.getAltitude() * 1000000));
    bab.append((int) (loc.getBearing() * 1000000));
    bab.append((int) (loc.getLatitude() * 1000000));
    bab.append((int) (loc.getLongitude() * 1000000));
    bab.append((int) (loc.getSpeed() * 1000000));
    bab.append((int) loc.getTime());

    byte[] providerBytes = loc.getProvider().getBytes();
    bab.append(providerBytes, 0, providerBytes.length);

    md.update(bab.buffer());
  }
Example #25
0
  public static void downloadPhoto(String img_url) {
    downloadImageSuccess = false;
    // This is for downloading venue photos in the venue list view
    try {
      if ("-".equals(img_url)) {
        return;
      }
      URL url = new URL(img_url);
      File cacheDir = new File(AppConstants.CACHED_IMGS_DIR);
      // create directory for cached images if it doesn't exist
      if (!cacheDir.exists()) {
        cacheDir.mkdir();
        Log.d(
            "Cache directory doest exist ",
            " create directory for cached images if it doesn't exist");
      }

      File file = new File(AppConstants.CACHED_IMGS_DIR + getBaseFilename(url.toString()));
      URLConnection ucon = url.openConnection();
      ucon.setReadTimeout(30000);
      ucon.setConnectTimeout(30000);
      ucon.setUseCaches(true);
      InputStream is = ucon.getInputStream();
      BufferedInputStream bis = new BufferedInputStream(is);

      ByteArrayBuffer baf = new ByteArrayBuffer(50);
      int current = 0;
      while ((current = bis.read()) != -1) {
        baf.append((byte) current);
      }

      FileOutputStream fos = new FileOutputStream(file);
      fos.write(baf.toByteArray());
      fos.close();
      downloadImageSuccess = true;
      Log.d("Image Manager", file.getPath() + " cached");
    } catch (IOException | NetworkOnMainThreadException e) {
      Log.d("ImageManager", "Error: " + e);
    }
  }
Example #26
0
  @Override
  protected byte[] doInBackground(String... urls) {
    // do above Server call here
    try {
      // convert URL to URL object
      URL imageUrl = new URL(urls[0]);
      // open connection
      // Log.i(TAG, "Get URL" + urls[0]);
      URLConnection ucon = imageUrl.openConnection();
      // get input stream from URL
      // Log.i(TAG, "Open connection" + ucon.getContent());
      InputStream is = ucon.getInputStream();
      // Log.i(TAG, "is" + is.toString());
      // create buffer input stream
      BufferedInputStream bis = new BufferedInputStream(is);
      // Log.i(TAG, "bis" + bis.toString());
      // create buffer array
      ByteArrayBuffer baf = new ByteArrayBuffer(500);
      // Log.i(TAG, "baf" + baf.toString());
      // initiate current
      int current = 0;
      // set current to current input stream
      while ((current = bis.read()) != -1) {
        // build the array with those values
        // type cast to byte
        baf.append((byte) current);
      }

      String result = baf.toByteArray().toString();
      if (result.equals("None")) {
        Log.i(TAG, "equals None");
      }
      // return the image as a byteArray
      return baf.toByteArray();

    } catch (Exception e) {
      Log.d(TAG, "Download image error: " + e.toString());
    }
    return null;
  }
Example #27
0
 @Override
 public void onSuccess(ByteArrayBuffer baf) {
   try {
     String jsonString = EncodingUtils.getString(baf.toByteArray(), "utf8");
     Log.d("URLHelper", "JSON response = " + jsonString);
     JSONObject obj = null;
     if (!jsonString.equals("") && !jsonString.equals("[]")) obj = new JSONObject(jsonString);
     mDelegate.updateModelWithJSONObject(obj, this.serviceId);
   } catch (Exception e) {
     e.printStackTrace();
     mDelegate.connectionFailed(this.serviceId);
   }
 }
 private boolean sendSavePasswordRequest() {
   message = null;
   boolean isSuccessful = false;
   try {
     String urlParams = setupAndCheckParams();
     if (message == null) {
       URL url = new URL(CCWChinaConst.WEBSITE_CONTEXT + "/mobile/edit-password.htm?" + urlParams);
       InputStream inputStream = url.openStream();
       ByteArrayBuffer baf = new ByteArrayBuffer(50);
       int current = 0;
       while ((current = inputStream.read()) != -1) {
         baf.append((byte) current);
       }
       String xml = EncodingUtils.getString(baf.toByteArray(), "UTF-8");
       isSuccessful = parseSavePasswordXMl(xml);
     }
   } catch (Exception e) {
     e.printStackTrace();
     message = CCWChinaConst.APP_ERROR_MSG;
   }
   return isSuccessful;
 }
Example #29
0
 public static String get(String url, String contentType) {
   HttpURLConnection connection = null;
   InputStream is = null;
   BufferedInputStream bis = null;
   try {
     URL requestUrl = new URL(url);
     connection = (HttpURLConnection) requestUrl.openConnection();
     if (contentType != null) {
       connection.setRequestProperty("Content-type", contentType);
     }
     connection.setConnectTimeout(CONNECTION_TIMEOUT);
     connection.setReadTimeout(READ_TIMEOUT);
     is = connection.getInputStream();
     bis = new BufferedInputStream(is);
     ByteArrayBuffer bab = new ByteArrayBuffer(32);
     int current = 0;
     while ((current = bis.read()) != -1) {
       bab.append((byte) current);
     }
     return EncodingUtils.getString(bab.toByteArray(), HTTP.UTF_8);
   } catch (Exception e) {
     LOGGER.error(e);
     return null;
   } finally {
     try {
       if (bis != null) {
         bis.close();
       }
       if (is != null) {
         is.close();
       }
     } catch (IOException e) {
       LOGGER.error(e);
     }
     if (connection != null) {
       connection.disconnect();
     }
   }
 }
    public void download() {
      HttpURLConnection requestection = null;

      File file = new File(fileName);
      try {
        requestection = (HttpURLConnection) url.openConnection();
        requestection.setRequestProperty("method", "GET");

        if (this.isCancelled()) {
          requestection.setRequestProperty(
              "Range", "bytes=" + requestection.getInputStream().available() + "-" + data);
        }
        requestection.connect();
        InputStream is = requestection.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(1024);
        int current = 0;
        while ((current = bis.read()) != -1) {
          baf.append((byte) current);
        }
        fos = new FileOutputStream(file);
        fos.write(baf.toByteArray());

      } catch (IOException e) {

        Log.d(
            "Exception ",
            "Message :" + e.getMessage() + "\n StackTrace: " + Log.getStackTraceString(e));
      } finally {
        try {
          fos.close();
        } catch (IOException e) {

          Log.d(
              "Exception ",
              "Message :" + e.getMessage() + "\n StackTrace: " + Log.getStackTraceString(e));
        }
      }
    }