org.assertj.core.util.Strings Java Examples

The following examples show how to use org.assertj.core.util.Strings. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GridLayoutAnimationControllerAssert.java    From assertj-android with Apache License 2.0 6 votes vote down vote up
private static String directionToString(@GridLayoutAnimationControllerDirection int direction) {
  List<String> parts = new ArrayList<>();
  int horizontal = direction & DIRECTION_HORIZONTAL_MASK;
  int vertical = direction & DIRECTION_VERTICAL_MASK;
  if ((horizontal & DIRECTION_RIGHT_TO_LEFT) != 0) {
    parts.add("rightToLeft");
  } else {
    parts.add("leftToRight");
  }
  if ((vertical & DIRECTION_BOTTOM_TO_TOP) != 0) {
    parts.add("bottomToTop");
  } else {
    parts.add("topToBottom");
  }
  return Strings.join(parts).with(", ");
}
 
Example #2
Source File: SecretServiceTest.java    From flow-platform-x with Apache License 2.0 6 votes vote down vote up
@Test
public void should_create_rsa_secret() {
    Secret rsa = secretService.createRSA("hello.rsa");
    Assert.assertNotNull(rsa);
    Assert.assertEquals(Secret.Category.SSH_RSA, rsa.getCategory());
    Assert.assertEquals(sessionManager.getUserId(), rsa.getCreatedBy());
    Assert.assertNotNull(rsa.getCreatedAt());
    Assert.assertNotNull(rsa.getUpdatedAt());

    Secret loaded = secretService.get("hello.rsa");
    Assert.assertTrue(loaded instanceof RSASecret);

    RSASecret keyPair = (RSASecret) loaded;
    Assert.assertFalse(Strings.isNullOrEmpty(keyPair.getPublicKey()));
    Assert.assertFalse(Strings.isNullOrEmpty(keyPair.getPrivateKey()));
}
 
Example #3
Source File: SecretServiceTest.java    From flow-platform-x with Apache License 2.0 6 votes vote down vote up
@Test
public void should_create_auth_secret() {
    SimpleAuthPair sa = new SimpleAuthPair();
    sa.setUsername("[email protected]");
    sa.setPassword("12345");

    Secret auth = secretService.createAuth("hello.auth", sa);
    Assert.assertNotNull(auth);
    Assert.assertEquals(Secret.Category.AUTH, auth.getCategory());
    Assert.assertEquals(sessionManager.getUserId(), auth.getCreatedBy());
    Assert.assertNotNull(auth.getCreatedAt());
    Assert.assertNotNull(auth.getUpdatedAt());

    Secret loaded = secretService.get("hello.auth");
    Assert.assertTrue(loaded instanceof AuthSecret);

    AuthSecret keyPair = (AuthSecret) loaded;
    Assert.assertFalse(Strings.isNullOrEmpty(keyPair.getUsername()));
    Assert.assertFalse(Strings.isNullOrEmpty(keyPair.getPassword()));
}
 
Example #4
Source File: PicoCliDelegateTest.java    From tessera with Apache License 2.0 6 votes vote down vote up
@Test
public void withEmptyConfigOverrideAll() throws Exception {

    Path unixSocketFile = Files.createTempFile("unixSocketFile", ".ipc");
    unixSocketFile.toFile().deleteOnExit();

    Path configFile = Files.createTempFile("withEmptyConfigOverrideAll", ".json");
    configFile.toFile().deleteOnExit();
    Files.write(configFile, "{}".getBytes());
    try {
        CliResult result =
                cliDelegate.execute(
                        "-configfile",
                        configFile.toString(),
                        "-o",
                        Strings.join("unixSocketFile=", unixSocketFile.toString()).with(""),
                        "-o",
                        "encryptor.type=NACL");

        assertThat(result).isNotNull();
        failBecauseExceptionWasNotThrown(ConstraintViolationException.class);
    } catch (ConstraintViolationException ex) {
        ex.getConstraintViolations().forEach(v -> LOGGER.info("{}", v));
    }
}
 
