java.security.KeyManagementException Java Examples

The following examples show how to use java.security.KeyManagementException. 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: SslContextFactory.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a SSLContext instance using the given information.
 *
 * @param truststore the full path to the truststore
 * @param truststorePasswd the truststore password
 * @param truststoreType the type of truststore (e.g., PKCS12, JKS)
 * @param protocol the protocol to use for the SSL connection
 *
 * @return a SSLContext instance
 * @throws java.security.KeyStoreException if any issues accessing the keystore
 * @throws java.io.IOException for any problems loading the keystores
 * @throws java.security.NoSuchAlgorithmException if an algorithm is found to be used but is unknown
 * @throws java.security.cert.CertificateException if there is an issue with the certificate
 * @throws java.security.UnrecoverableKeyException if the key is insufficient
 * @throws java.security.KeyManagementException if unable to manage the key
 */
public static SSLContext createTrustSslContext(
        final String truststore, final char[] truststorePasswd, final String truststoreType, final String protocol)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException, KeyManagementException {

    // prepare the truststore
    final KeyStore trustStore = KeyStoreUtils.getTrustStore(truststoreType);
    try (final InputStream trustStoreStream = new FileInputStream(truststore)) {
        trustStore.load(trustStoreStream, truststorePasswd);
    }
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);

    // initialize the ssl context
    final SSLContext ctx = SSLContext.getInstance(protocol);
    ctx.init(new KeyManager[0], trustManagerFactory.getTrustManagers(), new SecureRandom());

    return ctx;

}
 
Example #2
Source File: PushServiceSocket.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private static OkHttpClient createConnectionClient(SignalUrl url, List<Interceptor> interceptors, Optional<Dns> dns) {
  try {
    TrustManager[] trustManagers = BlacklistingTrustManager.createFor(url.getTrustStore());

    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, trustManagers, null);

    OkHttpClient.Builder builder = new OkHttpClient.Builder()
                                                   .sslSocketFactory(new Tls12SocketFactory(context.getSocketFactory()), (X509TrustManager)trustManagers[0])
                                                   .connectionSpecs(url.getConnectionSpecs().or(Util.immutableList(ConnectionSpec.RESTRICTED_TLS)))
                                                   .dns(dns.or(Dns.SYSTEM));

    builder.sslSocketFactory(new Tls12SocketFactory(context.getSocketFactory()), (X509TrustManager)trustManagers[0])
           .connectionSpecs(url.getConnectionSpecs().or(Util.immutableList(ConnectionSpec.RESTRICTED_TLS)))
           .build();

    for (Interceptor interceptor : interceptors) {
      builder.addInterceptor(interceptor);
    }

    return builder.build();
  } catch (NoSuchAlgorithmException | KeyManagementException e) {
    throw new AssertionError(e);
  }
}
 
Example #3
Source File: HttpRequestProcessor.java    From protect with MIT License 6 votes vote down vote up
public HttpRequestProcessor(final int serverIndex, final ServerConfiguration serverConfig,
		final AccessEnforcement accessEnforcement, final ConcurrentMap<String, ApvssShareholder> shareholders,
		final List<X509Certificate> caCerts, final X509Certificate hostCert, final PrivateKey privateKey,
		final KeyLoader clientKeys, final KeyLoader serverKeys)
		throws IOException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException,
		UnrecoverableKeyException, CertificateException {

	final int httpListenPort = CommonConfiguration.BASE_HTTP_PORT + serverIndex;
	this.server = HttpsServer.create(new InetSocketAddress(httpListenPort), 0);

	setupTls(caCerts, hostCert, privateKey, serverIndex);

	System.out.println("HTTPS server listening on port: " + httpListenPort);

	addHandlers(serverIndex, serverConfig, accessEnforcement, shareholders, clientKeys, serverKeys, caCerts, hostCert, privateKey);

	System.out.println("Ready to process requests.");

	// this.server.setExecutor(Executors.newFixedThreadPool(NUM_PROCESSING_THREADS));
}
 
