private static void postTrackedEntityInstance(
      TrackedEntityInstance trackedEntityInstance, DhisApi dhisApi) throws APIException {
    try {
      Response response = dhisApi.postTrackedEntityInstance(trackedEntityInstance);
      if (response.getStatus() == 200) {
        ImportSummary importSummary = getImportSummary(response);
        handleImportSummary(
            importSummary, FailedItem.TRACKEDENTITYINSTANCE, trackedEntityInstance.getLocalId());
        if (ImportSummary.SUCCESS.equals(importSummary.getStatus())
            || ImportSummary.OK.equals(importSummary.getStatus())) {

          // change state and save trackedentityinstance

          // trackedEntityInstance.setState(State.SYNCED);
          trackedEntityInstance.setFromServer(true);
          trackedEntityInstance.save();

          clearFailedItem(FailedItem.TRACKEDENTITYINSTANCE, trackedEntityInstance.getLocalId());
          UpdateTrackedEntityInstanceTimestamp(trackedEntityInstance, dhisApi);
        }
      }
    } catch (APIException apiException) {
      NetworkUtils.handleTrackedEntityInstanceSendException(apiException, trackedEntityInstance);
    }
  }
 public Throwable handleError(RetrofitError cause) {
   Response r = cause.getResponse();
   if (r != null) {
     Log.d("Retrofix", "Reponse Status: " + r.getStatus() + " , Reason: " + r.getReason());
   }
   return cause;
 }
