/**
   * Get the document's metadata from the package.
   *
   * @param documentPackage The DocumentPackage we want to get document from.
   * @param documentId Id of document to get.
   * @return the document's metadata
   */
  public com.silanis.esl.sdk.Document getDocumentMetadata(
      DocumentPackage documentPackage, String documentId) {
    String path =
        template
            .urlFor(UrlTemplate.DOCUMENT_ID_PATH)
            .replace("{packageId}", documentPackage.getId().getId())
            .replace("{documentId}", documentId)
            .build();

    try {
      String response = client.get(path);
      Document apilDocument = Serialization.fromJson(response, Document.class);

      // Wipe out the members not related to the metadata
      apilDocument.setApprovals(new ArrayList<Approval>());
      apilDocument.setFields(new ArrayList<Field>());
      apilDocument.setPages(new ArrayList<com.silanis.esl.api.model.Page>());

      return new DocumentConverter(
              apilDocument, new DocumentPackageConverter(documentPackage).toAPIPackage())
          .toSDKDocument();
    } catch (RequestException e) {
      throw new EslServerException("Could not get the document's metadata.", e);
    } catch (Exception e) {
      throw new EslException(
          "Could not get the document's metadata." + " Exception: " + e.getMessage());
    }
  }
  /*
                                            _
   _ __   __ _ _ __ ___   ___    ___  _ __ | |_   _
  | '_ \ / _` | '_ ` _ \ / _ \  / _ \| '_ \| | | | |
  | | | | (_| | | | | | |  __/ | (_) | | | | | |_| |
  |_| |_|\__,_|_| |_| |_|\___|  \___/|_| |_|_|\__, |
                                              |___/

   */
  @Test(expected = IOException.class)
  public void getFromLocationName_Exception() throws IOException {
    String addressToGeocode = "address to geocode";
    Long apiKey = 123L;
    int numberOfResults = 6;
    final RestClient restClientMock = EasyMock.createMock(RestClient.class);
    HashMap<String, String> params = new HashMap<String, String>();
    params.put(GisgraphyGeocoder.FORMAT_PARAMETER_NAME, GisgraphyGeocoder.DEFAULT_FORMAT);
    params.put(GisgraphyGeocoder.ADDRESS_PARAMETER_NAME, addressToGeocode);
    params.put(GisgraphyGeocoder.COUNTRY_PARAMETER_NAME, Locale.getDefault().getCountry());
    params.put(GisgraphyGeocoder.APIKEY_PARAMETER_NAME, apiKey + "");
    EasyMock.expect(
            restClientMock.get(GisgraphyGeocoder.GEOCODING_URI, AddressResultsDto.class, params))
        .andStubThrow(new RuntimeException());
    EasyMock.replay(restClientMock);
    GisgraphyGeocoder geocoder =
        new GisgraphyGeocoder(null) {
          @Override
          protected RestClient createRestClient() {
            return restClientMock;
          }

          @Override
          protected void log_d(String message) {}
        };
    geocoder.setApiKey(apiKey);
    geocoder.getFromLocationName(addressToGeocode, numberOfResults);
  }
  @Test
  public void getFromLocationName() throws IOException {
    String addressToGeocode = "address to geocode";
    Long apiKey = 123L;
    int numberOfResults = 6;
    List<com.gisgraphy.addressparser.Address> gisgraphyAddress = createGisgraphyAddresses(10);
    AddressResultsDto addressResultsDto = new AddressResultsDto(gisgraphyAddress, 10L);

    final RestClient restClientMock = EasyMock.createMock(RestClient.class);
    // EasyMock.expect(restClientMock.getWebServiceUrl()).andReturn(baseUrl);
    HashMap<String, String> params = new HashMap<String, String>();
    params.put(GisgraphyGeocoder.FORMAT_PARAMETER_NAME, GisgraphyGeocoder.DEFAULT_FORMAT);
    params.put(GisgraphyGeocoder.ADDRESS_PARAMETER_NAME, addressToGeocode);
    params.put(GisgraphyGeocoder.COUNTRY_PARAMETER_NAME, Locale.getDefault().getCountry());
    params.put(GisgraphyGeocoder.APIKEY_PARAMETER_NAME, apiKey + "");
    EasyMock.expect(
            restClientMock.get(GisgraphyGeocoder.GEOCODING_URI, AddressResultsDto.class, params))
        .andReturn(addressResultsDto);
    EasyMock.replay(restClientMock);
    GisgraphyGeocoder geocoder =
        new GisgraphyGeocoder(null) {
          @Override
          protected RestClient createRestClient() {
            return restClientMock;
          }

          @Override
          protected void log_d(String message) {}
        };
    geocoder.setApiKey(apiKey);
    List<Address> AndroidAddress = geocoder.getFromLocationName(addressToGeocode, numberOfResults);
    EasyMock.verify(restClientMock);
    Assert.assertEquals(
        "the max parameter should be taken into account", numberOfResults, AndroidAddress.size());
  }
  /**
   * Get Journal Entries.
   *
   * @param userId The ID of the user whose e-journal entries are being retrieved.
   * @return all of the user's notary e-journal entries.
   */
  public List<com.silanis.esl.sdk.NotaryJournalEntry> getJournalEntries(String userId) {
    List<com.silanis.esl.sdk.NotaryJournalEntry> result =
        new ArrayList<com.silanis.esl.sdk.NotaryJournalEntry>();
    String path =
        template.urlFor(UrlTemplate.NOTARY_JOURNAL_PATH).replace("{userId}", userId).build();

    try {
      String stringResponse = client.get(path);
      Result<com.silanis.esl.api.model.NotaryJournalEntry> apiResponse =
          JacksonUtil.deserialize(
              stringResponse,
              new TypeReference<Result<com.silanis.esl.api.model.NotaryJournalEntry>>() {});
      for (com.silanis.esl.api.model.NotaryJournalEntry apiNotaryJournalEntry :
          apiResponse.getResults()) {
        result.add(
            new NotaryJournalEntryConverter(apiNotaryJournalEntry).toSDKNotaryJournalEntry());
      }
      return result;

    } catch (RequestException e) {
      throw new EslException("Could not get Journal Entries.", e);
    } catch (Exception e) {
      throw new EslException("Could not get Journal Entries." + " Exception: " + e.getMessage());
    }
  }
  @Test
  public void getFromLocationShouldTakeMaxParameterIntoAccount() throws IOException {
    Long apiKey = 123L;
    int numberOfResults = 6;
    List<StreetDistance> streets = createStreetDistance(10);
    StreetSearchResultsDto streetSearchResultsDto = new StreetSearchResultsDto(streets, 10L, null);
    double lat = 12D;
    double lng = 25D;
    final RestClient restClientMock = EasyMock.createMock(RestClient.class);
    HashMap<String, String> params = new HashMap<String, String>();
    params.put(GisgraphyGeocoder.FORMAT_PARAMETER_NAME, GisgraphyGeocoder.DEFAULT_FORMAT);
    params.put(GisgraphyGeocoder.LATITUDE_PARAMETER_NAME, lat + "");
    params.put(GisgraphyGeocoder.LONGITUDE_PARAMETER_NAME, lng + "");
    params.put(GisgraphyGeocoder.APIKEY_PARAMETER_NAME, apiKey + "");
    EasyMock.expect(
            restClientMock.get(
                GisgraphyGeocoder.REVERSE_GEOCODING_URI, StreetSearchResultsDto.class, params))
        .andReturn(streetSearchResultsDto);
    EasyMock.replay(restClientMock);
    GisgraphyGeocoder geocoder =
        new GisgraphyGeocoder(null) {
          @Override
          protected RestClient createRestClient() {
            return restClientMock;
          }

          @Override
          protected void log_d(String message) {}
        };
    geocoder.setApiKey(apiKey);
    List<Address> addresses = geocoder.getFromLocation(lat, lng, numberOfResults);
    EasyMock.verify(restClientMock);
    Assert.assertEquals(
        "the max parameter should be taken into account", numberOfResults, addresses.size());
  }
  /**
   * Returns a Page of DocumentPackages, that last updated in time range, which represents a
   * paginated query response. Important once you have many DocumentPackages.
   *
   * @param status Returned DocumentPackages must have their status set to this value to be included
   *     in the result set
   * @param request Identifying which page of results to return
   * @param from Date range starting from this date included
   * @param to Date range ending of this date included
   * @return List of DocumentPackages that populate the specified page
   */
  public Page<DocumentPackage> getUpdatedPackagesWithinDateRange(
      PackageStatus status, PageRequest request, Date from, Date to) {
    String fromDate = DateHelper.dateToIsoUtcFormat(from);
    String toDate = DateHelper.dateToIsoUtcFormat(to);

    String path =
        template
            .urlFor(UrlTemplate.PACKAGE_LIST_STATUS_DATE_RANGE_PATH)
            .replace("{status}", new PackageStatusConverter(status).toAPIPackageStatus())
            .replace("{from}", Integer.toString(request.getFrom()))
            .replace("{to}", Integer.toString(request.to()))
            .replace("{lastUpdatedStartDate}", fromDate)
            .replace("{lastUpdatedEndDate}", toDate)
            .build();

    try {
      String response = client.get(path);
      Result<Package> results =
          JacksonUtil.deserialize(response, new TypeReference<Result<Package>>() {});
      return convertToPage(results, request);
    } catch (RequestException e) {
      throw new EslServerException("Could not get package list.", e);
    } catch (Exception e) {
      e.printStackTrace();
      throw new EslException("Could not get package list. Exception: " + e.getMessage());
    }
  }
 @Test(description = "Test get license.")
 public void testGetLicense() throws Exception {
   HttpResponse response = client.get(Constants.LicenseManagement.GET_LICENSE_ENDPOINT);
   Assert.assertEquals(HttpStatus.SC_OK, response.getResponseCode());
   Assert.assertTrue(
       response.getData().contains(Constants.LicenseManagement.LICENSE_RESPONSE_PAYLOAD));
 }