Example #4
Source File: AndroidSslSocketFactoryFactory.java    From PresencePublisher with MIT License 6 votes vote down vote up
SSLSocketFactory getSslSocketFactory(@Nullable String clientCertAlias) {
    try {
        SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        KeyStore androidCAStore = KeyStore.getInstance("AndroidCAStore");
        if (androidCAStore == null) {
            HyperLog.w(TAG, "Unable to load CA keystore");
            return null;
        }
        androidCAStore.load(null);
        trustManagerFactory.init(androidCAStore);
        KeyManager[] keyManagers = null;
        if (clientCertAlias != null) {
            keyManagers = getClientKeyManagers(clientCertAlias);
        }
        sslContext.init(keyManagers, trustManagerFactory.getTrustManagers(), null);
        return sslContext.getSocketFactory();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException | CertificateException | IOException e) {
        HyperLog.w(TAG, "Unable to get socket factory", e);
        return null;
    }
}
 
Example #5
Source File: HttpClientWrapper.java    From TrackRay with GNU General Public License v3.0 6 votes vote down vote up
public static void enabledSSL() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE);
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", new PlainConnectionSocketFactory())
            .register("https", sslConnectionSocketFactory)
            .build();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
    cm.setMaxTotal(100);
    client = HttpClients.custom()
            .setSSLSocketFactory(sslConnectionSocketFactory)
            .setConnectionManager(cm)
            .build();
}
 
Example #6
Source File: HTTPSTrustManager.java    From styT with Apache License 2.0 6 votes vote down vote up
public static void allowAllSSL() {
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(String arg0, SSLSession arg1) {
            return true;
        }
    });

    SSLContext sslContext = null;
    if (trustManagers == null) {
        trustManagers = new TrustManager[]{new HTTPSTrustManager()};
    }

    try {
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagers, new SecureRandom());
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        e.printStackTrace();
    }
    if (sslContext != null) {
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    }
}
 
Example #7
Source File: SSLEngineFactory.java    From NetBare with MIT License 6 votes vote down vote up
private TrustManager[] getClientTrustManager() {
    try {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
                TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init((KeyStore) null);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
            throw new KeyManagementException("Unexpected default trust managers:"
                    + Arrays.toString(trustManagers));
        }
        return trustManagers;
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        NetBareLog.wtf(e);
    }
    return null;
}
 
Example #8
Source File: HttpUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the http client.
 *
 * @return the http client
 */
private static CloseableHttpClient getHttpClient() {
    CloseableHttpClient httpClient = null;
    try {
        httpClient = HttpClientBuilder.create().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                    @Override
                    public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                        return true;
                    }
                }).build()).build();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
        LOGGER.error("Error getting getHttpClient " , e);
    }
    return httpClient;
}
 
Example #9
Source File: HttpUtil.java    From pacbot with Apache License 2.0 6 votes vote down vote up
/**
 * Gets the http client.
 *
 * @return the http client
 */
private static CloseableHttpClient getHttpClient() {
    CloseableHttpClient httpClient = null;
    try {
        httpClient = HttpClientBuilder.create().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                    @Override
                    public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                        return true;
                    }
                }).build()).build();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
        LOGGER.error("Error getting getHttpClient " , e);
    }
    return httpClient;
}
 
Example #10
Source File: TLSClientPropertyTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * The parameter passed is the user enforced protocol. Does not catch
 * NoSuchAlgorithmException, WrongProperty test will use it.
 */
public void test(String expectedContextProto,
        String[] expectedDefaultProtos) throws NoSuchAlgorithmException {

    SSLContext context = null;
    try {
        if (expectedContextProto != null) {
            context = SSLContext.getInstance(expectedContextProto);
            context.init(null, null, null);
        } else {
            context = SSLContext.getDefault();
        }
        printContextDetails(context);
    } catch (KeyManagementException ex) {
        error(null, ex);
    }

    validateContext(expectedContextProto, expectedDefaultProtos, context);
}
 