Example #3
0
 @Override
 public Throwable handleError(RetrofitError cause) {
   Response r = cause.getResponse();
   if (r != null && r.getStatus() == 401) {
     return cause.getCause();
   }
   return cause;
 }
 protected void checkResult(Response response) {
   int statusCode = response.getStatus();
   if (statusCode == 404
       || statusCode == 400
       || statusCode == 500
       || statusCode == 403
       || statusCode == 401) {
     throw RetrofitError.httpError(response.getUrl(), response, null, null);
   }
 }
  /**
   * Attempts to delete the specified user entry in the associated FreeAgent account.
   *
   * @param user The populated user instance.
   * @return True if the user has been deleted successfully, otherwise false.
   */
  public boolean deleteUser(FreeAgentUser user) {
    if (user != null) {
      String userId = extractIdentifier(user.getUrl());

      if (userId != null && !userId.isEmpty()) {
        Response response = freeAgentServiceInstance.deleteUser(userId);

        if (response.getStatus() == 200) {
          return true;
        } else {
          return false;
        }
      }
    }
    return false;
  }
  /**
   * Attempts to delete the specified invoice entry in the associated FreeAgent account.
   *
   * @param invoice The populated invoice instance.
   * @return True if the invoice has been deleted successfully, otherwise false.
   */
  public boolean deleteInvoice(FreeAgentInvoice invoice) {
    if (invoice != null) {
      String invoiceId = extractIdentifier(invoice.getUrl());

      if (invoiceId != null && !invoiceId.isEmpty()) {
        Response response = freeAgentServiceInstance.deleteInvoice(invoiceId);

        if (response.getStatus() == 200) {
          return true;
        } else {
          return false;
        }
      }
    }
    return false;
  }
  /**
   * Attempts to delete the specified project entry in the associated FreeAgent account.
   *
   * @param project The populated project instance.
   * @return True if the project has been deleted successfully, otherwise false.
   */
  public boolean deleteProject(FreeAgentProject project) {
    if (project != null) {
      String projectId = extractIdentifier(project.getUrl());

      if (projectId != null && !projectId.isEmpty()) {
        Response response = freeAgentServiceInstance.deleteProject(projectId);

        if (response.getStatus() == 200) {
          return true;
        } else {
          return false;
        }
      }
    }
    return false;
  }
 @Override
 public void onResponseOk(Object o, Response r) {
   if (r != null && r.getStatus() == 204) {
     repoWatched = true;
     invalidateOptionsMenu();
   }
 }
 @Override
 public void onResponseOk(Object o, Response r) {
   hideProgressDialog();
   if (r != null && r.getStatus() == 204) {
     repoWatched = false;
     invalidateOptionsMenu();
   }
 }
  /**
   * Attempts to update the specified invoice entry in the associated FreeAgent account.
   *
   * @param invoice The populated Invoice instance.
   * @return True if the invoice has been updated successfully, otherwise false.
   */
  public boolean updateInvoice(FreeAgentInvoice invoice) {
    if (invoice != null) {
      String invoiceId = extractIdentifier(invoice.getUrl());

      if (invoiceId != null && !invoiceId.isEmpty()) {
        Response response =
            freeAgentServiceInstance.updateInvoice(new FreeAgentInvoiceWrapper(invoice), invoiceId);
        if (response.getStatus() == 200) {
          invoice.setUpdatedAt(dateFormat.format(new Date()));
          return true;
        } else {
          return false;
        }
      }
    }
    return false;
  }
  /**
   * Attempts to update the specified project entry in the associated FreeAgent account.
   *
   * @param project The populated project instance.
   * @return True if the project has been updated successfully, otherwise false.
   */
  public boolean updateProject(FreeAgentProject project) {
    if (project != null) {
      String projectId = extractIdentifier(project.getUrl());

      if (projectId != null && !projectId.isEmpty()) {
        Response response =
            freeAgentServiceInstance.updateProject(new FreeAgentProjectWrapper(project), projectId);
        if (response.getStatus() == 200) {
          project.setUpdatedAt(dateFormat.format(new Date()));
          return true;
        } else {
          return false;
        }
      }
    }
    return false;
  }
 @Override
 protected Void doInBackground(ObdReading... readings) {
   Log.d(TAG, "Uploading " + readings.length + " readings..");
   // instantiate reading service client
   final String endpoint = prefs.getString(ConfigActivity.UPLOAD_URL_KEY, "");
   RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(endpoint).build();
   ObdService service = restAdapter.create(ObdService.class);
   // upload readings
   for (ObdReading reading : readings) {
     try {
       Response response = service.uploadReading(reading);
       assert response.getStatus() == 200;
     } catch (RetrofitError re) {
       Log.e(TAG, re.toString());
     }
   }
   Log.d(TAG, "Done");
   return null;
 }
  private static void putEvent(Event event, DhisApi dhisApi) throws APIException {
    try {
      Response response = dhisApi.putEvent(event.getEvent(), event);
      if (response.getStatus() == 200) {
        ImportSummary importSummary = getImportSummary(response);
        handleImportSummary(importSummary, FailedItem.EVENT, event.getLocalId());
        if (ImportSummary.SUCCESS.equals(importSummary.getStatus())
            || ImportSummary.OK.equals(importSummary.getStatus())) {

          event.setFromServer(true);
          event.save();
          clearFailedItem(FailedItem.EVENT, event.getLocalId());
          UpdateEventTimestamp(event, dhisApi);
        }
      }
    } catch (APIException apiException) {
      NetworkUtils.handleEventSendException(apiException, event);
    }
  }
  @Override
  protected IStatus run(IProgressMonitor monitor) {
    monitor.beginTask("Syncing Languages", selectLangs.length);
    for (ProjectLanguage lang : selectLangs) {
      if (monitor.isCanceled()) {
        return Status.CANCEL_STATUS;
      } else {
        try {
          Response resp =
              service.exportTranslation(projectId, lang.getCode(), "strings.xml", "strings.xml");

          if (resp.getStatus() == 204) {
            continue; // skip empty content file
          }

          String androidCode;
          if (lang.getCode().contains("-")) {
            androidCode = lang.getCode().replaceFirst("-", "-r");
          } else {
            androidCode = lang.getCode();
          }
          IFile file = project.getFile("/res/values-" + androidCode + "/strings.xml");
          prepareFolder((IFolder) file.getParent().getAdapter(IFolder.class));
          if (file.exists()) {
            file.setContents(resp.getBody().in(), true, true, monitor);
          } else {
            file.create(resp.getBody().in(), true, monitor);
          }
          // exportFile.mkdir();
          // FileUtils.copyInputStreamToFile(
          // resp.getBody().in(), exportFile);
          monitor.worked(1);
        } catch (Exception e) {
          return new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Error while downloading file", e);
        }
      }
    }
    monitor.done();
    return Status.OK_STATUS;
  }