Esempio n. 8
0
  /**
   * Get a checkout preference
   *
   * @param id
   * @return
   * @throws JSONException
   */
  public JSONObject getPreference(String id) throws JSONException, Exception {
    String accessToken;
    try {
      accessToken = this.getAccessToken();
    } catch (Exception e) {
      JSONObject result = new JSONObject(e.getMessage());
      return result;
    }

    JSONObject preferenceResult =
        RestClient.get("/checkout/preferences/" + id + "?access_token=" + accessToken);
    return preferenceResult;
  }
Esempio n. 9
0
  /**
   * Get a preapproval payment
   *
   * @param id
   * @return
   * @throws JSONException
   */
  public JSONObject getPreapprovalPayment(String id) throws JSONException, Exception {
    String accessToken;
    try {
      accessToken = this.getAccessToken();
    } catch (Exception e) {
      JSONObject result = new JSONObject(e.getMessage());
      return result;
    }

    JSONObject preapprovalResult =
        RestClient.get("/preapproval/" + id + "?access_token=" + accessToken);
    return preapprovalResult;
  }
Esempio n. 10
0
  /**
   * Get information for specific authorized payment
   *
   * @param id
   * @return
   * @throws JSONException
   */
  public JSONObject getAuthorizedPayment(String id) throws JSONException, Exception {
    String accessToken;
    try {
      accessToken = this.getAccessToken();
    } catch (Exception e) {
      JSONObject result = new JSONObject(e.getMessage());
      return result;
    }

    JSONObject paymentInfo =
        RestClient.get("/authorized_payments/" + id + "?access_token=" + accessToken);

    return paymentInfo;
  }
  /**
   * Gets the package.
   *
   * @param packageId
   * @return Package
   * @throws EslException
   */
  public Package getApiPackage(String packageId) throws EslException {
    String path =
        template.urlFor(UrlTemplate.PACKAGE_ID_PATH).replace("{packageId}", packageId).build();
    String stringResponse;
    try {
      stringResponse = client.get(path);
    } catch (RequestException e) {
      throw new EslServerException("Could not get package.", e);
    } catch (Exception e) {
      throw new EslException("Could not get package.", e);
    }

    return Serialization.fromJson(stringResponse, Package.class);
  }
 /**
  * Gets the roles for a package.
  *
  * @param packageId
  * @return A list of the roles in the package
  * @throws EslException
  */
 public List<Role> getRoles(PackageId packageId) throws EslException {
   String path =
       template.urlFor(UrlTemplate.ROLE_PATH).replace("{packageId}", packageId.getId()).build();
   String stringResponse;
   try {
     stringResponse = client.get(path);
   } catch (RequestException e) {
     throw new EslServerException(
         "Could not retrieve list of roles for package with id " + packageId.getId(), e);
   } catch (Exception e) {
     throw new EslException(
         "Could not retrieve list of roles for package with id " + packageId.getId(), e);
   }
   return Serialization.fromJson(stringResponse, RoleList.class).getResults();
 }