Example #11
Source File: GerritChecksApiBuilder.java    From gerrit-code-review-plugin with Apache License 2.0 6 votes vote down vote up
public GerritChecksApiBuilder allowInsecureHttps() {
  try {
    SSLContext sslContext =
        new SSLContextBuilder()
            .loadTrustMaterial(
                null,
                new TrustStrategy() {
                  public boolean isTrusted(final X509Certificate[] chain, String authType)
                      throws CertificateException {
                    return true;
                  }
                })
            .build();
    SSLConnectionSocketFactory sslsf =
        new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
    clientBuilder.setSSLSocketFactory(sslsf);
  } catch (KeyStoreException | KeyManagementException | NoSuchAlgorithmException e) {
    LOGGER.log(Level.WARNING, "Could not disable SSL verification.", e);
  }
  return this;
}
 
Example #12
Source File: SSLUtils.java    From ssltest with Apache License 2.0 6 votes vote down vote up
/**
     * Creates an SSLSocketFactory that supports only the specified protocols
     * and ciphers.
     */
    public static SSLSocketFactory getSSLSocketFactory(String protocol,
                                                       String[] sslEnabledProtocols,
                                                       String[] sslCipherSuites,
                                                       SecureRandom random,
                                                       TrustManager[] tms,
                                                       KeyManager[] kms)
        throws NoSuchAlgorithmException, KeyManagementException
    {
        SSLContext sc = SSLContext.getInstance(protocol);

//        System.out.println("Wanted protocol: " + protocol);
//        System.out.println("Got protocol:    " + sc.getProtocol());

        sc.init(kms, tms, random);

        SSLSocketFactory sf = sc.getSocketFactory();

        if(null != sslEnabledProtocols
           || null != sslCipherSuites)
            sf = new CustomSSLSocketFactory(sf,
                                            sslEnabledProtocols,
                                            sslCipherSuites);

        return sf;
    }
 
Example #13
Source File: SecureSslContextFactory.java    From openAGV with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an instance of {@link SSLContext} for the client.
 *
 * @return The ssl context.
 * @throws IllegalStateException If the creation of the ssl context fails.
 */
public SSLContext createClientContext()
    throws IllegalStateException {
  SSLContext context = null;

  try {
    KeyStore ts = KeyStore.getInstance(sslParameterSet.getKeystoreType());
    ts.load(new FileInputStream(sslParameterSet.getTruststoreFile()),
            sslParameterSet.getTruststorePassword().toCharArray());
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(KEY_TRUST_MANAGEMENT_ALGORITHM);
    tmf.init(ts);

    context = SSLContext.getInstance(SSL_CONTEXT_PROTOCOL);
    context.init(null, tmf.getTrustManagers(), null);
  }
  catch (NoSuchAlgorithmException | KeyStoreException | CertificateException | IOException
             | KeyManagementException ex) {
    throw new IllegalStateException("Error creating the client's ssl context", ex);
  }

  return context;
}
 
Example #14
Source File: ClientReceive1.java    From java-study with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args)
    throws java.io.IOException,java.lang.InterruptedException, TimeoutException, KeyManagementException, NoSuchAlgorithmException, URISyntaxException{
        ConnectionFactory factory=new ConnectionFactory();
//        factory.setHost("localhost");
//        factory.setVirtualHost("my_mq");
//        factory.setUsername("zhxia");
//        factory.setPassword("123456");
        factory.setUri("amqp://guest:[email protected]:5672");//获取url
        Connection connection=factory.newConnection();
        Channel channel=connection.createChannel();
        channel.queueDeclare(queue_name, durable, false, false, null);
        System.out.println("Wait for message");
        channel.basicQos(1); //消息分发处理
        QueueingConsumer consumer=new QueueingConsumer(channel);
        channel.basicConsume(queue_name, autoAck, consumer);
        while(true){
            Thread.sleep(500);
            QueueingConsumer.Delivery deliver=consumer.nextDelivery();
            String message=new String(deliver.getBody());
            System.out.println("Message received:"+message);
            channel.basicAck(deliver.getEnvelope().getDeliveryTag(), false);
        }
    }
 