Example #5
Source File: PicoCliDelegateTest.java    From tessera with Apache License 2.0 6 votes vote down vote up
@Test
public void overrideAlwaysSendTo() throws Exception {

    String alwaysSendToKey = "giizjhZQM6peq52O7icVFxdTmTYinQSUsvyhXzgZqkE=";

    Path configFile = createAndPopulatePaths(getClass().getResource("/sample-config.json"));
    CliResult result = null;
    try {
        result =
                cliDelegate.execute(
                        "-configfile",
                        configFile.toString(),
                        "-o",
                        Strings.join("alwaysSendTo[1]=", alwaysSendToKey).with(""));
    } catch (Exception ex) {
        fail(ex.getMessage());
    }
    assertThat(result).isNotNull();
    assertThat(result.getConfig()).isPresent();
    assertThat(result.getConfig().get().getAlwaysSendTo()).hasSize(2);
    assertThat(result.getConfig().get().getAlwaysSendTo())
            .containsExactly("/+UuD63zItL1EbjxkKUljMgG8Z1w0AJ8pNOR4iq2yQc=", alwaysSendToKey);
}
 
Example #6
Source File: BackupResourceTest.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
@Test public void backupSuccess() throws Exception {
  Response httpResponse = backup("test", "Blackops");
  assertThat(httpResponse.code()).isEqualTo(200);

  InputStream ciphertext = httpResponse.body().byteStream();
  ByteArrayOutputStream plaintext = new ByteArrayOutputStream();

  Key key = new Key(TEST_EXPORT_KEY_PRIVATE, "password");

  // Decrypt and make sure we have expected data in the encrypted backup
  Decryptor decryptor = new Decryptor(key);
  decryptor.setVerificationRequired(false);
  decryptor.decrypt(ciphertext, plaintext);

  List<SecretDeliveryResponse> output = mapper.readValue(
      plaintext.toByteArray(),
      new TypeReference<List<SecretDeliveryResponse>>() {});

  assertThat(output)
      .extracting(SecretDeliveryResponse::getName)
      .containsExactlyInAnyOrder("Hacking_Password", "General_Password");

  assertThat(output)
      .extracting(SecretDeliveryResponse::getSecret)
      .allMatch(s -> !Strings.isNullOrEmpty(s));
}
 
Example #7
Source File: SecretServiceTest.java    From flow-platform-x with Apache License 2.0 6 votes vote down vote up
@Test
public void should_create_auth_secret() {
    SimpleAuthPair sa = new SimpleAuthPair();
    sa.setUsername("[email protected]");
    sa.setPassword("12345");

    Secret auth = secretService.createAuth("hello.auth", sa);
    Assert.assertNotNull(auth);
    Assert.assertEquals(Secret.Category.AUTH, auth.getCategory());
    Assert.assertEquals(sessionManager.getUserEmail(), auth.getCreatedBy());
    Assert.assertNotNull(auth.getCreatedAt());
    Assert.assertNotNull(auth.getUpdatedAt());

    Secret loaded = secretService.get("hello.auth");
    Assert.assertTrue(loaded instanceof AuthSecret);

    AuthSecret keyPair = (AuthSecret) loaded;
    Assert.assertFalse(Strings.isNullOrEmpty(keyPair.getUsername()));
    Assert.assertFalse(Strings.isNullOrEmpty(keyPair.getPassword()));
}
 
Example #8
Source File: SecretServiceTest.java    From flow-platform-x with Apache License 2.0 6 votes vote down vote up
@Test
public void should_create_rsa_secret() {
    Secret rsa = secretService.createRSA("hello.rsa");
    Assert.assertNotNull(rsa);
    should_has_db_info(rsa);

    Assert.assertEquals(Secret.Category.SSH_RSA, rsa.getCategory());
    Assert.assertEquals(sessionManager.getUserEmail(), rsa.getCreatedBy());
    Assert.assertNotNull(rsa.getCreatedAt());
    Assert.assertNotNull(rsa.getUpdatedAt());

    Secret loaded = secretService.get("hello.rsa");
    Assert.assertTrue(loaded instanceof RSASecret);

    RSASecret secret = (RSASecret) loaded;
    Assert.assertFalse(Strings.isNullOrEmpty(secret.getPublicKey()));
    Assert.assertFalse(Strings.isNullOrEmpty(secret.getPrivateKey()));
    Assert.assertNotNull(secret.getMd5Fingerprint());
}
 
