public String waitForPassword(int timeout, String username) throws TimeoutException {
    while (!initiated) {
      try {
        Thread.sleep(100);
      } catch (InterruptedException ex) {
      }
    }

    String password = "";
    try {
      // send a message to the robot
      String response = robotSocketServer.sendMessageAndWaitForResponse("waitForPassword");
      if (!response.startsWith("password is ")) {
        System.err.println(
            "waitForPassword RECEIVED MESSAGE DIFFERENT THAN \"password is ...\": " + response);
        System.exit(1);
      }
      password = response.substring(12, response.length());
      System.out.println("Received: " + response + "   Password is " + password);
    } catch (SocketTimeoutException ex) {
      System.err.println("waitForPassword EXCEPTION!");
      ex.printStackTrace();
      System.exit(1);
    }
    return password;
  }
예제 #2
0
 public void receivePacket() {
   int buffLength = 256;
   byte[] buff = new byte[buffLength];
   DatagramPacket packet = new DatagramPacket(buff, buffLength);
   try {
     socket.receive(packet);
     String message = new String(packet.getData(), 0, packet.getLength() - 2);
     System.out.println("receive message : " + message);
     if (message.indexOf(":") == -1) {
       return;
     }
     String[] fields = message.split(":");
     long commandField = Long.parseLong(fields[4]);
     if ((commandField & IPMSG_ANSENTRY) != 0) {
       this.receiveAnswerEntry(fields, packet);
     } else if ((commandField & IPMSG_SENDMSG) != 0) {
       this.receiveMessage(fields, packet);
     }
   } catch (SocketTimeoutException ste) {
     ste.printStackTrace();
   } catch (PortUnreachableException pue) {
     pue.printStackTrace();
   } catch (IllegalBlockingModeException ibme) {
     ibme.printStackTrace();
   } catch (IOException ioe) {
     ioe.printStackTrace();
   }
 }
예제 #3
0
    @Override
    protected DanmuFileData doInBackground(Void... voids) {
      Boolean isSuccessed = false;

      try {
        isSuccessed = NetWorkUtils.downLoadDanmuFile(chatId);
      } catch (SocketTimeoutException e) {
        e.printStackTrace();
        return null;
      }
      L.e("网络请求成功" + isSuccessed);
      if (!isSuccessed) {
        return null;
      }

      File danmuFile = new File(Constant.DANMU_FILE_SAVE_PATH + chatId);
      if (!danmuFile.exists()) {
        return null;
      }
      L.e("文件解析成功");
      FileInputStream fileInputStream = null;
      try {
        fileInputStream = new FileInputStream(danmuFile);
      } catch (FileNotFoundException e) {
        e.printStackTrace();
        L.e("文件流读取失败");
        return null;
      }
      L.e("文件流读取成功");
      BiliDanmakuXMLParser biliDanmakuXMLParser =
          (BiliDanmakuXMLParser)
              DataUtils.parseXMLToDanmakuFile(fileInputStream, new BiliDanmakuXMLParser());
      return biliDanmakuXMLParser.getDanmakuFileData();
    }
예제 #4
0
 /**
  * 下载文件
  *
  * @param params 请求参数
  * @param filepath 保存路径
  */
 public static File downloadFile(RequestParams params, String filepath) throws TaskException {
   // 设置断点续传
   params.setAutoResume(true);
   params.setSaveFilePath(filepath);
   try {
     return x.http().getSync(params, File.class);
   } catch (SocketTimeoutException e) {
     e.printStackTrace();
     throw new TaskException(TaskException.TaskError.timeout.toString());
   } catch (ConnectTimeoutException e) {
     e.printStackTrace();
     throw new TaskException(TaskException.TaskError.timeout.toString());
   } catch (UnknownHostException e) {
     e.printStackTrace();
     throw new TaskException(TaskException.TaskError.timeout.toString());
   } catch (IOException e) {
     e.printStackTrace();
     throw new TaskException(TaskException.TaskError.timeout.toString());
   } catch (Throwable throwable) {
     TaskException taskException = null;
     if (throwable.getCause() instanceof TaskException) {
       taskException = (TaskException) throwable.getCause();
     } else if (throwable instanceof TaskException) {
       taskException = (TaskException) throwable;
     }
     if (taskException != null) {
       throw taskException;
     }
     throw new TaskException(
         "", TextUtils.isEmpty(throwable.getMessage()) ? "服务器错误" : throwable.getMessage());
   }
 }