Example #15
Source File: GetHTTP.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private SSLContext createSSLContext(final SSLContextService service)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {

    final SSLContextBuilder sslContextBuilder = new SSLContextBuilder();

    if (StringUtils.isNotBlank(service.getTrustStoreFile())) {
        final KeyStore truststore = KeyStoreUtils.getTrustStore(service.getTrustStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getTrustStoreFile()))) {
            truststore.load(in, service.getTrustStorePassword().toCharArray());
        }
        sslContextBuilder.loadTrustMaterial(truststore, new TrustSelfSignedStrategy());
    }

    if (StringUtils.isNotBlank(service.getKeyStoreFile())){
        final KeyStore keystore = KeyStoreUtils.getKeyStore(service.getKeyStoreType());
        try (final InputStream in = new FileInputStream(new File(service.getKeyStoreFile()))) {
            keystore.load(in, service.getKeyStorePassword().toCharArray());
        }
        sslContextBuilder.loadKeyMaterial(keystore, service.getKeyStorePassword().toCharArray());
    }

    sslContextBuilder.useProtocol(service.getSslAlgorithm());

    return sslContextBuilder.build();
}
 
Example #16
Source File: HttpClientSteps.java    From yaks with Apache License 2.0 6 votes vote down vote up
/**
 * Get secure http client implementation with trust all strategy and noop host name verifier.
 * @return
 */
private org.apache.http.client.HttpClient sslClient() {
    try {
        SSLContext sslcontext = SSLContexts
                .custom()
                .loadTrustMaterial(TrustAllStrategy.INSTANCE)
                .build();

        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
                sslcontext, NoopHostnameVerifier.INSTANCE);

        return HttpClients
                .custom()
                .setSSLSocketFactory(sslSocketFactory)
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                .build();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        throw new CitrusRuntimeException("Failed to create http client for ssl connection", e);
    }
}
 
Example #17
Source File: DownloadCartridgeTask.java    From WhereYouGo with GNU General Public License v3.0 6 votes vote down vote up
private boolean init() {
    try {
        System.setProperty("http.keepAlive", "false");
        httpClient = new OkHttpClient.Builder()
                .sslSocketFactory(new TLSSocketFactory())
                .cookieJar(new NonPersistentCookieJar())
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .build();
    } catch (KeyManagementException | NoSuchAlgorithmException e) {
        Logger.e(TAG, "init()", e);
        errorMessage = e.getMessage();
    }
    if (httpClient == null)
        publishProgress(new Progress(Task.INIT, State.FAIL, errorMessage));
    return httpClient != null;
}
 
Example #18
Source File: HttpClientConfig.java    From Pixiv-Illustration-Collection-Backend with Apache License 2.0 6 votes vote down vote up
@Bean
    @Primary
    @Autowired
    public HttpClient httpClientWithOutProxy(TrustManager[] trustAllCertificates, ExecutorService httpclientExecutorService) throws NoSuchAlgorithmException, KeyManagementException {
        SSLParameters sslParams = new SSLParameters();
        sslParams.setEndpointIdentificationAlgorithm("");
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCertificates, new SecureRandom());
        return HttpClient.newBuilder()
                .version(HttpClient.Version.HTTP_1_1)
//                .sslParameters(sslParams)
//                .sslContext(sc)
                .connectTimeout(Duration.ofSeconds(30))
              //          .proxy(ProxySelector.of(new InetSocketAddress("127.0.0.1", 8888)))
                .executor(httpclientExecutorService)
                .followRedirects(HttpClient.Redirect.NEVER)
                .build();
    }
 
Example #19
Source File: DockerServerCredentialsSSLConfig.java    From docker-swarm-plugin with MIT License 6 votes vote down vote up
@Override
public SSLContext getSSLContext()
        throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {

    try {
        final KeyStore keyStore = CertificateUtils.createKeyStore(credentials.getClientKey(),
                credentials.getClientCertificate());
        final KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, "docker".toCharArray());
        final KeyStore trustStore = CertificateUtils.createTrustStore(credentials.getServerCaCertificate());
        final TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        final SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
        return context;
    } catch (CertificateException | InvalidKeySpecException | IOException e) {
        throw new KeyStoreException("Can't build keystore from provided client key/certificate", e);
    }
}
 