Example #9
Source File: PropertiesHandler.java    From hedera-mirror-node with Apache License 2.0 5 votes vote down vote up
public Long getLongTestParam(String property, Long defaultVal) {
    String value = getTestParam(property);

    if (Strings.isNullOrEmpty(value)) {
        return defaultVal;
    }

    return Long.parseLong(value);
}
 
Example #10
Source File: SdxDatabaseDrServiceTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setup() {
    if (Strings.isNullOrEmpty(ThreadBasedUserCrnProvider.getUserCrn())) {
        ThreadBasedUserCrnProvider.setUserCrn(USER_CRN);
    }
    flowIdentifier = new FlowIdentifier(FlowType.FLOW, POLLABLE_ID);
}
 
Example #11
Source File: BaseTest.java    From jackson-jaxrs-propertyfiltering with Apache License 2.0 5 votes vote down vote up
protected <T> T getObjects(TypeReference<T> typeReference, String path, String queryParamName, String... queryParams) throws IOException {
  String urlString = "http://localhost:" + port + "/test" + path;
  if (queryParams.length > 0) {
    urlString += "?" + queryParamName + "=" + Strings.join(queryParams).with("&" + queryParamName + "=");
  }

  URL url = new URL(urlString);

  return reader.forType(typeReference).readValue(url.openStream());
}
 
Example #12
Source File: AuthServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static HttpRequestBase oauth1aGetRequest(
        String path, OAuth1aToken oAuth1aToken, AsciiString header) {
    final HttpGet request = new HttpGet(server.httpUri().resolve(path));
    final StringBuilder authorization = new StringBuilder("OAuth ");
    final String realm = oAuth1aToken.realm();
    if (!Strings.isNullOrEmpty(realm)) {
        authorization.append("realm=\"");
        authorization.append(realm);
        authorization.append("\",");
    }
    authorization.append("oauth_consumer_key=\"");
    authorization.append(oAuth1aToken.consumerKey());
    authorization.append("\",oauth_token=\"");
    authorization.append(oAuth1aToken.token());
    authorization.append("\",oauth_signature_method=\"");
    authorization.append(oAuth1aToken.signatureMethod());
    authorization.append("\",oauth_signature=\"");
    authorization.append(oAuth1aToken.signature());
    authorization.append("\",oauth_timestamp=\"");
    authorization.append(oAuth1aToken.timestamp());
    authorization.append("\",oauth_nonce=\"");
    authorization.append(oAuth1aToken.nonce());
    authorization.append("\",version=\"");
    authorization.append(oAuth1aToken.version());
    authorization.append('"');
    for (Entry<String, String> entry : oAuth1aToken.additionals().entrySet()) {
        authorization.append("\",");
        authorization.append(entry.getKey());
        authorization.append("=\"");
        authorization.append(entry.getValue());
        authorization.append('"');
    }
    request.addHeader(header.toString(), authorization.toString());
    return request;
}
 
Example #13
Source File: KubernetesDiscoveryClientFilterMetadataTest.java    From spring-cloud-kubernetes with Apache License 2.0 5 votes vote down vote up
private List<EndpointPort> getEndpointPorts(Map<Integer, String> ports) {
	return ports.entrySet().stream().map(e -> {
		EndpointPortBuilder endpointPortBuilder = new EndpointPortBuilder();
		endpointPortBuilder.withPort(e.getKey());
		if (!Strings.isNullOrEmpty(e.getValue())) {
			endpointPortBuilder.withName(e.getValue());
		}
		return endpointPortBuilder.build();
	}).collect(toList());
}
 
