org.bouncycastle.util.Strings Java Examples

The following examples show how to use org.bouncycastle.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: TxtTablePrinter.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
private StringBuilder getColumnBlock(List<String> order, Map<String, ColumnDefinition> definitions, Locale locale) {
    Map<String, String> columns = new HashMap<>();
    for (String columnKey : order) {
        if (definitions.containsKey(columnKey)) {
            ColumnDefinition columnDefinition = definitions.get(columnKey);
            String translationKey = columnDefinition.getTranslationKey();
            String defaultColumnName = columnDefinition.getValue();
            String columnName = I18nString.getLocaleStringOrDefault(translationKey, locale, defaultColumnName);
            String capitalizedColumnName = Strings.toUpperCase(columnName);
            columns.put(columnKey, capitalizedColumnName);

            // in case of translated column title bigger then column width we need to increase the width
            if (columnName.length() > columnDefinition.getWidth()) {
                columnDefinition.setWidth(columnName.length());
            }
        }
    }

    return getRowsBlock(order, definitions, new RowImpl(columns));
}
 
Example #2
Source File: SM2Encryptor.java    From alipay-sdk-java-all with Apache License 2.0 6 votes vote down vote up
private static byte[] sm2Sign(byte[] message, PrivateKey sm2PrivateKey, String sm2UserId) throws AlipayApiException {
    try {
        String userId = "1234567812345678";
        if (!StringUtils.isEmpty(sm2UserId)) {
            userId = sm2UserId;
        }
        Signature sm2SignEngine = Signature.getInstance("SM3withSM2");
        sm2SignEngine.setParameter(new SM2ParameterSpec(
                Strings.toByteArray(userId)));
        sm2SignEngine.initSign(sm2PrivateKey);
        sm2SignEngine.update(message);
        return sm2SignEngine.sign();
    } catch (Exception e) {
        AlipayLogger.logBizError(e);
        throw new AlipayApiException(e);
    }
}
 
Example #3
Source File: SM2Encryptor.java    From alipay-sdk-java-all with Apache License 2.0 6 votes vote down vote up
private static boolean sm2Verify(byte[] signature, byte[] message, PublicKey publicKey, String sm2UserId) {
    try {
        String userId = "1234567812345678";
        if (!StringUtils.isEmpty(sm2UserId)) {
            userId = sm2UserId;
        }
        Signature sm2SignEngine = Signature.getInstance("SM3withSM2");
        sm2SignEngine.setParameter(new SM2ParameterSpec(Strings.toByteArray(userId)));
        sm2SignEngine.initVerify(publicKey);
        sm2SignEngine.update(message);
        return sm2SignEngine.verify(signature);
    } catch (Exception e) {
        AlipayLogger.logBizError(e);
        return false;
    }
}
 
Example #4
Source File: ZipPackagerTest.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    fileSystem = Jimfs.newFileSystem(Configuration.unix());
    workingDir = fileSystem.getPath("/wd");
    Path f1 = workingDir.resolve("f1");
    Path f2 = workingDir.resolve("f2");
    Path f3 = workingDir.resolve("f3.gz");
    try {
        Files.createDirectories(workingDir);
        try (BufferedWriter f1Writer = Files.newBufferedWriter(f1, StandardCharsets.UTF_8);
             BufferedWriter f2Writer = Files.newBufferedWriter(f2, StandardCharsets.UTF_8);
             OutputStream f3Writer = new GZIPOutputStream(Files.newOutputStream(f3))) {
            f1Writer.write("foo");
            f2Writer.write("bar");
            f3Writer.write(Strings.toByteArray("hello"));
        }
    } catch (IOException e) {
        fail();
    }
}
 
