Java Code Examples for org.assertj.core.util.Strings

The following examples show how to use org.assertj.core.util.Strings. These examples are extracted from open source projects. 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 Project: flow-platform-x   Source File: SecretServiceTest.java    License: 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 2
Source Project: flow-platform-x   Source File: SecretServiceTest.java    License: 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 3
Source Project: tessera   Source File: PicoCliDelegateTest.java    License: 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 4
Source Project: tessera   Source File: PicoCliDelegateTest.java    License: 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 5
Source Project: flow-platform-x   Source File: SecretServiceTest.java    License: 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 6
Source Project: flow-platform-x   Source File: SecretServiceTest.java    License: 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 7
Source Project: keywhiz   Source File: BackupResourceTest.java    License: 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 8
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 9
Source Project: hedera-mirror-node   Source File: PropertiesHandler.java    License: 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 Project: hedera-mirror-node   Source File: PropertiesHandler.java    License: 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 11
Source Project: hedera-mirror-node   Source File: PropertiesHandler.java    License: 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 12
Source Project: tessera   Source File: FilesDelegateTest.java    License: 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 13
Source Project: azure-cosmosdb-java   Source File: OfferQueryTest.java    License: 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 14
Source Project: eagle   Source File: ConsoleIndex.java    License: 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 15
Source Project: eagle   Source File: InterfaceApiServiceImpl.java    License: 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 16
Source Project: eagle   Source File: InterfaceApiServiceImpl.java    License: 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 17
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 18
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 19
Source Project: armeria   Source File: AuthServiceTest.java    License: 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 20
Source Project: jackson-jaxrs-propertyfiltering   Source File: BaseTest.java    License: 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 21
Source Project: cloudbreak   Source File: SdxDatabaseDrServiceTest.java    License: 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 22
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 23
Source Project: pazuzu-registry   Source File: AbstractComponentTest.java    License: 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 24
Source Project: assertj-android   Source File: BitmaskUtils.java    License: Apache License 2.0 4 votes vote down vote up
public String get() {
  if (value == 0) {
    return "none";
  }
  return Strings.join(parts.values()).with(", ");
}