Example #14
Source File: KubernetesDiscoveryClientFilterMetadataTest.java    From spring-cloud-kubernetes with Apache License 2.0 5 votes vote down vote up
private List<ServicePort> getServicePorts(Map<Integer, String> ports) {
	return ports.entrySet().stream().map(e -> {
		ServicePortBuilder servicePortBuilder = new ServicePortBuilder();
		servicePortBuilder.withPort(e.getKey());
		if (!Strings.isNullOrEmpty(e.getValue())) {
			servicePortBuilder.withName(e.getValue());
		}
		return servicePortBuilder.build();
	}).collect(toList());
}
 
Example #15
Source File: InterfaceApiServiceImpl.java    From eagle with Apache License 2.0 5 votes vote down vote up
@Override
public ServerServiceInfo getServerConfig(String serviceName, String protocol, String host) {
    String serverConfigJson = regCenter.getDirectly(String.format(SERVICE, serviceName, protocol, host));
    if (Strings.isNullOrEmpty(serverConfigJson)) {
        return null;
    }
    MergeConfig config = MergeConfig.decode(serverConfigJson);
    ServerServiceInfo serviceInfo = new ServerServiceInfo();
    getServiceInfo(ServerServiceInfo.class, config, serviceInfo);
    return serviceInfo;
}
 
Example #16
Source File: InterfaceApiServiceImpl.java    From eagle with Apache License 2.0 5 votes vote down vote up
@Override
public ClientServiceInfo getClientConfig(String serviceName, String protocol, String host) {
    String clientConfigJson = regCenter.getDirectly(String.format(REF, serviceName, protocol, host));
    if (Strings.isNullOrEmpty(clientConfigJson)) {
        return null;
    }
    MergeConfig config = MergeConfig.decode(clientConfigJson);
    ClientServiceInfo serviceInfo = new ClientServiceInfo();
    getServiceInfo(ClientServiceInfo.class, config, serviceInfo);
    return serviceInfo;
}
 
Example #17
Source File: ConsoleIndex.java    From eagle with Apache License 2.0 5 votes vote down vote up
@ResponseBody
@RequestMapping(value = "/user", method = RequestMethod.HEAD)
public void getLoginUser(HttpServletResponse response) {
    UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    String userName = userDetails.getUsername();
    if (Strings.isNullOrEmpty(userName)) {
        AuthenticatUtil.needAuthenticate(response);
        return;
    }
    AuthenticatUtil.authenticateSuccess(response, userName);
}
 
Example #18
Source File: OfferQueryTest.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
@Test(groups = { "emulator" }, timeOut = TIMEOUT * 100)
public void queryOffersFilterMorePages() throws Exception {
    
    List<String> collectionResourceIds = createdCollections.stream().map(c -> c.getResourceId()).collect(Collectors.toList());
    String query = String.format("SELECT * from c where c.offerResourceId in (%s)", 
            Strings.join(collectionResourceIds.stream().map(s -> "'" + s + "'").collect(Collectors.toList())).with(","));

    FeedOptions options = new FeedOptions();
    options.setMaxItemCount(1);
    Observable<FeedResponse<Offer>> queryObservable = client.queryOffers(query, options);

    List<Offer> expectedOffers = client.readOffers(null).flatMap(f -> Observable.from(f.getResults())).toList().toBlocking().single()
            .stream().filter(o -> collectionResourceIds.contains(o.getOfferResourceId()))
            .collect(Collectors.toList());

    assertThat(expectedOffers).hasSize(createdCollections.size());

    int expectedPageSize = (expectedOffers.size() + options.getMaxItemCount() - 1) / options.getMaxItemCount();

    FeedResponseListValidator<Offer> validator = new FeedResponseListValidator.Builder<Offer>()
            .totalSize(expectedOffers.size())
            .exactlyContainsInAnyOrder(expectedOffers.stream().map(d -> d.getResourceId()).collect(Collectors.toList()))
            .numberOfPages(expectedPageSize)
            .pageSatisfy(0, new FeedResponseValidator.Builder<Offer>()
                    .requestChargeGreaterThanOrEqualTo(1.0).build())
            .build();

    validateQuerySuccess(queryObservable, validator, 10000);
}
 