Example #15
0
  @Override
  public Response execute(Request request) throws IOException {
    Response response = wrappedClient.execute(request);

    boolean gzipped = false;
    for (Header h : response.getHeaders()) {
      if (h.getName() != null
          && h.getName().toLowerCase().equals("content-encoding")
          && h.getValue() != null
          && h.getValue().toLowerCase().equals("gzip")) {
        gzipped = true;
        break;
      }
    }

    Response r = null;
    if (gzipped) {
      InputStream is = null;
      ByteArrayOutputStream bos = null;

      try {
        is = new BufferedInputStream(new GZIPInputStream(response.getBody().in()));
        bos = new ByteArrayOutputStream();

        int b;
        while ((b = is.read()) != -1) {
          bos.write(b);
        }

        TypedByteArray body = new TypedByteArray(response.getBody().mimeType(), bos.toByteArray());
        r =
            new Response(
                response.getUrl(),
                response.getStatus(),
                response.getReason(),
                response.getHeaders(),
                body);
      } finally {
        if (is != null) {
          is.close();
        }
        if (bos != null) {
          bos.close();
        }
      }
    } else {
      r = response;
    }
    return r;
  }
  private static void postEnrollment(Enrollment enrollment, DhisApi dhisApi) throws APIException {
    try {
      Response response = dhisApi.postEnrollment(enrollment);
      if (response.getStatus() == 200) {
        ImportSummary importSummary = getImportSummary(response);
        handleImportSummary(importSummary, FailedItem.ENROLLMENT, enrollment.getLocalId());

        if (ImportSummary.SUCCESS.equals(importSummary.getStatus())
            || ImportSummary.OK.equals(importSummary.getStatus())) {
          // change state and save enrollment

          // enrollment.setState(State.SYNCED);
          enrollment.setFromServer(true);
          enrollment.save();
          clearFailedItem(FailedItem.ENROLLMENT, enrollment.getLocalId());
          UpdateEnrollmentTimestamp(enrollment, dhisApi);
        }
      }
    } catch (APIException apiException) {
      NetworkUtils.handleEnrollmentSendException(apiException, enrollment);
    }
  }
 private static void postEvent(Event event, DhisApi dhisApi) throws APIException {
   try {
     Response response = dhisApi.postEvent(event);
     if (response.getStatus() == 200) {
       ImportSummary importSummary = getImportSummary(response);
       handleImportSummary(importSummary, FailedItem.EVENT, event.getLocalId());
       if (ImportSummary.SUCCESS.equals(importSummary.getStatus())
           || ImportSummary.OK.equals(importSummary.getStatus())) {
         // also, we will need to find UUID of newly created event,
         // which is contained inside of HTTP Location header
         Header header = NetworkUtils.findLocationHeader(response.getHeaders());
         // change state and save event
         event.setFromServer(true);
         event.save();
         clearFailedItem(FailedItem.EVENT, event.getLocalId());
         UpdateEventTimestamp(event, dhisApi);
       }
     }
   } catch (APIException apiException) {
     NetworkUtils.handleEventSendException(apiException, event);
   }
 }
 private static ImportSummary getPostImportSummary(Response response) {
   ImportSummary importSummary = null;
   try {
     String body = new StringConverter().fromBody(response.getBody(), String.class);
     Log.d(CLASS_TAG, body);
     importSummary =
         DhisController.getInstance().getObjectMapper().readValue(body, ImportSummary.class);
   } catch (IOException e) {
     e.printStackTrace();
   } catch (ConversionException e) {
     e.printStackTrace();
   }
   return importSummary;
 }
 @Override
 public void failure(RetrofitError error) {
   Response response = error.getResponse();
   String responseMsg = null;
   // if request failed and either no response received or internal error occurred
   if (response == null) {
     switch (error.getKind()) {
       case NETWORK:
         responseMsg = getString(R.string.error_net);
         break;
       case CONVERSION:
         responseMsg = getString(R.string.error_conv);
         break;
       case UNEXPECTED:
         responseMsg = getString(R.string.error_unknown);
         break;
       default:
         break;
     }
     mListener.onError(/*null,*/ responseMsg);
     return;
   }
   // if response received, but is not valid JSON
   JsonObject body = null;
   try {
     body = (JsonObject) error.getBodyAs(JsonObject.class);
   } catch (Exception e) {
     Log.e(ConversionException.class.getName(), e.getLocalizedMessage());
     //            responseMsg = getString(R.string.error_conv);
     mListener.onError(response.getReason() + "\nError code: " + response.getStatus());
     return;
   }
   // if response is valid JSON
   String[] errorInfo = getErrorInfo(body);
   mListener.onError(errorInfo[1] + "\nError code: " + errorInfo[0]);
 }
 private static ImportSummary getPutImportSummary(Response response) {
   ApiResponse apiResponse = null;
   try {
     String body = new StringConverter().fromBody(response.getBody(), String.class);
     Log.d(CLASS_TAG, body);
     apiResponse =
         DhisController.getInstance().getObjectMapper().readValue(body, ApiResponse.class);
     if (apiResponse != null
         && apiResponse.getImportSummaries() != null
         && !apiResponse.getImportSummaries().isEmpty()) {
       return (apiResponse.getImportSummaries().get(0));
     }
   } catch (IOException e) {
     e.printStackTrace();
   } catch (ConversionException e) {
     e.printStackTrace();
   }
   return null;
 }
 private static ImportSummary getImportSummary(Response response) {
   // because the web api almost randomly gives the responses in different forms, this
   // method checks which one it is that is being returned, and parses accordingly.
   try {
     JsonNode node =
         DhisController.getInstance()
             .getObjectMapper()
             .readTree(new StringConverter().fromBody(response.getBody(), String.class));
     if (node == null) {
       return null;
     }
     if (node.has("response")) {
       return getPutImportSummary(response);
     } else {
       return getPostImportSummary(response);
     }
   } catch (IOException e) {
     e.printStackTrace();
   } catch (ConversionException e) {
     e.printStackTrace();
   }
   return null;
 }