예제 #5
0
 public static <T> T doPostSync(RequestParams params, Class<T> responseCls) throws TaskException {
   try {
     return x.http().postSync(params, responseCls);
   } catch (SocketTimeoutException e) {
     e.printStackTrace();
     throw new TaskException(TaskException.TaskError.timeout.toString());
   } catch (ConnectTimeoutException e) {
     e.printStackTrace();
     throw new TaskException(TaskException.TaskError.timeout.toString());
   } catch (UnknownHostException e) {
     e.printStackTrace();
     throw new TaskException(TaskException.TaskError.timeout.toString());
   } catch (IOException e) {
     e.printStackTrace();
     throw new TaskException(TaskException.TaskError.timeout.toString());
   } catch (Throwable throwable) {
     TaskException taskException = null;
     if (throwable.getCause() instanceof TaskException) {
       taskException = (TaskException) throwable.getCause();
     } else if (throwable instanceof TaskException) {
       taskException = (TaskException) throwable;
     }
     if (taskException != null) {
       throw taskException;
     }
     throw new TaskException(
         "", TextUtils.isEmpty(throwable.getMessage()) ? "服务器错误" : throwable.getMessage());
   }
 }
예제 #6
0
  public static byte[] post(String url, RequestEntity requestEntity) throws Exception {

    PostMethod method = new PostMethod(url);
    method.addRequestHeader("Connection", "Keep-Alive");
    method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
    method
        .getParams()
        .setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));
    method.setRequestEntity(requestEntity);
    method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    try {
      int statusCode = client.executeMethod(method);
      if (statusCode != HttpStatus.SC_OK) {
        System.err.println("httpCode=" + statusCode);
        return method.getResponseBody();
      }
      return method.getResponseBody();

    } catch (SocketTimeoutException e) {
      e.printStackTrace();
      return null;
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    } finally {
      method.releaseConnection();
    }
  }
    public void run() {
      // Counter to wait for timeout 5 times
      int counter = 5;

      while (running) {
        try {
          byte[] buf = new byte[32];
          packet = new DatagramPacket(buf, buf.length);
          socket.setSoTimeout(1000);

          // Wait for a message
          socket.receive(packet);

          // Clean the string (remove all the null characters)
          String message = new String(packet.getData());
          int endoftext = message.indexOf("\0");
          if (endoftext != -1) message = message.substring(0, endoftext);

          // If the message is different from the one sent
          if (!message.equals("requestIP")) {
            // Broadcast an intent with the message
            Intent answer = new Intent(Constants.UDP_ANSWER);
            answer.putExtra("message", message);
            sendBroadcast(answer);
          }
        } catch (SocketTimeoutException e) {
          // If the socket timed out, decrement the counter
          counter--;
          if (counter == 0) cancel();
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
예제 #8
0
    protected String doInBackground(String... params) {
      Log.i(TAG, "doInBackground");
      String respuesta = null;

      try {
        TelephonyManager telephonyManager =
            (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        String IMEI = telephonyManager.getDeviceId();
        String IMSI = telephonyManager.getSimSerialNumber();
        String consulta;
        if (phone.getText().toString().equals("2")) {
          consulta = URLs.RESOURCE;
        } else consulta = SoapRequestMovistar.getResource(IMEI, IMSI, phone.getText().toString());

        ArrayList<String> retorno = XMLParser.getReturnCode(consulta);

        code = Integer.valueOf(retorno.get(0));

        if (code == 0) {
          respuesta = consulta;
          Log.i(TAG, retorno.get(1));
        } else respuesta = retorno.get(1);
        return respuesta;

      } catch (HttpHostConnectException e2) {
        errorMessage = "Se agotó el tiempo de espera. Por favor reintente";
        return null;
      } catch (HttpResponseException e3) {
        e3.printStackTrace();
        errorMessage = "Se agotó el tiempo de espera. Por favor reintente";
        return null;
      } catch (ParseException p) {
        p.printStackTrace();
        errorMessage = "Error en la recepción de los datos. Por favor reintente";
        return null;
      } catch (SocketTimeoutException s1) {
        s1.printStackTrace();
        errorMessage = "Se agotó el tiempo de espera. Por favor reintente";
        return null;
      } catch (ConnectTimeoutException et) {
        et.printStackTrace();
        errorMessage = "Se agotó el tiempo de espera. Por favor reintente";
        return null;
      } catch (Exception e1) {
        e1.printStackTrace();
        errorMessage = "Ha ocurrido un error con la respuesta del servidor.";
        return null;
      }
    }
예제 #9
0
 public JSONArray getArray(String path, ArrayList<NameValuePair> params) {
   JSONArray res = new JSONArray();
   String paramString = URLEncodedUtils.format(params, "utf-8");
   HttpGet httpGet = new HttpGet(host + ":" + port + path + "?" + paramString);
   HttpResponse response;
   try {
     response = httpClient.execute(httpGet);
     res = new JSONArray(EntityUtils.toString(response.getEntity()));
   } catch (ConnectTimeoutException c) {
     c.printStackTrace();
   } catch (SocketTimeoutException s) {
     s.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } catch (JSONException e) {
     e.printStackTrace();
   }
   return res;
 }
예제 #10
0
 public JSONObject put(String path, ArrayList<NameValuePair> params) {
   JSONObject res = new JSONObject();
   HttpPut httpPut = new HttpPut(host + ":" + port + path);
   try {
     httpPut.setEntity(new UrlEncodedFormEntity(params));
     HttpResponse response;
     response = httpClient.execute(httpPut);
     res = new JSONObject(EntityUtils.toString(response.getEntity()));
   } catch (ConnectTimeoutException c) {
     c.printStackTrace();
   } catch (SocketTimeoutException s) {
     s.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } catch (JSONException e) {
     e.printStackTrace();
   }
   return res;
 }
  public void openTray(int trayNum) {
    while (!initiated) {
      try {
        Thread.sleep(100);
      } catch (InterruptedException ex) {
      }
    }

    try {
      // send a message to the robot
      String response = robotSocketServer.sendMessageAndWaitForResponse("openTray " + trayNum);
      if (!response.startsWith("closedTray")) {
        System.err.println("openTray RECEIVED MESSAGE DIFFERENT THAN \"closedTray\": " + response);
        System.exit(1);
      }
    } catch (SocketTimeoutException ex) {
      System.err.println("openTray EXCEPTION!");
      ex.printStackTrace();
      System.exit(1);
    }
  }
  public void ringBuzzer() {
    while (!initiated) {
      try {
        Thread.sleep(100);
      } catch (InterruptedException ex) {
      }
    }

    try {
      // send a message to the robot
      String response = robotSocketServer.sendMessageAndWaitForResponse("ringBuzzer");
      if (!response.equals("ringBuzzer done")) {
        System.err.println(
            "ringBuzzer RECEIVED MESSAGE DIFFERENT THAN \"ringBuzzer done\": " + response);
        System.exit(1);
      }
    } catch (SocketTimeoutException ex) {
      System.err.println("ringBuzzer EXCEPTION!");
      ex.printStackTrace();
      System.exit(1);
    }
  }
예제 #13
0
파일: ServerTest.java 프로젝트: suevip/moja
  public void run() {
    OutputStream out = null;
    InputStream in = null;
    try {
      client.setSoTimeout(4000);
      while (true) {
        out = client.getOutputStream();
        in = client.getInputStream();

        byte[] temp = SocketUtil.readBytesFromStream(in);

        if (null != temp && temp.length > 0) {
          String proTypeStr = new String(temp);
          System.out.println("接收到客户端消息" + proTypeStr + "当前服务器端口是" + port);

          out.write(("success" + port).getBytes());
        }
      }
    } catch (SocketTimeoutException e1) {
      e1.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        if (out != null) {
          out.close();
        }
        if (in != null) {
          in.close();
        }

        if (client != null) {
          client.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
예제 #14
0
  public void read(URL url) throws Exception {

    URLConnection connection = url.openConnection();
    if (connection instanceof HttpURLConnection) {
      HttpURLConnection hc = ((HttpURLConnection) connection);
      // hc.setConnectTimeout(1000);
      // hc.setReadTimeout(6000);
      try {
        BufferedReader in = new BufferedReader(new InputStreamReader(hc.getInputStream()));
        String input;
        StringBuffer response = new StringBuffer(256);

        while ((input = in.readLine()) != null) {
          response.append(input + "\r");
          System.out.println(input);
        }
      } catch (SocketTimeoutException x) {
        x.printStackTrace();
        System.out.println(x.getClass().getName());
      }
    }
  }
  public void moveRobotToNextPoint() {
    while (!initiated) {
      try {
        Thread.sleep(100);
      } catch (InterruptedException ex) {
      }
    }

    try {
      // send a message to the robot
      String response = robotSocketServer.sendMessageAndWaitForResponse("move robot to next point");
      if (!response.equals("next point found")) {
        System.err.println(
            "moveRobotToNextPoint RECEIVED MESSAGE DIFFERENT THAN \"next point found\": "
                + response);
        System.exit(1);
      }
      System.out.println("Robot arrived to the next point");
    } catch (SocketTimeoutException ex) {
      System.err.println("moveRobotToNextPoint EXCEPTION!");
      ex.printStackTrace();
      System.exit(1);
    }
  }
예제 #16
0
  public static String sendHttpPost(String URL, JSONObject jsonObjSend) {

    final int CONNECTION_TIMEOUT = 2000; // Connection Timeout
    InputStream instream = null;
    try {
      DefaultHttpClient httpclient = new DefaultHttpClient();

      HttpParams params = httpclient.getParams();
      HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
      HttpConnectionParams.setSoTimeout(params, CONNECTION_TIMEOUT);
      httpclient.setParams(params);

      HttpPost httpPostRequest = new HttpPost(URL);
      StringEntity se = new StringEntity(jsonObjSend.toString(), "UTF-8");

      httpPostRequest.setEntity(se);
      httpPostRequest.setHeader("Accept", "application/json");
      httpPostRequest.setHeader("Content-type", "application/json");
      httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set

      long t = System.currentTimeMillis();
      HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
      log.debug("HTTPResponse received in [" + (System.currentTimeMillis() - t) + "ms]");
      // Get hold of the response entity (-> the data):

      HttpEntity entity = response.getEntity();

      if (entity != null) {

        instream = entity.getContent();
        Header contentEncoding = response.getFirstHeader("Content-Encoding");

        if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
          instream = new GZIPInputStream(instream);
        }

        String resultString = convertStreamToString(instream);

        return resultString;
      }
    } catch (SocketTimeoutException ste) {
      ste.printStackTrace();
      return null;
    } catch (SocketException se) {
      se.printStackTrace();
      return null;
    } catch (IOException ie) {
      ie.printStackTrace();
      return null;
    } catch (Exception e) {
      log.error("", e);

    } finally {
      try {
        if (instream != null) {
          instream.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return null;
  }
  public boolean downloadFormAndSubmissionFiles(List<FormStatus> formsToTransfer) {
    boolean allSuccessful = true;

    // boolean error = false;
    int total = formsToTransfer.size();

    for (int i = 0; i < total; i++) {
      FormStatus fs = formsToTransfer.get(i);

      if (isCancelled()) {
        fs.setStatusString("aborted. Skipping fetch of form and submissions...", true);
        EventBus.publish(new FormStatusEvent(fs));
        return false;
      }

      RemoteFormDefinition fd = (RemoteFormDefinition) fs.getFormDefinition();
      fs.setStatusString("Fetching form definition", true);
      EventBus.publish(new FormStatusEvent(fs));
      try {

        File tmpdl = FileSystemUtils.getTempFormDefinitionFile();
        AggregateUtils.commonDownloadFile(serverInfo, tmpdl, fd.getDownloadUrl());

        fs.setStatusString("resolving against briefcase form definitions", true);
        EventBus.publish(new FormStatusEvent(fs));

        boolean successful = false;
        BriefcaseFormDefinition briefcaseLfd;
        DatabaseUtils formDatabase = null;
        try {
          try {
            briefcaseLfd = BriefcaseFormDefinition.resolveAgainstBriefcaseDefn(tmpdl);
            if (briefcaseLfd.needsMediaUpdate()) {

              if (fd.getManifestUrl() != null) {
                File mediaDir = FileSystemUtils.getMediaDirectory(briefcaseLfd.getFormDirectory());
                String error = downloadManifestAndMediaFiles(mediaDir, fs);
                if (error != null) {
                  allSuccessful = false;
                  fs.setStatusString("Error fetching form definition: " + error, false);
                  EventBus.publish(new FormStatusEvent(fs));
                  continue;
                }
              }
            }
            formDatabase =
                new DatabaseUtils(FileSystemUtils.getFormDatabase(briefcaseLfd.getFormDirectory()));

          } catch (BadFormDefinition e) {
            e.printStackTrace();
            allSuccessful = false;
            fs.setStatusString("Error parsing form definition: " + e.getMessage(), false);
            EventBus.publish(new FormStatusEvent(fs));
            continue;
          }

          fs.setStatusString("preparing to retrieve instance data", true);
          EventBus.publish(new FormStatusEvent(fs));

          File formInstancesDir =
              FileSystemUtils.getFormInstancesDirectory(briefcaseLfd.getFormDirectory());

          // this will publish events
          successful =
              downloadAllSubmissionsForForm(formInstancesDir, formDatabase, briefcaseLfd, fs);
        } catch (FileSystemException e) {
          e.printStackTrace();
          allSuccessful = false;
          fs.setStatusString("unable to open form database: " + e.getMessage(), false);
          EventBus.publish(new FormStatusEvent(fs));
          continue;
        } finally {
          if (formDatabase != null) {
            try {
              formDatabase.close();
            } catch (SQLException e) {
              e.printStackTrace();
              allSuccessful = false;
              fs.setStatusString("unable to close form database: " + e.getMessage(), false);
              EventBus.publish(new FormStatusEvent(fs));
              continue;
            }
          }
        }

        allSuccessful = allSuccessful && successful;

        // on success, we haven't actually set a success event (because we don't know we're done)
        if (successful) {
          fs.setStatusString("SUCCESS!", true);
          EventBus.publish(new FormStatusEvent(fs));
        } else {
          fs.setStatusString("FAILED.", true);
          EventBus.publish(new FormStatusEvent(fs));
        }

      } catch (SocketTimeoutException se) {
        se.printStackTrace();
        allSuccessful = false;
        fs.setStatusString(
            "Communications to the server timed out. Detailed message: "
                + se.getLocalizedMessage()
                + " while accessing: "
                + fd.getDownloadUrl()
                + " A network login screen may be interfering with the transmission to the server.",
            false);
        EventBus.publish(new FormStatusEvent(fs));
        continue;
      } catch (IOException e) {
        e.printStackTrace();
        allSuccessful = false;
        fs.setStatusString(
            "Unexpected error: "
                + e.getLocalizedMessage()
                + " while accessing: "
                + fd.getDownloadUrl()
                + " A network login screen may be interfering with the transmission to the server.",
            false);
        EventBus.publish(new FormStatusEvent(fs));
        continue;
      } catch (FileSystemException e) {
        e.printStackTrace();
        allSuccessful = false;
        fs.setStatusString(
            "Unexpected error: "
                + e.getLocalizedMessage()
                + " while accessing: "
                + fd.getDownloadUrl(),
            false);
        EventBus.publish(new FormStatusEvent(fs));
        continue;
      } catch (URISyntaxException e) {
        e.printStackTrace();
        allSuccessful = false;
        fs.setStatusString(
            "Unexpected error: "
                + e.getLocalizedMessage()
                + " while accessing: "
                + fd.getDownloadUrl(),
            false);
        EventBus.publish(new FormStatusEvent(fs));
        continue;
      } catch (TransmissionException e) {
        e.printStackTrace();
        allSuccessful = false;
        fs.setStatusString(
            "Unexpected error: "
                + e.getLocalizedMessage()
                + " while accessing: "
                + fd.getDownloadUrl(),
            false);
        EventBus.publish(new FormStatusEvent(fs));
        continue;
      }
    }
    return allSuccessful;
  }
예제 #18
0
  @Override
  protected void download() {
    File destination = new File(request.getDestination());
    final boolean fileExists = destination.exists();

    if (request.isDeleteOnFailure() && fileExists) {
      Log.w(TAG, "File already exists");
      if (request.getFeedfileType() != FeedImage.FEEDFILETYPE_FEEDIMAGE) {
        onFail(DownloadError.ERROR_FILE_EXISTS, null);
        return;
      } else {
        onSuccess();
        return;
      }
    }

    OkHttpClient httpClient = AntennapodHttpClient.getHttpClient();
    RandomAccessFile out = null;
    InputStream connection;
    ResponseBody responseBody = null;

    try {
      final URI uri = URIUtil.getURIFromRequestUrl(request.getSource());
      Request.Builder httpReq =
          new Request.Builder().url(uri.toURL()).header("User-Agent", ClientConfig.USER_AGENT);
      if (request.getIfModifiedSince() > 0) {
        long threeDaysAgo = System.currentTimeMillis() - 1000 * 60 * 60 * 24 * 3;
        if (request.getIfModifiedSince() > threeDaysAgo) {
          Date date = new Date(request.getIfModifiedSince());
          String httpDate = HttpDate.format(date);
          Log.d(TAG, "addHeader(\"If-Modified-Since\", \"" + httpDate + "\")");
          httpReq.addHeader("If-Modified-Since", httpDate);
        }
      }

      // add authentication information
      String userInfo = uri.getUserInfo();
      if (userInfo != null) {
        String[] parts = userInfo.split(":");
        if (parts.length == 2) {
          String credentials = encodeCredentials(parts[0], parts[1], "ISO-8859-1");
          httpReq.header("Authorization", credentials);
        }
      } else if (!StringUtils.isEmpty(request.getUsername()) && request.getPassword() != null) {
        String credentials =
            encodeCredentials(request.getUsername(), request.getPassword(), "ISO-8859-1");
        httpReq.header("Authorization", credentials);
      }

      // add range header if necessary
      if (fileExists) {
        request.setSoFar(destination.length());
        httpReq.addHeader("Range", "bytes=" + request.getSoFar() + "-");
        Log.d(TAG, "Adding range header: " + request.getSoFar());
      }

      Response response = null;
      try {
        response = httpClient.newCall(httpReq.build()).execute();
      } catch (IOException e) {
        Log.e(TAG, e.toString());
        if (e.getMessage().contains("PROTOCOL_ERROR")) {
          httpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1));
          response = httpClient.newCall(httpReq.build()).execute();
        } else {
          throw e;
        }
      }
      responseBody = response.body();
      String contentEncodingHeader = response.header("Content-Encoding");
      boolean isGzip = StringUtils.equalsIgnoreCase(contentEncodingHeader, "gzip");

      Log.d(TAG, "Response code is " + response.code());

      if (!response.isSuccessful() && response.code() == HttpURLConnection.HTTP_UNAUTHORIZED) {
        Log.d(TAG, "Authorization failed, re-trying with UTF-8 encoding");
        if (userInfo != null) {
          String[] parts = userInfo.split(":");
          if (parts.length == 2) {
            String credentials = encodeCredentials(parts[0], parts[1], "UTF-8");
            httpReq.header("Authorization", credentials);
          }
        } else if (!StringUtils.isEmpty(request.getUsername()) && request.getPassword() != null) {
          String credentials =
              encodeCredentials(request.getUsername(), request.getPassword(), "UTF-8");
          httpReq.header("Authorization", credentials);
        }
        response = httpClient.newCall(httpReq.build()).execute();
        responseBody = response.body();
        contentEncodingHeader = response.header("Content-Encoding");
        isGzip = StringUtils.equalsIgnoreCase(contentEncodingHeader, "gzip");
      }

      if (!response.isSuccessful() && response.code() == HttpURLConnection.HTTP_NOT_MODIFIED) {
        Log.d(
            TAG,
            "Feed '" + request.getSource() + "' not modified since last update, Download canceled");
        onCancelled();
        return;
      }

      if (!response.isSuccessful() || response.body() == null) {
        final DownloadError error;
        final String details;
        if (response.code() == HttpURLConnection.HTTP_UNAUTHORIZED) {
          error = DownloadError.ERROR_UNAUTHORIZED;
          details = String.valueOf(response.code());
        } else {
          error = DownloadError.ERROR_HTTP_DATA_ERROR;
          details = String.valueOf(response.code());
        }
        onFail(error, details);
        return;
      }

      if (!StorageUtils.storageAvailable(
          ClientConfig.applicationCallbacks.getApplicationInstance())) {
        onFail(DownloadError.ERROR_DEVICE_NOT_FOUND, null);
        return;
      }

      connection = new BufferedInputStream(responseBody.byteStream());

      String contentRangeHeader = (fileExists) ? response.header("Content-Range") : null;

      if (fileExists
          && response.code() == HttpStatus.SC_PARTIAL_CONTENT
          && !StringUtils.isEmpty(contentRangeHeader)) {
        String start =
            contentRangeHeader.substring("bytes ".length(), contentRangeHeader.indexOf("-"));
        request.setSoFar(Long.valueOf(start));
        Log.d(TAG, "Starting download at position " + request.getSoFar());

        out = new RandomAccessFile(destination, "rw");
        out.seek(request.getSoFar());
      } else {
        destination.delete();
        destination.createNewFile();
        out = new RandomAccessFile(destination, "rw");
      }

      byte[] buffer = new byte[BUFFER_SIZE];
      int count = 0;
      request.setStatusMsg(R.string.download_running);
      Log.d(TAG, "Getting size of download");
      request.setSize(responseBody.contentLength() + request.getSoFar());
      Log.d(TAG, "Size is " + request.getSize());
      if (request.getSize() < 0) {
        request.setSize(DownloadStatus.SIZE_UNKNOWN);
      }

      long freeSpace = StorageUtils.getFreeSpaceAvailable();
      Log.d(TAG, "Free space is " + freeSpace);

      if (request.getSize() != DownloadStatus.SIZE_UNKNOWN && request.getSize() > freeSpace) {
        onFail(DownloadError.ERROR_NOT_ENOUGH_SPACE, null);
        return;
      }

      Log.d(TAG, "Starting download");
      try {
        while (!cancelled && (count = connection.read(buffer)) != -1) {
          out.write(buffer, 0, count);
          request.setSoFar(request.getSoFar() + count);
          request.setProgressPercent(
              (int) (((double) request.getSoFar() / (double) request.getSize()) * 100));
        }
      } catch (IOException e) {
        Log.e(TAG, Log.getStackTraceString(e));
      }
      if (cancelled) {
        onCancelled();
      } else {
        // check if size specified in the response header is the same as the size of the
        // written file. This check cannot be made if compression was used
        if (!isGzip
            && request.getSize() != DownloadStatus.SIZE_UNKNOWN
            && request.getSoFar() != request.getSize()) {
          onFail(
              DownloadError.ERROR_IO_ERROR,
              "Download completed but size: "
                  + request.getSoFar()
                  + " does not equal expected size "
                  + request.getSize());
          return;
        } else if (request.getSize() > 0 && request.getSoFar() == 0) {
          onFail(DownloadError.ERROR_IO_ERROR, "Download completed, but nothing was read");
          return;
        }
        onSuccess();
      }

    } catch (IllegalArgumentException e) {
      e.printStackTrace();
      onFail(DownloadError.ERROR_MALFORMED_URL, e.getMessage());
    } catch (SocketTimeoutException e) {
      e.printStackTrace();
      onFail(DownloadError.ERROR_CONNECTION_ERROR, e.getMessage());
    } catch (UnknownHostException e) {
      e.printStackTrace();
      onFail(DownloadError.ERROR_UNKNOWN_HOST, e.getMessage());
    } catch (IOException e) {
      e.printStackTrace();
      onFail(DownloadError.ERROR_IO_ERROR, e.getMessage());
    } catch (NullPointerException e) {
      // might be thrown by connection.getInputStream()
      e.printStackTrace();
      onFail(DownloadError.ERROR_CONNECTION_ERROR, request.getSource());
    } finally {
      IOUtils.closeQuietly(out);
      AntennapodHttpClient.cleanup();
      IOUtils.closeQuietly(responseBody);
    }
  }
예제 #19
0
  @Override
  protected void download() {
    File destination = new File(request.getDestination());
    final boolean fileExists = destination.exists();

    if (request.isDeleteOnFailure() && fileExists) {
      Log.w(TAG, "File already exists");
      if (request.getFeedfileType() != FeedImage.FEEDFILETYPE_FEEDIMAGE) {
        onFail(DownloadError.ERROR_FILE_EXISTS, null);
        return;
      } else {
        onSuccess();
        return;
      }
    }

    HttpClient httpClient = AntennapodHttpClient.getHttpClient();
    RandomAccessFile out = null;
    InputStream connection = null;
    try {
      HttpGet httpGet = new HttpGet(URIUtil.getURIFromRequestUrl(request.getSource()));

      // add authentication information
      String userInfo = httpGet.getURI().getUserInfo();
      if (userInfo != null) {
        String[] parts = userInfo.split(":");
        if (parts.length == 2) {
          httpGet.addHeader(
              BasicScheme.authenticate(
                  new UsernamePasswordCredentials(parts[0], parts[1]), "UTF-8", false));
        }
      } else if (!StringUtils.isEmpty(request.getUsername()) && request.getPassword() != null) {
        httpGet.addHeader(
            BasicScheme.authenticate(
                new UsernamePasswordCredentials(request.getUsername(), request.getPassword()),
                "UTF-8",
                false));
      }

      // add range header if necessary
      if (fileExists) {
        request.setSoFar(destination.length());
        httpGet.addHeader(new BasicHeader("Range", "bytes=" + request.getSoFar() + "-"));
        if (BuildConfig.DEBUG) Log.d(TAG, "Adding range header: " + request.getSoFar());
      }

      HttpResponse response = httpClient.execute(httpGet);
      HttpEntity httpEntity = response.getEntity();
      int responseCode = response.getStatusLine().getStatusCode();
      Header contentEncodingHeader = response.getFirstHeader("Content-Encoding");

      final boolean isGzip =
          contentEncodingHeader != null
              && contentEncodingHeader.getValue().equalsIgnoreCase("gzip");

      if (BuildConfig.DEBUG) Log.d(TAG, "Response code is " + responseCode);

      if (responseCode / 100 != 2 || httpEntity == null) {
        final DownloadError error;
        final String details;
        if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
          error = DownloadError.ERROR_UNAUTHORIZED;
          details = String.valueOf(responseCode);
        } else {
          error = DownloadError.ERROR_HTTP_DATA_ERROR;
          details = String.valueOf(responseCode);
        }
        onFail(error, details);
        return;
      }

      if (!StorageUtils.storageAvailable(PodcastApp.getInstance())) {
        onFail(DownloadError.ERROR_DEVICE_NOT_FOUND, null);
        return;
      }

      connection = new BufferedInputStream(AndroidHttpClient.getUngzippedContent(httpEntity));

      Header[] contentRangeHeaders = (fileExists) ? response.getHeaders("Content-Range") : null;

      if (fileExists
          && responseCode == HttpStatus.SC_PARTIAL_CONTENT
          && contentRangeHeaders != null
          && contentRangeHeaders.length > 0) {
        String start =
            contentRangeHeaders[0]
                .getValue()
                .substring("bytes ".length(), contentRangeHeaders[0].getValue().indexOf("-"));
        request.setSoFar(Long.valueOf(start));
        Log.d(TAG, "Starting download at position " + request.getSoFar());

        out = new RandomAccessFile(destination, "rw");
        out.seek(request.getSoFar());
      } else {
        destination.delete();
        destination.createNewFile();
        out = new RandomAccessFile(destination, "rw");
      }

      byte[] buffer = new byte[BUFFER_SIZE];
      int count = 0;
      request.setStatusMsg(R.string.download_running);
      if (BuildConfig.DEBUG) Log.d(TAG, "Getting size of download");
      request.setSize(httpEntity.getContentLength() + request.getSoFar());
      if (BuildConfig.DEBUG) Log.d(TAG, "Size is " + request.getSize());
      if (request.getSize() < 0) {
        request.setSize(DownloadStatus.SIZE_UNKNOWN);
      }

      long freeSpace = StorageUtils.getFreeSpaceAvailable();
      if (BuildConfig.DEBUG) Log.d(TAG, "Free space is " + freeSpace);

      if (request.getSize() != DownloadStatus.SIZE_UNKNOWN && request.getSize() > freeSpace) {
        onFail(DownloadError.ERROR_NOT_ENOUGH_SPACE, null);
        return;
      }

      if (BuildConfig.DEBUG) Log.d(TAG, "Starting download");
      while (!cancelled && (count = connection.read(buffer)) != -1) {
        out.write(buffer, 0, count);
        request.setSoFar(request.getSoFar() + count);
        request.setProgressPercent(
            (int) (((double) request.getSoFar() / (double) request.getSize()) * 100));
      }
      if (cancelled) {
        onCancelled();
      } else {
        // check if size specified in the response header is the same as the size of the
        // written file. This check cannot be made if compression was used
        if (!isGzip
            && request.getSize() != DownloadStatus.SIZE_UNKNOWN
            && request.getSoFar() != request.getSize()) {
          onFail(
              DownloadError.ERROR_IO_ERROR,
              "Download completed but size: "
                  + request.getSoFar()
                  + " does not equal expected size "
                  + request.getSize());
          return;
        }
        onSuccess();
      }

    } catch (IllegalArgumentException e) {
      e.printStackTrace();
      onFail(DownloadError.ERROR_MALFORMED_URL, e.getMessage());
    } catch (SocketTimeoutException e) {
      e.printStackTrace();
      onFail(DownloadError.ERROR_CONNECTION_ERROR, e.getMessage());
    } catch (UnknownHostException e) {
      e.printStackTrace();
      onFail(DownloadError.ERROR_UNKNOWN_HOST, e.getMessage());
    } catch (IOException e) {
      e.printStackTrace();
      onFail(DownloadError.ERROR_IO_ERROR, e.getMessage());
    } catch (NullPointerException e) {
      // might be thrown by connection.getInputStream()
      e.printStackTrace();
      onFail(DownloadError.ERROR_CONNECTION_ERROR, request.getSource());
    } finally {
      IOUtils.closeQuietly(out);
      AntennapodHttpClient.cleanup();
    }
  }
예제 #20
0
  /*
   * We don't use getContentEncoding() on the URL connection, because it might leave open streams behind.
   * See https://bugs.eclipse.org/bugs/show_bug.cgi?id=117890
   */
  public static char[] getURLContents(String docUrlValue) {
    InputStream stream = null;
    JarURLConnection connection2 = null;
    try {
      URL docUrl = new URL(docUrlValue);
      URLConnection connection = docUrl.openConnection();
      connection.setConnectTimeout(10000);
      connection.setReadTimeout(10000);

      if (connection instanceof JarURLConnection) {
        connection2 = (JarURLConnection) connection;
        // https://bugs.eclipse.org/bugs/show_bug.cgi?id=156307
        connection.setUseCaches(false);
      }
      try {
        stream = new BufferedInputStream(connection.getInputStream());
      } catch (IllegalArgumentException e) {
        // https://bugs.eclipse.org/bugs/show_bug.cgi?id=304316
        return null;
      } catch (NullPointerException e) {
        // https://bugs.eclipse.org/bugs/show_bug.cgi?id=304316
        return null;
      }
      String encoding = connection.getContentEncoding();
      byte[] contents = Util.getInputStreamAsByteArray(stream, connection.getContentLength());
      if (encoding == null) {
        int index = getIndexOf(contents, CONTENT_TYPE, 0);
        if (index != -1) {
          index = getIndexOf(contents, CONTENT, index);
          if (index != -1) {
            int offset = index + CONTENT.length;
            int index2 = getIndexOf(contents, CLOSING_DOUBLE_QUOTE, offset);
            if (index2 != -1) {
              final int charsetIndex = getIndexOf(contents, CHARSET, offset);
              if (charsetIndex != -1) {
                int start = charsetIndex + CHARSET.length;
                encoding = new String(contents, start, index2 - start, IApiCoreConstants.UTF_8);
              }
            }
          }
        }
      }
      if (contents != null) {
        if (encoding != null) {
          return new String(contents, encoding).toCharArray();
        } else {
          // platform encoding is used
          return new String(contents).toCharArray();
        }
      }
    } catch (SocketTimeoutException e) {
      e.printStackTrace();
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (FileNotFoundException e) {
      // ignore. see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=120559
    } catch (SocketException e) {
      // ignore. see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=247845
    } catch (UnknownHostException e) {
      // ignore. see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=247845
    } catch (ProtocolException e) {
      // ignore. see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=247845
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (stream != null) {
        try {
          stream.close();
        } catch (IOException e) {
          // ignore
        }
      }
      if (connection2 != null) {
        try {
          connection2.getJarFile().close();
        } catch (IOException e) {
          // ignore
        } catch (IllegalStateException e) {
          /*
           * ignore. Can happen in case the stream.close() did close the jar file
           * see https://bugs.eclipse.org/bugs/show_bug.cgi?id=140750
           */
        }
      }
    }
    return null;
  }