Example #19
Source File: FilesDelegateTest.java    From tessera with Apache License 2.0 5 votes vote down vote up
@Test
public void readAllLines() throws Exception {
    final List<String> lines = Arrays.asList("line1", "line2");
    final byte[] linesBytes = Strings.join(lines).with("\n").getBytes();

    final Path file = Files.createTempFile(UUID.randomUUID().toString(), ".txt");
    file.toFile().deleteOnExit();
    Files.write(file, linesBytes);

    final List<String> result = filesDelegate.readAllLines(file);

    assertThat(result).isEqualTo(lines);
}
 
Example #20
Source File: PropertiesHandler.java    From hedera-mirror-node with Apache License 2.0 5 votes vote down vote up
public String getClientTestParam(String property, int num, String defaultVal) {
    String retrievedValue = getTestParam(String.format(clientPattern, property, num));

    if (Strings.isNullOrEmpty(retrievedValue)) {
        return defaultVal;
    }

    return retrievedValue;
}
 
Example #21
Source File: PropertiesHandler.java    From hedera-mirror-node with Apache License 2.0 5 votes vote down vote up
public int getIntTestParam(String property, int defaultVal) {
    String value = getTestParam(property);

    if (Strings.isNullOrEmpty(value)) {
        return defaultVal;
    }

    return Integer.parseInt(value);
}
 
Example #22
Source File: AbstractComponentTest.java    From pazuzu-registry with MIT License 4 votes vote down vote up
protected String url(String... paths) {
    return "http://127.0.0.1:" + webPort + Strings.join(paths).with("/");
}
 
Example #23
Source File: ApiV2ControllerStateTransitionTest.java    From we-cmdb with Apache License 2.0 4 votes vote down vote up
private void updateCiData(int ciTypeId, String guid) throws Exception {
    // get existing description
    com.webank.cmdb.dto.QueryRequest request;
    String existingDesc = getFieldValue(ciTypeId, guid, "description", false);

    Map<?, ?> jsonMap = ImmutableMap.builder()
            .put("guid", guid)
            .put("description", "update desc new")
            .build();
    String updateJson = JsonUtil.toJson(ImmutableList.of(jsonMap));

    MvcResult updateResult = mvc.perform(post("/api/v2/ci/{ciTypeId}/update", ciTypeId).contentType(MediaType.APPLICATION_JSON)
            .content(updateJson))
            .andExpect(jsonPath("$.statusCode", is("OK")))
            .andExpect(jsonPath("$.data", hasSize(equalTo(1))))
            .andReturn();

    String updatedRet = updateResult.getResponse()
            .getContentAsString();
    JsonNode updateResultDataNode = new ObjectMapper().readTree(updatedRet)
            .get("data");
    if (updateResultDataNode.isArray()) {
        assertThat(updateResultDataNode.get(0)
                .get("description")
                .asText(), equalTo("update desc new"));
    }

    String parentGuid = JsonUtil.asNodeByPath(updatedRet, "/data/0/p_guid")
            .asText();
    if (!Strings.isNullOrEmpty(parentGuid)) {
        // compare the description from parent ci with existing description
        request = new com.webank.cmdb.dto.QueryRequest();
        request.getDialect()
                .setShowCiHistory(true);
        request.setFilters(Lists.newArrayList(new Filter("guid", FilterOperator.Equal.getCode(), parentGuid)));
        MvcResult parentResult = mvc.perform(post("/api/v2/ci/{ciTypeId}/retrieve", ciTypeId).contentType(MediaType.APPLICATION_JSON)
                .content(JsonUtil.toJson(request)))
                .andReturn();
        String parentRetContent = parentResult.getResponse()
                .getContentAsString();
        String parentDesc = JsonUtil.asNodeByPath(parentRetContent, "/data/contents/0/data/description")
                .asText();
        assertThat(parentDesc, equalTo(existingDesc));
    }

}
 
Example #24
Source File: BitmaskUtils.java    From assertj-android with Apache License 2.0 4 votes vote down vote up
public String get() {
  if (value == 0) {
    return "none";
  }
  return Strings.join(parts.values()).with(", ");
}