Example #22
0
 /**
  * handles the retrofit errors<br>
  * (which is always thrown when http status != 200)<br>
  * and print some error msg
  *
  * @param re the Retrofit error
  */
 private void handleRetrofitError(RetrofitError re) {
   Response r = re.getResponse();
   String msg = "";
   if (r != null) {
     msg = r.getStatus() + " " + r.getReason();
     if (r.getBody() != null && r.getBody().length() > 0) {
       try {
         InputStream in = r.getBody().in();
         String body = " - " + IOUtils.toString(in, "UTF-8");
         in.close();
         LOGGER.trace(body);
       } catch (IOException e1) {
         LOGGER.warn("IOException on Trakt error", e1);
       }
     }
   } else {
     msg = re.getMessage();
   }
   LOGGER.error("Trakt error (wrong settings?) " + msg);
   MessageManager.instance.pushMessage(new Message(MessageLevel.ERROR, msg, "Settings.trakttv"));
 }
  protected boolean retry(RetrofitError error, AtomicInteger retries) {
    // increment retries
    retries.incrementAndGet();
    Log.i(TAG, "request retry check: " + retries.get());

    // no internet connection
    if (error.getCause() instanceof NoConnectivityException) {
      Log.v(TAG, "No internet!");
      retryHandler.onNoInternet();
      return false;
    }

    Response r = error.getResponse();

    if (r != null && r.getStatus() == 400) {
      Log.v(TAG, "400 error! bad request!");
      if (retries.get() < retryHandler.RETRY_400_BADREQUEST) {

        retryHandler.on400();

        return true;

      } else {
        return false;
      }
    }

    if (r != null && r.getStatus() == 500) {
      Log.v(TAG, "500 error! internal server error!");
      if (retries.get() < retryHandler.RETRY_500_ISE) {

        retryHandler.on500();

        return true;

      } else {
        return false;
      }
    }

    if (r != null && r.getStatus() == 401) {
      Log.v(TAG, "401 error! unauthorized");
      if (retries.get() < retryHandler.RETRY_401_UNAUTHORIZED) {

        retryHandler.on401();

        return true;

      } else {
        return false;
      }
    }

    if (r != null && r.getStatus() == 403) {
      Log.v(TAG, "403 error! forbidden!");
      if (retries.get() < retryHandler.RETRY_403_FORBIDDEN) {

        retryHandler.on403();

        return true;

      } else {
        return false;
      }
    }

    if (r != null && r.getStatus() == 404) {
      Log.v(TAG, "404 hiba!");
      if (retries.get() < retryHandler.RETRY_404_NOTFOUND) { // retry
        retryHandler.on404();
        return true;
      } else { // no more
        retries.set(0);
        return false;
      }
    }

    // TODO other error check
    if (error.isNetworkError()) { // network error
      if (error.getCause() instanceof SocketTimeoutException) { // connection timeout check
        Log.v(TAG, "retry - socket timeout exception!");
        if (retries.get() < retryHandler.DEFAULT_RETRY_COUNT) { // retry
          // retryHandler.onSocketTimeout();
          return true;
        } else { // no more
          retries.set(0);
          return false;
        }
      } else { // no connection check
        Log.v(TAG, "retry - no connection check!");
        if (retries.get() < retryHandler.DEFAULT_RETRY_COUNT) { // retry
          //  retryHandler.onNoConnectivity();
          return true;
        } else { // no more
          retries.set(0);
          return false;
        }
      }
    } else { // non network error check
      Log.v(TAG, "retry - non error check!");
      retries.set(0);
      return false;
    }
  }