Example #20
Source File: UCHttpClient.java    From netanalysis-sdk-android with Apache License 2.0 5 votes vote down vote up
protected static SSLContext getSSLContextWithoutCer() throws NoSuchAlgorithmException, KeyManagementException {
    // 实例化SSLContext
    // 这里参数可以用TSL 也可以用SSL
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, new TrustManager[]{trustManagers}, new SecureRandom());
    return sslContext;
}
 
Example #21
Source File: MySSLSocketFactory.java    From Moss with Apache License 2.0 5 votes vote down vote up
public static SSLSocketFactory getSSLSocketFactory()
    throws KeyManagementException, NoSuchProviderException, NoSuchAlgorithmException {

    if (VI_SSL_FACTORY == null) {
        TrustManager[] tm = {new MyX509TrustManager()};
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, tm, new SecureRandom());
        VI_SSL_FACTORY = sslContext.getSocketFactory();
    }
    return VI_SSL_FACTORY;
}
 
Example #22
Source File: APIImportConfigAdapter.java    From apimanager-swagger-promote with Apache License 2.0 5 votes vote down vote up
private void addSSLContext(String uri, HttpClientBuilder httpClientBuilder) throws KeyManagementException,
		NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, UnrecoverableKeyException {
	if (isHttpsUri(uri)) {
		SSLConnectionSocketFactory sslCtx = createSSLContext();
		if (sslCtx!=null) {
			httpClientBuilder.setSSLSocketFactory(sslCtx);
		}
	}
}
 
Example #23
Source File: RMQConnectionConfigTest.java    From flink with Apache License 2.0 5 votes vote down vote up
@Test(expected = NullPointerException.class)
public void shouldThrowNullPointExceptionIfHostIsNull() throws NoSuchAlgorithmException,
	KeyManagementException, URISyntaxException {
	RMQConnectionConfig connectionConfig = new RMQConnectionConfig.Builder()
		.setPort(1000).setUserName("guest")
		.setPassword("guest").setVirtualHost("/").build();
	connectionConfig.getConnectionFactory();
}
 
Example #24
Source File: HttpTest.java    From Java-API-Test-Examples with Apache License 2.0 5 votes vote down vote up
@Test(enabled = false,description = "测试绕过SSL证书Post方法")
public void doIgnoreVerifySSLPostTest() throws IOException, NoSuchAlgorithmException, KeyManagementException {
	String url = "https://localhost/springboot/person";
	//装填参数
	JSONObject param = new JSONObject();
	param.put("name","doIgnoreVerifySSLPost");
	param.put("age",20);
	//调用方法
	String response = HttpUtil.doIgnoreVerifySSLPost(url,param);
	//断言返回结果是否为空
	Assert.assertNotNull(response);
	System.out.println("【doIgnoreVerifySSLPost】"+response);
}
 
Example #25
Source File: RMQConnectionConfigTest.java    From flink with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSetProvidedValueIfConnectionTimeoutNotGiven() throws NoSuchAlgorithmException,
	KeyManagementException, URISyntaxException {
	RMQConnectionConfig connectionConfig = new RMQConnectionConfig.Builder()
		.setHost("localhost").setPort(5000).setUserName("guest")
		.setPassword("guest").setVirtualHost("/")
		.setConnectionTimeout(5000).build();
	ConnectionFactory factory = connectionConfig.getConnectionFactory();
	assertEquals(5000, factory.getConnectionTimeout());
}
 
Example #26
Source File: HttpEventPublisherTest.java    From DataflowTemplates with Apache License 2.0 5 votes vote down vote up
@Test
public void configureBackOffDefaultTest()
    throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException {

  HttpEventPublisher publisherDefaultBackOff =
      HttpEventPublisher.newBuilder()
          .withUrl("http://example.com")
          .withToken("test-token")
          .withDisableCertificateValidation(false)
          .build();

  assertThat(
      publisherDefaultBackOff.getConfiguredBackOff().getMaxElapsedTimeMillis(),
      is(equalTo(ExponentialBackOff.DEFAULT_MAX_ELAPSED_TIME_MILLIS)));
}
 