Example #5
Source File: Encryptor.java    From jpgpj with MIT License 6 votes vote down vote up
protected int estimateOutFileSize(long inFileSize) {
    int maxBufSize = getMaxFileBufferSize();
    if (inFileSize >= maxBufSize) return maxBufSize;

    // start with size of original input file
    long outFileSize = inFileSize;
    // then add ~500 bytes for each key, plus ~500 for misc pgp headers
    outFileSize += (
        getRing().getEncryptionKeys().size() +
        getRing().getSigningKeys().size() + 1
    ) * 512;

    if (isAsciiArmored()) {
        outFileSize *=
            // multiply by 4/3 for base64 encoding
            (4f / 3) *
            // and 65/64 (or 66/64) for line feed every 64 (encoded) chars
            ((64f + Strings.lineSeparator().length()) / 64);
        // then add ~80 chars for armor headers/trailers
        outFileSize += 80;
    }

    return (int) Math.min(outFileSize, maxBufSize);
}
 
Example #6
Source File: IstioExecutor.java    From istio-apim with Apache License 2.0 5 votes vote down vote up
/**
 * Create HTTPAPISpecBinding for the API
 *
 * @param apiName  Name of the API
 * @param endPoint Endpoint of the API
 */
public void createHttpAPISpecBinding(String apiName, String endPoint) {

    NonNamespaceOperation<HTTPAPISpecBinding, HTTPAPISpecBindingList, DoneableHTTPAPISpecBinding,
            io.fabric8.kubernetes.client.dsl.Resource<HTTPAPISpecBinding, DoneableHTTPAPISpecBinding>> bindingClient
            = client.customResource(httpAPISpecBindingCRD, HTTPAPISpecBinding.class, HTTPAPISpecBindingList.class,
            DoneableHTTPAPISpecBinding.class).inNamespace(appNamespace);

    String bindingName = Strings.toLowerCase(apiName) + "-binding";
    String apiSpecName = Strings.toLowerCase(apiName) + "-apispec";

    HTTPAPISpecBinding httpapiSpecBinding = new HTTPAPISpecBinding();
    ObjectMeta metadata = new ObjectMeta();
    metadata.setName(bindingName);
    httpapiSpecBinding.setMetadata(metadata);
    HTTPAPISpecBindingSpec httpapiSpecBindingSpec = new HTTPAPISpecBindingSpec();

    APISpec apiSpec = new APISpec();
    apiSpec.setName(apiSpecName);
    apiSpec.setNamespace(appNamespace);
    ArrayList<APISpec> apiSpecsList = new ArrayList<>();
    apiSpecsList.add(apiSpec);
    httpapiSpecBindingSpec.setApi_specs(apiSpecsList);

    Service service = new Service();
    service.setName(endPoint);
    service.setNamespace(appNamespace);
    ArrayList<Service> servicesList = new ArrayList<>();
    servicesList.add(service);
    httpapiSpecBindingSpec.setServices(servicesList);
    httpapiSpecBinding.setSpec(httpapiSpecBindingSpec);

    bindingClient.createOrReplace(httpapiSpecBinding);
    log.info("[HTTPAPISpecBinding] " + bindingName + " Created in the [Namespace] " + appNamespace + " for the"
            + " [API] " + apiName);
}
 
Example #7
Source File: IstioExecutor.java    From istio-apim with Apache License 2.0 5 votes vote down vote up
/**
 * Create Mixer rule for the API
 *
 * @param apiName     Name of the API
 * @param serviceName Istio service name
 */
private void createRule(String apiName, String serviceName) {

    NonNamespaceOperation<Rule, RuleList, DoneableRule,
            io.fabric8.kubernetes.client.dsl.Resource<Rule, DoneableRule>> ruleCRDClient
            = client.customResource(ruleCRD, Rule.class, RuleList.class,
            DoneableRule.class).inNamespace(istioSystemNamespace);
    String ruleName = Strings.toLowerCase(apiName) + "-rule";

    Rule rule = new Rule();
    ObjectMeta metadata = new ObjectMeta();
    metadata.setName(ruleName);
    rule.setMetadata(metadata);

    Action action = new Action();
    String handlerName = "wso2-handler." + istioSystemNamespace;
    action.setHandler(handlerName);
    ArrayList<String> instances = new ArrayList<>();
    instances.add("wso2-authorization");
    instances.add("wso2-metrics");
    action.setInstances(instances);

    ArrayList<Action> actions = new ArrayList<>();
    actions.add(action);

    RuleSpec ruleSpec = new RuleSpec();
    String matchValue = "context.reporter.kind == \"inbound\" && destination.namespace == \"" + appNamespace +
            "\" && destination.service.name == \"" + serviceName + "\"";
    ruleSpec.setMatch(matchValue);
    ruleSpec.setActions(actions);
    rule.setSpec(ruleSpec);

    ruleCRDClient.createOrReplace(rule);
    log.info("[Rule] " + ruleName + " Created in the [Namespace] " + istioSystemNamespace + " for the [API] "
            + apiName);

}
 