Esempio n. 13
0
  /**
   * Get information for specific payment
   *
   * @param id
   * @return
   * @throws JSONException
   */
  public JSONObject getPayment(String id) throws JSONException, Exception {
    String accessToken;
    try {
      accessToken = this.getAccessToken();
    } catch (Exception e) {
      JSONObject result = new JSONObject(e.getMessage());
      return result;
    }

    String uriPrefix = this.sandbox ? "/sandbox" : "";

    JSONObject paymentInfo =
        RestClient.get(
            uriPrefix + "/collections/notifications/" + id + "?access_token=" + accessToken);

    return paymentInfo;
  }
  private void insertServiceRequest() {
    // send data to Web Service.
    Random rand = new Random();
    service_id = rand.nextInt(Integer.MAX_VALUE);
    int tokenSeed = rand.nextInt(Integer.MAX_VALUE);
    current_token = md5(tokenSeed + "");

    Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    String fecha = sdf.format(cal.getTime());

    int deliver_state = 1;

    int costo = (int) Math.round(destinations.get(0).total_price);

    ArrayList<String> param = new ArrayList<>();
    param.add(service_id + "");
    param.add(current_token);
    param.add(fecha);
    param.add(deliver_state + "");
    param.add(id_cliente + "");
    param.add(costo + "");
    param.add("0");
    RestClient.get()
        .executeCommand(
            "8",
            param.toString(),
            new Callback<Response>() {
              @Override
              public void success(Response response, retrofit.client.Response response2) {

                insertRoutes();
              }

              @Override
              public void failure(RetrofitError error) {
                hideOverlay();
                showDialog(
                    getResources().getString(R.string.msg_serverError_title),
                    getResources().getString(R.string.msg_serverError),
                    false,
                    false);
              }
            });
  }
  public void getInfoToShow(String type) {

    RestClient.get()
        .executeCommand(
            "5",
            "[" + id_cliente + "]",
            new Callback<Response>() {
              @Override
              public void success(Response response, retrofit.client.Response response2) {
                if (response != null
                    && response.getClientes() != null
                    && response.getClientes().size() > 0) {
                  String nombre = response.getClientes().get(0).getNombre_cliente();
                  String apellido = response.getClientes().get(0).getApellido_cliente();
                  String email = response.getClientes().get(0).getEmail_cliente();
                  String telefono = response.getClientes().get(0).getTelefono_cliente();

                  SharedPreferences settings =
                      WaitingForSherpaActivity.this.getSharedPreferences(
                          "com.fr3estudio.sherpaV3P.UsersData", Context.MODE_PRIVATE);
                  SharedPreferences.Editor editor = settings.edit();
                  // editor.putInt("id_cliente", id_cliente);
                  editor.putString("nombre", nombre);
                  editor.putString("apellido", apellido);
                  editor.putString("email", email);
                  editor.putString("telefono", telefono);
                  System.out.println("metiendo " + nombre + apellido + email + telefono);
                  editor.commit();

                  hideOverlay();
                  showInfo("profile");
                }
              }

              @Override
              public void failure(RetrofitError error) {
                hideOverlay();
                showDialog(
                    getResources().getString(R.string.msg_serverError_title),
                    getResources().getString(R.string.msg_serverError),
                    false,
                    false);
              }
            });
  }
  private String getFastTrackUrl(PackageId packageId, Boolean signing) {
    String path =
        template
            .urlFor(UrlTemplate.FAST_TRACK_URL_PATH)
            .replace("{packageId}", packageId.getId())
            .replace("{signing}", signing.toString())
            .build();

    try {
      String json = client.get(path);
      SigningUrl signingUrl = Serialization.fromJson(json, SigningUrl.class);
      return signingUrl.getUrl();
    } catch (RequestException e) {
      throw new EslException("Could not get a fastTrack url.", e);
    } catch (Exception e) {
      throw new EslException("Could not get a fastTrack url." + " Exception: " + e.getMessage());
    }
  }
  /**
   * Get thank you dialog content.
   *
   * @param packageId The id of the package to get thank you dialog content.
   * @return thank you dialog content
   */
  public String getThankYouDialogContent(PackageId packageId) {
    String path =
        template
            .urlFor(UrlTemplate.THANK_YOU_DIALOG_PATH)
            .replace("{packageId}", packageId.getId())
            .build();

    try {
      String json = client.get(path);
      Properties thankYouDialogContent = Serialization.fromJson(json, Properties.class);
      return thankYouDialogContent.getProperty("body");
    } catch (RequestException e) {
      throw new EslException("Could not get thank you dialog content.", e);
    } catch (Exception e) {
      throw new EslException(
          "Could not get thank you dialog content." + " Exception: " + e.getMessage());
    }
  }
  /**
   * Gets the documents from the history list
   *
   * @return
   */
  public List<com.silanis.esl.sdk.Document> getDocuments() {
    String path = template.urlFor(UrlTemplate.PROVIDER_DOCUMENTS).build();

    try {
      String stringResponse = client.get(path);
      List<Document> apiResponse =
          JacksonUtil.deserialize(stringResponse, new TypeReference<List<Document>>() {});
      List<com.silanis.esl.sdk.Document> documents = new ArrayList<com.silanis.esl.sdk.Document>();
      for (Document document : apiResponse) {
        documents.add(new DocumentConverter(document, null).toSDKDocument());
      }
      return documents;
    } catch (RequestException e) {
      throw new EslServerException("Failed to retrieve documents from history List.", e);
    } catch (Exception e) {
      throw new EslException("Failed to retrieve documents from history list.", e);
    }
  }
  @Test
  public void getFromLocationNameAndBoundingBoxShouldFilter() throws IOException {
    String addressToGeocode = "address to geocode";
    Long apiKey = 123L;
    int numberOfResults = 6;
    List<com.gisgraphy.addressparser.Address> gisgraphyAddress = createGisgraphyAddresses(2);
    // set out of the bounding box
    gisgraphyAddress.get(0).setLat(-10D);
    gisgraphyAddress.get(0).setLng(-20D);

    gisgraphyAddress.get(1).setLat(51D);
    gisgraphyAddress.get(1).setLng(21D);

    AddressResultsDto addressResultsDto = new AddressResultsDto(gisgraphyAddress, 10L);

    final RestClient restClientMock = EasyMock.createMock(RestClient.class);
    // EasyMock.expect(restClientMock.getWebServiceUrl()).andReturn(baseUrl);
    HashMap<String, String> params = new HashMap<String, String>();
    params.put(GisgraphyGeocoder.FORMAT_PARAMETER_NAME, GisgraphyGeocoder.DEFAULT_FORMAT);
    params.put(GisgraphyGeocoder.ADDRESS_PARAMETER_NAME, addressToGeocode);
    params.put(GisgraphyGeocoder.COUNTRY_PARAMETER_NAME, Locale.getDefault().getCountry());
    params.put(GisgraphyGeocoder.APIKEY_PARAMETER_NAME, apiKey + "");
    EasyMock.expect(
            restClientMock.get(GisgraphyGeocoder.GEOCODING_URI, AddressResultsDto.class, params))
        .andReturn(addressResultsDto);
    EasyMock.replay(restClientMock);
    GisgraphyGeocoder geocoder =
        new GisgraphyGeocoder(null) {
          @Override
          protected RestClient createRestClient() {
            return restClientMock;
          }

          @Override
          protected void log_d(String message) {}
        };
    geocoder.setApiKey(apiKey);
    List<Address> addresses =
        geocoder.getFromLocationName(addressToGeocode, numberOfResults, 50, 20, 52, 22);
    EasyMock.verify(restClientMock);
    Assert.assertEquals(1, addresses.size());
    Assert.assertEquals(51D, addresses.get(0).getLatitude());
    Assert.assertEquals(21D, addresses.get(0).getLongitude());
  }
  private String getSigningUrl(PackageId packageId, Role role) {

    String path =
        template
            .urlFor(UrlTemplate.SIGNER_URL_PATH)
            .replace("{packageId}", packageId.getId())
            .replace("{roleId}", role.getId())
            .build();

    try {
      String response = client.get(path);
      SigningUrl signingUrl = Serialization.fromJson(response, SigningUrl.class);
      return signingUrl.getUrl();
    } catch (RequestException e) {
      throw new EslException("Could not get a signing url.", e);
    } catch (Exception e) {
      throw new EslException("Could not get a signing url." + " Exception: " + e.getMessage());
    }
  }
  /**
   * Get a signer from the specified package
   *
   * @param packageId The id of the package in which to get the signer
   * @param signerId The id of signer to get
   * @return The signer
   */
  public com.silanis.esl.sdk.Signer getSigner(PackageId packageId, String signerId) {
    String path =
        template
            .urlFor(UrlTemplate.SIGNER_PATH)
            .replace("{packageId}", packageId.getId())
            .replace("{roleId}", signerId)
            .build();

    try {
      String response = client.get(path);
      Role apiRole = Serialization.fromJson(response, Role.class);
      return new SignerConverter(apiRole).toSDKSigner();

    } catch (RequestException e) {
      throw new EslServerException("Could not get signer.", e);
    } catch (Exception e) {
      throw new EslException("Could not get signer." + " Exception: " + e.getMessage());
    }
  }
  /**
   * Get package support configuration.
   *
   * @param packageId The id of the package to get package support configuration.
   * @return package support configuration
   */
  public SupportConfiguration getConfig(PackageId packageId) {
    String path =
        template
            .urlFor(UrlTemplate.PACKAGE_INFORMATION_CONFIG_PATH)
            .replace("{packageId}", packageId.getId())
            .build();

    try {
      String json = client.get(path);
      com.silanis.esl.api.model.SupportConfiguration apiSupportConfiguration =
          Serialization.fromJson(json, com.silanis.esl.api.model.SupportConfiguration.class);
      return new SupportConfigurationConverter(apiSupportConfiguration).toSDKSupportConfiguration();
    } catch (RequestException e) {
      throw new EslException("Could not get support configuration.", e);
    } catch (Exception e) {
      throw new EslException(
          "Could not get support configuration." + " Exception: " + e.getMessage());
    }
  }
  public Page<DocumentPackage> getTemplates(PageRequest request) {
    String path =
        template
            .urlFor(UrlTemplate.TEMPLATE_LIST_PATH)
            .replace("{from}", Integer.toString(request.getFrom()))
            .replace("{to}", Integer.toString(request.to()))
            .build();

    try {
      String response = client.get(path);
      Result<Package> results =
          JacksonUtil.deserialize(response, new TypeReference<Result<Package>>() {});

      return convertToPage(results, request);
    } catch (RequestException e) {
      throw new EslServerException("Could not get template list.", e);
    } catch (Exception e) {
      throw new EslException("Could not get template list. Exception: " + e.getMessage());
    }
  }
  /**
   * Retrieves the current signing status of the DocumentPackage, Document or Signer specified.
   *
   * @param packageId Id of the DocumentPackage who's status we are to retrieve
   * @param signerId If not null, the id of the signer who's status we are to retrieve
   * @param documentId If not null, the id of the document who's status we are to retrieve
   * @return One of the following values: INACTIVE - process is not active COMPLETE - process has
   *     been completed ARCHIVED - process has been archived SIGNING-PENDING - process is active,
   *     but not all signatures have been added SIGNING-COMPLETE - process is active, all signaures
   *     have been added
   */
  public SigningStatus getSigningStatus(
      PackageId packageId, SignerId signerId, DocumentId documentId) {
    String path =
        template
            .urlFor(UrlTemplate.SIGNING_STATUS_PATH)
            .replace("{packageId}", packageId.getId())
            .replace("{signerId}", signerId != null ? signerId.getId() : "")
            .replace("{documentId}", documentId != null ? documentId.getId() : "")
            .build();

    try {
      String stringResponse = client.get(path);
      ObjectMapper objectMapper = new ObjectMapper();
      JsonNode topNode = objectMapper.readTree(stringResponse);
      String statusString = topNode.get("status").textValue();
      return SigningStatus.statusForToken(statusString);
    } catch (RequestException e) {
      throw new EslServerException("Could not retrieve signing status.", e);
    } catch (Exception e) {
      throw new EslException("Could not retrieve signing status.", e);
    }
  }
