@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());
  }
  @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());
  }
  public void testProcessDir() throws IOException {
    RestClient restClient = new RestClient();
    final AtomicInteger ok = new AtomicInteger();

    restClient.setListener(
        (File src, String error, Query q) -> {
          if (q.getState() == State.SUCCESS) ok.incrementAndGet();
        });

    File google = new File("google.query");
    File yandex = new File("yandex.query");
    File googleResponse = new File("google.response");
    File yandexResponse = new File("yandex.response");
    prepareQueries(google, yandex);

    googleResponse.delete();
    yandexResponse.delete();

    boolean result = !googleResponse.exists() && !yandexResponse.exists();

    assertTrue(result);
    restClient.start();
    restClient.processDir(null);
    restClient.awaitFinishAndStop();
    result = googleResponse.exists() && yandexResponse.exists();

    assertTrue(ok.get() == 2);
    assertTrue(result);

    google.delete();
    yandex.delete();
    googleResponse.delete();
    yandexResponse.delete();
  }
Example #4
0
 @Test
 public void testExecuteWithLB() throws Exception {
   ConfigurationManager.getConfigInstance()
       .setProperty("allservices.ribbon." + CommonClientConfigKey.ReadTimeout, "10000");
   ConfigurationManager.getConfigInstance()
       .setProperty("allservices.ribbon." + CommonClientConfigKey.FollowRedirects, "true");
   RestClient client = (RestClient) ClientFactory.getNamedClient("allservices");
   BaseLoadBalancer lb = new BaseLoadBalancer();
   Server[] servers = new Server[] {new Server("localhost", server.getServerPort())};
   lb.addServers(Arrays.asList(servers));
   client.setLoadBalancer(lb);
   Set<URI> expected = new HashSet<URI>();
   expected.add(new URI(server.getServerPath("/")));
   Set<URI> result = new HashSet<URI>();
   HttpRequest request = HttpRequest.newBuilder().uri(new URI("/")).build();
   for (int i = 0; i < 5; i++) {
     HttpResponse response = client.executeWithLoadBalancer(request);
     assertStatusIsOk(response.getStatus());
     assertTrue(response.isSuccess());
     String content = response.getEntity(String.class);
     response.close();
     assertFalse(content.isEmpty());
     result.add(response.getRequestedURI());
   }
   assertEquals(expected, result);
   request = HttpRequest.newBuilder().uri(server.getServerURI()).build();
   HttpResponse response = client.executeWithLoadBalancer(request);
   assertEquals(200, response.getStatus());
 }
  /*
                                            _
   _ __   __ _ _ __ ___   ___    ___  _ __ | |_   _
  | '_ \ / _` | '_ ` _ \ / _ \  / _ \| '_ \| | | | |
  | | | | (_| | | | | | |  __/ | (_) | | | | | |_| |
  |_| |_|\__,_|_| |_| |_|\___|  \___/|_| |_|_|\__, |
                                              |___/

   */
  @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);
  }
  public static Long getProjectIdByName(String projectName, RestClient restClient) {

    Long projectId = 0L;

    HttpResponse response = null;
    try {
      response =
          restClient
              .getHttpclient()
              .execute(
                  new HttpGet(
                      restClient.getUrl()
                          + "/flex/services/rest/latest/project?name="
                          + URLEncoder.encode(projectName, "utf-8")),
                  restClient.getContext());
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    int statusCode = response.getStatusLine().getStatusCode();

    if (statusCode >= 200 && statusCode < 300) {
      HttpEntity entity = response.getEntity();
      String string = null;
      try {
        string = EntityUtils.toString(entity);
      } catch (ParseException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }

      try {
        JSONArray projArray = new JSONArray(string);
        List<Long> projectIdList = new ArrayList<Long>();
        for (int i = 0; i < projArray.length(); i++) {
          Long id = projArray.getJSONObject(i).getLong("id");
          projectIdList.add(id);
        }

        Collections.sort(projectIdList);
        projectId = projectIdList.get(0);

      } catch (JSONException e) {
        e.printStackTrace();
      }

    } else {
      try {
        throw new ClientProtocolException("Unexpected response status: " + statusCode);
      } catch (ClientProtocolException e) {
        e.printStackTrace();
      }
    }

    return projectId;
  }
Example #7
0
 @Test
 public void testSecureClient() throws Exception {
   ConfigurationManager.getConfigInstance().setProperty("test2.ribbon.IsSecure", "true");
   RestClient client = (RestClient) ClientFactory.getNamedClient("test2");
   HttpRequest request = HttpRequest.newBuilder().uri(server.getServerURI()).build();
   HttpResponse response = client.executeWithLoadBalancer(request);
   assertStatusIsOk(response.getStatus());
 }
  @Before
  public void setUp() throws Exception {
    initMocks(this);

    when(restClient.getUser(anyString())).thenAnswer(m -> getUserWithSleepTime());
    when(restClient.getFollowers(anyString())).thenAnswer(m -> getFollowersWithSleepTime());
    when(restClient.getRepositories(anyString())).then(m -> getReposWithSleepTime());
  }
Example #9
0
 @Test
 public void testExecuteWithoutLB() throws Exception {
   RestClient client = (RestClient) ClientFactory.getNamedClient("google");
   HttpRequest request = HttpRequest.newBuilder().uri(server.getServerURI()).build();
   HttpResponse response = client.executeWithLoadBalancer(request);
   assertStatusIsOk(response.getStatus());
   response = client.execute(request);
   assertStatusIsOk(response.getStatus());
 }
Example #10
0
 /** false is bu default so we test positive case only */
 @Test
 public void testDelete() throws Exception {
   RestClient restClient = mock(RestClient.class);
   URI uri = new URI("DUMMY");
   when(restClient.buildURI(anyString(), any(Map.class))).thenReturn(uri);
   when(restClient.delete(eq(uri))).thenReturn(null);
   Issue issue = new Issue(restClient, Utils.getTestIssue());
   Assert.assertTrue(issue.delete(true));
 }
  @Test
  public void testListEmployeeUrl() throws Exception {

    RestClient client = new RestClient("http://localhost:8080");

    String messageDeErro = "O valor do endpoint list employee é diferente do esperado";

    String valorEsperadoReviewList = "http://localhost:8080" + "/" + "/review/list";

    assertEquals(messageDeErro, valorEsperadoReviewList, client.endpointListReview());
  }
Example #12
0
        public void run() {

          while (false == stopThread) {
            if (true == requestToSendAuthHttp) {
              // send HTTP request here
              // Send Auth request to server here
              {
                Log.d("Anoop", "Connecting to HTTP server");

                // TODO: Add HTTP URL here
                try {
                  httpRestClient = new RestClient("http://192.241.136.52:5000/project/create");
                } catch (Exception e) {
                  e.printStackTrace();
                  Log.d("Anoop", "Unable to connect to HTTP server");
                  return;
                }

                Log.d("Anoop", "httpRestClient object " + httpRestClient);

                httpRestClient.AddParam("name", "Anoop");

                try {
                  httpRestClient.Execute(RequestMethod.POST);
                } catch (Exception e) {

                  Log.d("Anoop", "Fatal Unable to send HTTP POST Request " + httpRestClient);

                  e.printStackTrace();
                }

                Log.d("Anoop", "Done... with connection to HTTP server");
              }

              // Obtain ID from the server
              {
                httpResponse = httpRestClient.getResponse();

                Log.d("Anoop", "Response from HTTP server " + httpResponse);
              }

              requestToSendAuthHttp = false;
            }

            try {
              sleep(100);

            } catch (Exception e) {
              e.printStackTrace();
              Log.d("Anoop", "Sleeping for 100 ms ");
            }
          }
          ;
        }
Example #13
0
 @Test
 public void testVipAsURI() throws Exception {
   ConfigurationManager.getConfigInstance()
       .setProperty("test1.ribbon.DeploymentContextBasedVipAddresses", server.getServerPath("/"));
   ConfigurationManager.getConfigInstance()
       .setProperty("test1.ribbon.InitializeNFLoadBalancer", "false");
   RestClient client = (RestClient) ClientFactory.getNamedClient("test1");
   assertNull(client.getLoadBalancer());
   HttpRequest request = HttpRequest.newBuilder().uri(new URI("/")).build();
   HttpResponse response = client.executeWithLoadBalancer(request);
   assertStatusIsOk(response.getStatus());
   assertEquals(server.getServerPath("/"), response.getRequestedURI().toString());
 }
Example #14
0
        public void run() {

          while (false == stopPerThread) {
            if (true == requestToSendLatHttp) {
              // send HTTP request here
              // Send Auth request to server here
              {
                Log.d("Anoop", "Sending Latlong to HTTP server");

                httpRestClient = new RestClient("http://192.241.136.52:5000/location/create");

                if (null == httpRestClient) {
                  //							txtLat.setText("Error in connecting to server");
                  //							Log.d("Anoop", "Error in connecting to server");
                  //							return;
                }

                Log.d("Anoop", "Adding parameters to the HTTP Request");

                httpRestClient.AddParam("project_id", httpResponse);
                httpRestClient.AddParam("latitude", Double.toString(currLocation.getLatitude()));
                httpRestClient.AddParam("longitude", Double.toString(currLocation.getLongitude()));

                try {
                  //							txtLat.setText("Sending HTTP request");
                  Log.d("Anoop", "Sending HTTP request");
                  httpRestClient.Execute(RequestMethod.POST);
                } catch (Exception e) {
                  e.printStackTrace();
                }
              }

              // Obtain junk from the server
              {
                httpResponseLat = httpRestClient.getResponse();
                Log.d("Anoop", "Response from HTTP server " + httpResponseLat);
              }

              requestToSendLatHttp = false;
            }

            try {
              sleep(100);

            } catch (Exception e) {
              e.printStackTrace();
              Log.d("Anoop", "Sleeping for 100 ms ");
            }
          }
          ;
        }
  @Test
  public void testListEmployeeUrl() throws Exception {

    RestClient clientBuyer = new RestClient("http://localhost:8080");
    RestClient clientItem = new RestClient("http://localhost:8080");
    RestClient clientSeller = new RestClient("http://localhost:8080");
    RestClient clientSupplier = new RestClient("http://localhost:8080");

    String endpointListBuyer = clientBuyer.endpointListBuyer();
    String endpointListItem = clientItem.endpointListItem();
    String endpointListSeller = clientSeller.endpointListSeller();
    String endpointListSupplier = clientSupplier.endpointListSupplier();

    String messageDeErro = "O valor do endpoint list employee é diferente do esperado";
    String valorEsperadoBuyer = "http://localhost:8080" + "/" + "/buyer/list";
    String valorEsperadoItem = "http://localhost:8080" + "/" + "/item/list";
    String valorEsperadoSeller = "http://localhost:8080" + "/" + "/setler/list";
    String valorEsperadoSupplier = "http://localhost:8080" + "/" + "/supplier/list";

    assertEquals(messageDeErro, valorEsperadoSupplier, endpointListSupplier);

    assertEquals(messageDeErro, valorEsperadoSeller, endpointListSeller);

    assertEquals(messageDeErro, valorEsperadoItem, endpointListItem);

    assertEquals(messageDeErro, valorEsperadoBuyer, endpointListBuyer);
  }
  private static void handleShortcut(final ShortcutItem sc) {
    String type = sc.getType();

    if (type.equals(ShortcutType.OPEN_REQUEST.toString())) {
      RestClient.getClientFactory().getPlaceController().goTo(new SavedPlace("default"));
    } else if (type.equals(ShortcutType.SAVE_REQUEST.toString())) {
      eventBus.fireEvent(new SaveRequestEvent());
    } else if (type.equals(ShortcutType.SEND_REQUEST.toString())) {
      eventBus.fireEvent(new RequestStartActionEvent(new Date()));
    } else if (type.equals(ShortcutType.HISTORY_TAB.toString())) {
      RestClient.getClientFactory().getPlaceController().goTo(new HistoryPlace("default"));
    }
    GoogleAnalytics.sendEvent("Shortcats usage", "Shortcat used", type);
    GoogleAnalyticsApp.sendEvent("Shortcats usage", "Shortcat used", type);
  }
  /**
   * 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());
    }
  }
  /**
   * 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));
 }
  /**
   * 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());
    }
  }
  /**
   * Create Fast Track Package.
   *
   * @param packageId The id of the package to start FastTrack
   * @param signers The signers to get the signing url
   * @return The signing url
   */
  public String startFastTrack(PackageId packageId, List<FastTrackSigner> signers) {
    String token = getFastTrackToken(packageId, true);
    String path =
        template.urlFor(UrlTemplate.START_FAST_TRACK_PATH).replace("{token}", token).build();

    List<FastTrackRole> roles = new ArrayList<FastTrackRole>();
    for (FastTrackSigner signer : signers) {
      FastTrackRole role =
          FastTrackRoleBuilder.newRoleWithId(signer.getId())
              .withName(signer.getId())
              .withSigner(signer)
              .build();
      roles.add(role);
    }

    String json = Serialization.toJson(roles);
    try {
      String response = client.post(path, json);
      SigningUrl signingUrl = Serialization.fromJson(response, SigningUrl.class);
      return signingUrl.getUrl();
    } catch (RequestException e) {
      throw new EslException("Could not start fast track.", e);
    } catch (Exception e) {
      throw new EslException("Could not start fast track." + " Exception: " + e.getMessage());
    }
  }
  protected void onHandleIntent(Intent intent) {
    Log.d(TAG, "onHandleIntent");
    if (intent.getBooleanExtra("dismiss", false)) {
      // Case 1: Dismiss intent
      intent.getIntExtra("notification_id", 1);
      cancelNotification();
      stopForeground(true);
      stopSelf(mServiceId);
    } else {
      // Case 2: Initialization for intent calls (ie: called from long pressing a departure)
      // Restriction: only one alarm can be set right now
      cancelNotification();
      mStopIdString = intent.getStringExtra("current_stop");
      mStopName = intent.getStringExtra("stop_name");
      mVehicleIdString = intent.getLongExtra("unique_id", 1);
      timeToRingAlarm = intent.getIntExtra("alarm_time", 5);
      mRestClient.getDeparturesByStop(mStopIdString, mCallback);

      // Log metrics because I'm a sucker for data
      Answers.getInstance()
          .logContentView(
              new ContentViewEvent()
                  .putContentName("NotificationAlarm")
                  .putCustomAttribute("Minutes", intent.getIntExtra("alarm_time", -1)));
    }
  }
  public ResourcePoolRead get(String id) {
    id = CommonUtil.encode(id);
    final String path = Constants.REST_PATH_RESOURCEPOOL;
    final HttpMethod httpverb = HttpMethod.GET;

    return restClient.getObject(id, ResourcePoolRead.class, path, httpverb, false);
  }
  public void delete(String id) {
    id = CommonUtil.encode(id);
    final String path = Constants.REST_PATH_RESOURCEPOOL;
    final HttpMethod httpverb = HttpMethod.DELETE;

    restClient.deleteObject(id, path, httpverb);
  }
Example #25
0
 public Observable<Void> sendData(UserSubmission userSubmission) {
   return restClient.addNewLoan(
       userSubmission.getName(),
       userSubmission.getSurname(),
       userSubmission.getDays(),
       userSubmission.getAmount(),
       userSubmission.getAmountToPay());
 }
 @Override
 protected void setCommonHeaders(HttpRequest req) {
   super.setCommonHeaders(req);
   if (filter != null) {
     req.setHeader(X_MOBC3_FILTER, filter);
     filter = null;
   }
 }
Example #27
0
  @Test
  public void testRelogin() throws IOException {
    Mockito.when(
            loginClient.login(Matchers.anyString(), Matchers.anyString(), Matchers.anyString()))
        .thenReturn(new LoginResponse(200, "JSESSIONID=B6926322AF4D8A8B9CEF3906D5735D41"));

    Connect.ConnectType connectType = restClient.connect("127.0.0.1:8443", "root", "vmware");

    Assert.assertEquals(connectType, Connect.ConnectType.SUCCESS);

    Mockito.when(
            loginClient.login(Matchers.anyString(), Matchers.anyString(), Matchers.anyString()))
        .thenReturn(new LoginResponse(200, null));

    connectType = restClient.connect("127.0.0.1:8443", "root", "vmware");

    Assert.assertEquals(connectType, Connect.ConnectType.SUCCESS);
  }
 private T parseJson(JsonTypedInput input, Class dataClass) {
   T parsedObject = null;
   try {
     parsedObject = (T) RestClient.getConverter().fromBody(input, dataClass);
   } catch (ConversionException e) {
     Log.e("Response conversion", e.getLocalizedMessage());
   }
   return parsedObject;
 }
  @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());
  }
Example #30
0
  @Test
  public void testLoginWithException() throws IOException {
    Mockito.when(
            loginClient.login(Matchers.anyString(), Matchers.anyString(), Matchers.anyString()))
        .thenThrow(new IOException("can't connect to network"));

    Connect.ConnectType connectType = restClient.connect("127.0.0.1:8443", "root", "vmware");

    Assert.assertEquals(connectType, Connect.ConnectType.ERROR);
  }