Example #8
Source File: Asset.java    From evt4j with MIT License 5 votes vote down vote up
@NotNull
public static Asset parseFromRawBalance(String balance, @Nullable Symbol symbol) {
    String[] parts = Strings.split(balance, ' ');
    int id;
    int precision;

    if (parts.length != 2) {
        throw new IllegalArgumentException(
                String.format("Failed to parse balance: \"1.00000 S#1\" is expected, %s is passed in.", balance));
    }

    String[] balanceParts = Strings.split(parts[0], '.');

    if (balanceParts.length == 1) {
        precision = 0;
    } else if (balanceParts.length == 2) {
        precision = balanceParts[1].length();
    } else {
        throw new IllegalArgumentException(String.format(
                "Failed to parse precision in balance. A \".\" is " + "expected, \"%s\" is passed in", balance));
    }

    try {
        String[] symbolArray = Strings.split(parts[1], '#');
        id = Integer.parseInt(symbolArray[1], 10);
    } catch (Exception ex) {
        throw new InvalidFungibleBalanceException(String.format("Failed to parse symbol id %s", parts[1]), ex);
    }

    Symbol localSymbol = symbol;

    if (symbol == null) {
        localSymbol = Symbol.of(id, precision);
    }

    BigDecimal balanceInFloat = new BigDecimal(parts[0]);

    return Asset.of(localSymbol, balanceInFloat);
}
 
Example #9
Source File: ElasticSearchNodeIntegrationTest.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
@Test(groups = {"Integration"})
public void testDocumentCount() throws URISyntaxException {
    elasticSearchNode = app.createAndManageChild(EntitySpec.create(ElasticSearchNode.class));
    app.start(ImmutableList.of(testLocation));
    
    EntityAsserts.assertAttributeEqualsEventually(elasticSearchNode, Startable.SERVICE_UP, true);
    
    EntityAsserts.assertAttributeEquals(elasticSearchNode, ElasticSearchNode.DOCUMENT_COUNT, 0);
    
    String baseUri = "http://" + elasticSearchNode.getAttribute(Attributes.HOSTNAME) + ":" + elasticSearchNode.getAttribute(Attributes.HTTP_PORT);
    
    HttpToolResponse pingResponse = HttpTool.execAndConsume(
            HttpTool.httpClientBuilder().build(),
            new HttpGet(baseUri));
    assertEquals(pingResponse.getResponseCode(), 200);
    
    String document = "{\"foo\" : \"bar\",\"baz\" : \"quux\"}";
    
    HttpToolResponse putResponse = HttpTool.httpPut(
            HttpTool.httpClientBuilder()
                .port(elasticSearchNode.getAttribute(Attributes.HTTP_PORT))
                .build(), 
            new URI(baseUri + "/mydocuments/docs/1"), 
            ImmutableMap.<String, String>of(), 
            Strings.toByteArray(document)); 
    assertEquals(putResponse.getResponseCode(), 201);
    
    HttpToolResponse getResponse = HttpTool.execAndConsume(
            HttpTool.httpClientBuilder().build(),
            new HttpGet(baseUri + "/mydocuments/docs/1/_source"));
    assertEquals(getResponse.getResponseCode(), 200);
    assertEquals(HttpValueFunctions.jsonContents("foo", String.class).apply(getResponse), "bar");
    
    EntityAsserts.assertAttributeEqualsEventually(elasticSearchNode, ElasticSearchNode.DOCUMENT_COUNT, 1);
}
 