Esempio n. 25
0
  public JSONObject searchPayment(Map<String, Object> filters, Long offset, Long limit)
      throws JSONException {
    String accessToken;
    try {
      accessToken = this.getAccessToken();
    } catch (Exception e) {
      JSONObject result = new JSONObject(e.getMessage());
      return result;
    }

    filters.put("offset", offset);
    filters.put("limit", limit);

    String filtersQuery = this.buildQuery(filters);

    String uriPrefix = this.sandbox ? "/sandbox" : "";

    JSONObject collectionResult =
        RestClient.get(
            uriPrefix + "/collections/search?" + filtersQuery + "&access_token=" + accessToken);
    return collectionResult;
  }
  public void isServiceAttended() {

    RestClient.get()
        .executeCommand(
            "10",
            "[" + service_id + "]",
            new Callback<Response>() {
              @Override
              public void success(Response response, retrofit.client.Response response2) {

                if (response != null
                    && response.getDiligencias() != null
                    && response.getDiligencias().size() > 0
                    && !response.getDiligencias().get(0).getToken_actualizaciones().isEmpty()) {
                  String token = response.getDiligencias().get(0).getToken_actualizaciones();
                  if (current_token.equals(token) && !service_canceled) {
                    scheduleAttentionQuery(CONSTANTS.TIME_BETWEEN_SERVICEA_CALLS);
                  } else if (!current_token.equals(token)) {
                    sherpa_id = response.getDiligencias().get(0).getId_sherpa();

                    updateServiceId();
                  }
                } else {
                  scheduleAttentionQuery(CONSTANTS.TIME_BETWEEN_SERVICEA_CALLS);
                }
              }

              @Override
              public void failure(RetrofitError error) {
                hideOverlay();
                showDialog(
                    getResources().getString(R.string.msg_serverError_title),
                    getResources().getString(R.string.msg_serverError),
                    false,
                    false);
              }
            });
  }
  public void insertRoutes() {

    int queriesToInsert = destinations.size();
    ArrayList<String> param = new ArrayList<>();

    for (int i = 0; i < destinations.size(); i++) {
      param.add("pto" + i);
      param.add(new String(destinations.get(i).latitude + "").replace(',', ' '));
      param.add(new String(destinations.get(i).longitude + "").replace(',', ' '));
      param.add(new String(destinations.get(i).service_detail).replace(',', ' '));
      param.add("no");
      param.add(new String(destinations.get(i).address).replace(',', ' '));
      param.add(new String(service_id + "").replace(',', ' '));
      param.add("),");
    }
    Log.i("Waiting", "====>" + param.toString());

    RestClient.get()
        .executeCommand(
            "9",
            param.toString(),
            new Callback<Response>() {
              @Override
              public void success(Response response, retrofit.client.Response response2) {
                scheduleAttentionQuery(CONSTANTS.TIME_BETWEEN_SERVICEA_CALLS);
              }

              @Override
              public void failure(RetrofitError error) {
                hideOverlay();
                showDialog(
                    getResources().getString(R.string.msg_serverError_title),
                    getResources().getString(R.string.msg_serverError),
                    false,
                    false);
              }
            });
  }
  public void updateServiceId() {

    RestClient.get()
        .executeCommand(
            "11",
            "[" + service_id + "]",
            new Callback<Response>() {
              @Override
              public void success(Response response, retrofit.client.Response response2) {
                showServiceInAction();
              }

              @Override
              public void failure(RetrofitError error) {
                hideOverlay();
                showDialog(
                    getResources().getString(R.string.msg_serverError_title),
                    getResources().getString(R.string.msg_serverError),
                    false,
                    false);
              }
            });
  }