Example #27
Source File: HttpEventPublisher.java    From DataflowTemplates with Apache License 2.0 5 votes vote down vote up
/**
 * Validates and builds a {@link HttpEventPublisher} object.
 *
 * @return {@link HttpEventPublisher}
 */
public HttpEventPublisher build()
    throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {

  checkNotNull(token(), "Authentication token needs to be specified via withToken(token).");
  checkNotNull(genericUrl(), "URL needs to be specified via withUrl(url).");

  if (disableCertificateValidation() == null) {
    LOG.info("Certificate validation disabled: {}", DEFAULT_DISABLE_CERTIFICATE_VALIDATION);
    setDisableCertificateValidation(DEFAULT_DISABLE_CERTIFICATE_VALIDATION);
  }

  if (maxElapsedMillis() == null) {
    LOG.info(
        "Defaulting max backoff time to: {} milliseconds ",
        ExponentialBackOff.DEFAULT_MAX_ELAPSED_TIME_MILLIS);
    setMaxElapsedMillis(ExponentialBackOff.DEFAULT_MAX_ELAPSED_TIME_MILLIS);
  }

  CloseableHttpClient httpClient =
      getHttpClient(DEFAULT_MAX_CONNECTIONS, disableCertificateValidation());

  setTransport(new ApacheHttpTransport(httpClient));
  setRequestFactory(transport().createRequestFactory());

  return autoBuild();
}
 
Example #28
Source File: DavGatewaySSLProtocolSocketFactory.java    From davmail with GNU General Public License v2.0 5 votes vote down vote up
public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) throws IOException {
    try {
        return getSSLContext().getSocketFactory().createSocket(host, port, clientHost, clientPort);
    } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException | InvalidAlgorithmParameterException e) {
        throw new IOException(e + " " + e.getMessage());
    }
}
 
Example #29
Source File: ClientMain.java    From java-11-examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws NoSuchAlgorithmException, KeyManagementException, URISyntaxException, IOException, TimeoutException {
    LOG.info("Client Service starting ...");

    ConnectionFactory factory = new ConnectionFactory();
    factory.setUri("amqp://guest:guest@localhost:15672/virtualHost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare("exchangeName", "direct", true);
    String queueName = channel.queueDeclare().getQueue();
    channel.queueBind(queueName, "exchangeName", "publishKey");

    channel.close();
    connection.close();
}
 
Example #30
Source File: http.java    From ontology-java-sdk with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static String post(String url,Map<String,String> header, String body, boolean https) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
    URL u = new URL(url);
    HttpURLConnection http = (HttpURLConnection) u.openConnection();
    http.setConnectTimeout(10000);
    http.setReadTimeout(10000);
    http.setRequestMethod("POST");
    http.setRequestProperty("Content-Type","application/json");
    if(header != null) {
        for (Map.Entry<String, String> e : header.entrySet()) {
            http.setRequestProperty(e.getKey(), (String) e.getValue());
        }
    }
    if(https) {
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, new TrustManager[]{new X509()}, new SecureRandom());
        SSLSocketFactory ssf = sslContext.getSocketFactory();
        ((HttpsURLConnection)http).setSSLSocketFactory(ssf);
    }
    http.setDoOutput(true);
    http.setDoInput(true);
    http.connect();
    try (OutputStream out = http.getOutputStream()) {
        out.write(body.getBytes(DEFAULT_CHARSET));
        out.flush();
    }
    StringBuilder sb = new StringBuilder();
    try (InputStream is = http.getInputStream()) {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, DEFAULT_CHARSET))) {
            String str = null;
            while((str = reader.readLine()) != null) {
                sb.append(str);
                str = null;
            }
        }
    }
    if (http != null) {
        http.disconnect();
    }
    return sb.toString();
}