Example #10
Source File: HttpExecutorImplTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testHttpPasswordRequest() throws Exception {
    MockResponse firstServerResponse = new MockResponse().setResponseCode(401).addHeader("WWW-Authenticate", "Basic realm=\"User Visible Realm\"").setBody("Not Authenticated");
    server.enqueue(firstServerResponse);
    MockResponse secondServerResponse = new MockResponse().setResponseCode(200).addHeader(HTTP_RESPONSE_HEADER_KEY, HTTP_RESPONSE_HEADER_VALUE).setBody(HTTP_BODY);
    server.enqueue(secondServerResponse);
    final String USER = "brooklyn",
            PASSWORD = "apache";
    String authUnencoded = USER + ":" + PASSWORD;
    String authEncoded = Base64.encodeBase64String(Strings.toByteArray(authUnencoded));
    HttpExecutor executor = factory.getHttpExecutor(getProps());
    HttpRequest executorRequest = new HttpRequest.Builder().headers(ImmutableMap.of("RequestHeader", "RequestHeaderValue"))
            .method("GET")
            .uri(baseUrl.toURI())
            .credentials(new UsernamePassword("brooklyn", "apache"))
            .build();
    HttpResponse executorResponse = executor.execute(executorRequest);

    RecordedRequest recordedFirstRequest = server.takeRequest();
    RecordedRequest recordedSecondRequest = server.takeRequest();

    assertRequestAndResponse(recordedFirstRequest,
            firstServerResponse,
            executorRequest,
            new HttpResponse.Builder()
                    .header("WWW-Authenticate", "Basic realm=\"User Visible Realm\"")
                    .header("Content-Length", "" + "Not Authenticated".length())
                    .content("Not Authenticated".getBytes())
                    .build());
    ArrayListMultimap newHeaders = ArrayListMultimap.create(executorRequest.headers());
    newHeaders.put("Authorization", "Basic " + authEncoded);
    assertRequestAndResponse(recordedSecondRequest,
            secondServerResponse,
            new HttpRequest.Builder().from((HttpRequestImpl)executorRequest).headers(newHeaders).build(),
            executorResponse);
}
 
Example #11
Source File: RecordBatchSizer.java    From Bats with Apache License 2.0 4 votes vote down vote up
private ColumnSize getComplexColumn(String path) {
  String[] segments = Strings.split(path, '.');
  Map<String, ColumnSize> map = columnSizes;
  return getComplexColumnImpl(segments, 0, map);
}
 
Example #12
Source File: IstioExecutor.java    From istio-apim with Apache License 2.0 4 votes vote down vote up
/**
 * Create HTTPAPISpec for the API
 *
 * @param apiName        Name of the API
 * @param apiContext     Context of the API
 * @param apiVersion     Version of the API
 * @param uriTemplates   URI templates of the API
 * @param resourceScopes Scopes of the resources of the API
 */
public void createHTTPAPISpec(String apiName, String apiContext, String apiVersion, Set<URITemplate> uriTemplates,
                              HashMap<String, String> resourceScopes) {

    NonNamespaceOperation<HTTPAPISpec, HTTPAPISpecList, DoneableHTTPAPISpec,
            io.fabric8.kubernetes.client.dsl.Resource<HTTPAPISpec, DoneableHTTPAPISpec>> apiSpecClient
            = client.customResource(httpAPISpecCRD, HTTPAPISpec.class, HTTPAPISpecList.class,
            DoneableHTTPAPISpec.class).inNamespace(appNamespace);

    String apiSpecName = Strings.toLowerCase(apiName) + "-apispec";

    HTTPAPISpec httpapiSpec = new HTTPAPISpec();
    ObjectMeta metadata = new ObjectMeta();
    metadata.setName(apiSpecName);
    httpapiSpec.setMetadata(metadata);

    HTTPAPISpecSpec httpapiSpecSpec = new HTTPAPISpecSpec();
    Map<String, Map<String, String>> attributeList = new HashMap<>();

    Map<String, String> apiService = new HashMap<>();
    apiService.put("stringValue", apiName);
    attributeList.put("api.service", apiService);

    Map<String, String> apiContextValue = new HashMap<>();
    apiContextValue.put("stringValue", apiContext);
    attributeList.put("api.context", apiContextValue);

    Map<String, String> apiVersionValue = new HashMap<>();
    apiVersionValue.put("stringValue", apiVersion);
    attributeList.put("api.version", apiVersionValue);

    Attributes attributes = new Attributes();
    attributes.setAttributes(attributeList);
    httpapiSpecSpec.setAttributes(attributes);
    httpapiSpecSpec.setPatterns(getPatterns(apiContext, apiVersion, uriTemplates, resourceScopes));
    httpapiSpec.setSpec(httpapiSpecSpec);

    apiSpecClient.createOrReplace(httpapiSpec);
    log.info("[HTTPAPISpec] " + apiSpecName + " Created in the [Namespace] " + appNamespace + " for the"
            + " [API] " + apiName);
}
 