Esempio n. 29
0
  /**
   * Generic resource get
   *
   * @param uri
   * @param authenticate
   * @return
   * @throws JSONException
   */
  public JSONObject get(String uri, Map<String, Object> params, boolean authenticate)
      throws JSONException, Exception {
    if (params == null) {
      params = new HashMap<String, Object>();
    }
    if (authenticate) {
      String accessToken;
      try {
        accessToken = this.getAccessToken();
      } catch (Exception e) {
        JSONObject result = new JSONObject(e.getMessage());
        return result;
      }

      params.put("access_token", accessToken);
    }

    if (!params.isEmpty()) {
      uri += (uri.contains("?") ? "&" : "?") + this.buildQuery(params);
    }

    JSONObject result = RestClient.get(uri);
    return result;
  }
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CONSTANTS.CANCEL_CONFIRMATION_OVARLAY) {
      if (data.getExtras() != null
          && data.getExtras().containsKey("confirm")
          && data.getExtras().getBoolean("confirm")) {
        service_canceled = true;
        cancelUpdates();

        RestClient.get()
            .executeCommand(
                "17",
                "[" + service_id + "]",
                new Callback<Response>() {
                  @Override
                  public void success(Response response, retrofit.client.Response response2) {

                    Log.i(TAG, "ServiceCanceled!!!");
                    goBackMainMenu();
                  }

                  @Override
                  public void failure(RetrofitError error) {
                    hideOverlay();
                    showDialog(
                        getResources().getString(R.string.msg_serverError_title),
                        getResources().getString(R.string.msg_serverError),
                        false,
                        false);
                  }
                });
      }
    } else if (requestCode == CONSTANTS.MENU_OPTION) {
      if (data != null && data.getExtras() != null && data.getExtras().containsKey("menu_option")) {
        String menu = data.getStringExtra("menu_option");
        if (menu.equals("about") || menu.equals("terms")) {
          showInfo(menu);
        } else if (menu.equals("profile")) {
          getInfoToShow(menu);
        }
      }
    } else if (requestCode == CONSTANTS.CLOSE_SESSION) {
      if (data != null
          && data.getExtras() != null
          && data.getExtras().containsKey(CONSTANTS.CLOSE_SESSION_ST)
          && data.getExtras().getBoolean(CONSTANTS.CLOSE_SESSION_ST)) {
        onCloseSession();
        return;
      }
    } else if (requestCode == CONSTANTS.MENU_OVARLAY) {
      if (data != null
          && data.getExtras() != null
          && data.getExtras().containsKey("update")
          && data.getExtras().getBoolean("update")) {
        System.out.println("menuOvarlay");
        SharedPreferences settings =
            this.getSharedPreferences("com.fr3estudio.sherpaV3P.UsersData", Context.MODE_PRIVATE);

        // id_cliente = settings.getInt("id_cliente", 0);
        String nombre = settings.getString("nombre", "");
        String apellido = settings.getString("apellido", "");
        String email = settings.getString("email", "");
        String telefono = settings.getString("telefono", "");
        String passwd = settings.getString("passwd", "");

        ArrayList<String> param = new ArrayList<>();

        param.add(nombre);
        param.add(apellido);
        param.add(email);
        param.add(telefono);
        param.add(id_cliente + "");

        RestClient.get()
            .executeCommand(
                "6",
                param.toString(),
                new Callback<Response>() {
                  @Override
                  public void success(Response response, retrofit.client.Response response2) {

                    if (response.getStatus() == 0) {
                      hideOverlay();
                      showDialog(
                          getResources().getString(R.string.msg_title_success),
                          getResources().getString(R.string.msg_detail_infoSaved),
                          false,
                          false);

                    } else {
                      hideOverlay();
                      showDialog(
                          getResources().getString(R.string.msg_serverError_title),
                          getResources().getString(R.string.msg_detail_info_not_Saved),
                          false,
                          false);
                    }
                  }

                  @Override
                  public void failure(RetrofitError error) {
                    System.out.println("Error [" + error + "]");

                    hideOverlay();
                    showDialog(
                        getResources().getString(R.string.msg_serverError_title),
                        getResources().getString(R.string.msg_serverError),
                        false,
                        false);
                  }
                });

        if (passwd != null && !passwd.isEmpty()) {
          param = new ArrayList<>();
          param.add(passwd);
          param.add(id_cliente + "");
          RestClient.get()
              .executeCommand(
                  "18",
                  param.toString(),
                  new Callback<Response>() {
                    @Override
                    public void success(Response response, retrofit.client.Response response2) {

                      if (response.getStatus() != 0) {
                        hideOverlay();
                        showDialog(
                            getResources().getString(R.string.msg_serverError_title),
                            getResources().getString(R.string.msg_detail_info_not_Saved),
                            false,
                            false);
                      }
                    }

                    @Override
                    public void failure(RetrofitError error) {
                      System.out.println("Error [" + error + "]");

                      hideOverlay();
                      showDialog(
                          getResources().getString(R.string.msg_serverError_title),
                          getResources().getString(R.string.msg_serverError),
                          false,
                          false);
                    }
                  });
        }
      }
      if (data != null
          && data.getExtras() != null
          && data.getExtras().containsKey(CONSTANTS.CLOSE_SESSION_ST)
          && data.getExtras().getBoolean(CONSTANTS.CLOSE_SESSION_ST)) {

        onBackPressed();
        return;
      }
    } else if (requestCode == CONSTANTS.CONFIRMATION_OVARLAY) {
      if (data != null
          && data.getExtras() != null
          && data.getExtras().containsKey("confirm")
          && data.getExtras().getBoolean("confirm")) {
        onCloseSession();
      }
    }
  }