Example #13
Source File: DevicesAdapter.java    From WIFIADB with Apache License 2.0 4 votes vote down vote up
protected void bindDevice(Device device){
    mDeviceLabel.setText(Strings.toUpperCase(device.device));
    mIdLabel.setText(Strings.toUpperCase(device.id));
}
 
Example #14
Source File: DevicesAdapter.java    From WIFIADB with Apache License 2.0 4 votes vote down vote up
@Override
protected void onBind(@Nullable Object obj) {
    mTitleLabel.setText(Strings.toUpperCase("Remote Devices"));
}
 
Example #15
Source File: DevicesAdapter.java    From WIFIADB with Apache License 2.0 4 votes vote down vote up
@Override
protected void onBind(@Nullable Object obj) {
    mTitleLabel.setText(Strings.toUpperCase("Local Devices"));
}
 
Example #16
Source File: ElasticSearchClusterIntegrationTest.java    From brooklyn-library with Apache License 2.0 4 votes vote down vote up
@Test(groups = {"Integration"})
public void testPutAndGet() throws URISyntaxException {
    elasticSearchCluster = app.createAndManageChild(EntitySpec.create(ElasticSearchCluster.class)
            .configure(DynamicCluster.INITIAL_SIZE, 3));
    app.start(ImmutableList.of(testLocation));
    
    EntityAsserts.assertAttributeEqualsEventually(elasticSearchCluster, Startable.SERVICE_UP, true);
    assertEquals(elasticSearchCluster.getMembers().size(), 3);
    assertEquals(clusterDocumentCount(), 0);
    
    ElasticSearchNode anyNode = (ElasticSearchNode)elasticSearchCluster.getMembers().iterator().next();
    
    String document = "{\"foo\" : \"bar\",\"baz\" : \"quux\"}";
    
    String putBaseUri = "http://" + anyNode.getAttribute(Attributes.HOSTNAME) + ":" + anyNode.getAttribute(Attributes.HTTP_PORT);
    
    HttpToolResponse putResponse = HttpTool.httpPut(
            HttpTool.httpClientBuilder()
                .port(anyNode.getAttribute(Attributes.HTTP_PORT))
                .build(), 
            new URI(putBaseUri + "/mydocuments/docs/1"), 
            ImmutableMap.<String, String>of(), 
            Strings.toByteArray(document)); 
    assertEquals(putResponse.getResponseCode(), 201);
    
    for (Entity entity : elasticSearchCluster.getMembers()) {
        ElasticSearchNode node = (ElasticSearchNode)entity;
        String getBaseUri = "http://" + node.getAttribute(Attributes.HOSTNAME) + ":" + node.getAttribute(Attributes.HTTP_PORT);
        HttpToolResponse getResponse = HttpTool.execAndConsume(
                HttpTool.httpClientBuilder().build(),
                new HttpGet(getBaseUri + "/mydocuments/docs/1/_source"));
        assertEquals(getResponse.getResponseCode(), 200);
        assertEquals(HttpValueFunctions.jsonContents("foo", String.class).apply(getResponse), "bar");
    }
    Asserts.succeedsEventually(new Runnable() {
        @Override
        public void run() {
            int count = clusterDocumentCount();
            assertTrue(count >= 1, "count="+count);
            LOG.debug("Document count is {}", count);
        }});
}