org.glassfish.jersey.client.authentication.HttpAuthenticationFeature Java Examples

The following examples show how to use org.glassfish.jersey.client.authentication.HttpAuthenticationFeature. 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: WebClient.java    From ambari-logsearch with Apache License 2.0 7 votes vote down vote up
public String put(String path, String requestBody) {
  JerseyClient jerseyClient = JerseyClientBuilder.createClient();
  HttpAuthenticationFeature authFeature = HttpAuthenticationFeature.basicBuilder()
          .credentials("admin", "admin")
          .build();
  jerseyClient.register(authFeature);

  String url = String.format("http://%s:%d%s", host, port, path);

  LOG.info("Url: {}", url);

  WebTarget target = jerseyClient.target(url);
  Invocation.Builder invocationBuilder =  target.request(MediaType.APPLICATION_JSON_TYPE);
  String response = invocationBuilder.put(Entity.entity(requestBody, MediaType.APPLICATION_JSON_TYPE)).readEntity(String.class);

  LOG.info("Response: {}", response);

  return response;
}
 
Example #2
Source File: ResolverClient.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
Client getHttpClient() {
    if (httpClient == null) {
        try {
            SSLContext sslCtx = SSLContext.getInstance("SSL");
            TrustManager tm = new TrustThemAll();
            sslCtx.init(null, new TrustManager[] {tm}, null);

            httpClient = ClientBuilder.newBuilder()
                    .sslContext(sslCtx)
                    .register(HttpAuthenticationFeature.basic(user, passwd))
                    .build();
            httpClient.property(ClientProperties.FOLLOW_REDIRECTS, true);
            httpClient.property(ClientProperties.CONNECT_TIMEOUT, 2 * 60 * 1000); // 2 min
        } catch (NoSuchAlgorithmException | KeyManagementException ex) {
            throw new IllegalStateException(ex);
        }
    }
    return httpClient;
}
 
Example #3
Source File: DockerRegistry.java    From carnotzet with Apache License 2.0 6 votes vote down vote up
private WebTarget getRegistryWebTarget(ImageRef imageRef) {
	if (!webTargets.containsKey(imageRef.getRegistryUrl())) {

		ObjectMapper mapper = new ObjectMapper();
		mapper.registerModule(new JavaTimeModule());

		ClientConfig clientCOnfig = new ClientConfig();
		clientCOnfig.connectorProvider(new HttpUrlConnectorProvider());

		// TODO : This client doesn't handle mandatory Oauth2 Bearer token imposed by some registries implementations (ie : docker hub)
		Client client = ClientBuilder.newClient(clientCOnfig)
				.register(new JacksonJaxbJsonProvider(mapper, new Annotations[] {Annotations.JACKSON}))
				.register(JacksonFeature.class);
		String auth = config.getAuthFor(imageRef.getRegistryName());
		if (auth != null) {
			String[] credentials = new String(Base64.getDecoder().decode(auth), StandardCharsets.UTF_8).split(":");
			client.register(HttpAuthenticationFeature.basicBuilder().credentials(credentials[0], credentials[1]));
		}
		WebTarget webTarget = client.target(imageRef.getRegistryUrl());
		webTargets.put(imageRef.getRegistryUrl(), webTarget);
	}
	return webTargets.get(imageRef.getRegistryUrl());
}
 
Example #4
Source File: NamedResource.java    From usergrid with Apache License 2.0 6 votes vote down vote up
public <T> T post(boolean useToken, Token tokenToUse , Class<T> type, Map entity,
                  final QueryParameters queryParameters, boolean useBasicAuthentication) {

    WebTarget resource = getTarget( useToken,tokenToUse );
    resource = addParametersToResource(resource, queryParameters);

    GenericType<T> gt = new GenericType<>((Class) type);

    if (useBasicAuthentication) {
        HttpAuthenticationFeature feature = HttpAuthenticationFeature.basicBuilder()
            .credentials("superuser", "superpassword").build();
        return resource.register(feature).request()
                       .accept(MediaType.APPLICATION_JSON)
                       .post(javax.ws.rs.client.Entity.json(entity), gt);
    }

    return resource.request()
                   .accept(MediaType.APPLICATION_JSON)
                   .post(javax.ws.rs.client.Entity.json(entity), gt);
}
 
Example #5
Source File: TenacityAuthenticatorTest.java    From tenacity with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotTransformAuthenticationExceptionIntoMappedException() throws AuthenticationException {
    when(AuthenticatorApp.getMockAuthenticator().authenticate(any(BasicCredentials.class))).thenThrow(new AuthenticationException("test"));
    final Client client = new JerseyClientBuilder(new MetricRegistry())
            .using(executorService, Jackson.newObjectMapper())
            .build("dropwizard-app-rule");

    client.register(HttpAuthenticationFeature.basicBuilder()
            .nonPreemptive()
            .credentials("user", "stuff")
            .build());

    final Response response = client
            .target(URI.create("http://localhost:" + RULE.getLocalPort() + "/auth"))
            .request()
            .get(Response.class);

    assertThat(response.getStatus()).isEqualTo(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());

    verify(AuthenticatorApp.getMockAuthenticator(), times(1)).authenticate(any(BasicCredentials.class));
    verifyZeroInteractions(AuthenticatorApp.getTenacityContainerExceptionMapper());
    verify(AuthenticatorApp.getTenacityExceptionMapper(), times(1)).toResponse(any(HystrixRuntimeException.class));
}
 
Example #6
Source File: NamedResource.java    From usergrid with Apache License 2.0 6 votes vote down vote up
public <T> T post(boolean useToken, Class<T> type, Map entity,
                  final QueryParameters queryParameters, boolean useBasicAuthentication) {

    WebTarget resource = getTarget(useToken);
    resource = addParametersToResource(resource, queryParameters);

    GenericType<T> gt = new GenericType<>((Class) type);

    if (useBasicAuthentication) {
        HttpAuthenticationFeature feature = HttpAuthenticationFeature.basicBuilder()
            .credentials("superuser", "superpassword").build();
        return resource.register(feature).request()
            .accept(MediaType.APPLICATION_JSON)
            .post(javax.ws.rs.client.Entity.json(entity), gt);
    }

    return resource.request()
        .accept(MediaType.APPLICATION_JSON)
        .post(javax.ws.rs.client.Entity.json(entity), gt);
}
 
Example #7
Source File: SimpleRestClient.java    From next-api-v2-examples with MIT License 6 votes vote down vote up
public JsonNode login(String user, String password)
    throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException,
        NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, IOException {

  String authParameters = encryptAuthParameter(user, password);

  // Send login request
  Response response =
      baseResource
          .path("login")
          .queryParam("service", Main.SERVICE)
          .queryParam("auth", authParameters)
          .request(responseType)
          .post(null);

  ObjectNode json = response.readEntity(ObjectNode.class);

  JsonNode node = new ObjectMapper().readTree(json.toString());

  String sessionKey = json.get("session_key").asText();

  // Add the session key to basic auth for all calls
  baseResource.register(HttpAuthenticationFeature.basic(sessionKey, sessionKey));

  return node;
}
 
Example #8
Source File: Connection.java    From ecs-cf-service-broker with Apache License 2.0 6 votes vote down vote up
public void login() throws EcsManagementClientException {
    UriBuilder uriBuilder = UriBuilder.fromPath(endpoint).segment("login");

    logger.info("Logging into {} as {}", endpoint, username);

    HttpAuthenticationFeature authFeature = HttpAuthenticationFeature
            .basicBuilder().credentials(username, password).build();
    Client jerseyClient = buildJerseyClient().register(authFeature);

    Builder request = jerseyClient.target(uriBuilder).request();

    Response response = request.get();
    try {
        handleResponse(response);
    } catch (EcsManagementResourceNotFoundException e) {
        logger.warn("Login failed to handle response: {}", e.getMessage());
        logger.warn("Response: {}", response);

        throw new EcsManagementClientException(e);
    }
    this.authToken = response.getHeaderString("X-SDS-AUTH-TOKEN");
    this.authRetries = 0;
}
 
Example #9
Source File: BasicAuthClientGenerator.java    From raml-java-client-generator with Apache License 2.0 6 votes vote down vote up
@Override
public JMethod createClient(JDefinedClass containerClass) {
    JCodeModel cm = new JCodeModel();
    JMethod getClient = containerClass.method(JMod.PROTECTED, Client.class, "getClient");
    JBlock body = getClient.body();

    JVar decl = body.decl(JMod.FINAL, cm._ref(Client.class), RamlJavaClientGenerator.CLIENT_FIELD_NAME, cm.anonymousClass(ClientBuilder.class).staticInvoke("newClient"));
    JInvocation invoke = cm.ref(HttpAuthenticationFeature.class).staticInvoke("basic");

    for (JFieldVar var : generatedRequiredField) {
        invoke.arg(var);
    }

    invoke.invoke("build");

    JInvocation jInvocation1 = decl.invoke("register").arg(invoke);
    body.add(jInvocation1);
    body._return(decl);
    return getClient;
}
 
Example #10
Source File: BasicAuthClientGenerator.java    From raml-java-client-generator with Apache License 2.0 6 votes vote down vote up
@Override
public JMethod createClientWithMultipart(JDefinedClass containerClass) {
    JCodeModel cm = new JCodeModel();
    JMethod getClient = containerClass.method(JMod.PROTECTED, Client.class, "getClientWithMultipart");
    JBlock body = getClient.body();

    JVar decl = body.decl(JMod.FINAL, cm._ref(Client.class), RamlJavaClientGenerator.CLIENT_FIELD_NAME, cm.anonymousClass(ClientBuilder.class).staticInvoke("newClient"));
    JInvocation invoke = cm.ref(HttpAuthenticationFeature.class).staticInvoke("basic");

    for (JFieldVar var : generatedRequiredField) {
        invoke.arg(var);
    }

    invoke.invoke("build");

    JInvocation jInvocation1 = decl.invoke("register").arg(invoke);
    body.add(jInvocation1);

    JInvocation jInvocation2 = decl.invoke("register").arg(cm.ref(MultiPartFeature.class).dotclass());
    body.add(jInvocation2);
    body._return(decl);
    return getClient;
}
 
Example #11
Source File: SaltConnector.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
public SaltConnector(GatewayConfig gatewayConfig, SaltErrorResolver saltErrorResolver, boolean debug) {
    try {
        restClient = RestClientUtil.createClient(
                gatewayConfig.getServerCert(), gatewayConfig.getClientCert(), gatewayConfig.getClientKey(), debug);
        String saltBootPasswd = Optional.ofNullable(gatewayConfig.getSaltBootPassword()).orElse(SALT_BOOT_PASSWORD);
        saltTarget = restClient.target(gatewayConfig.getGatewayUrl())
                .register(HttpAuthenticationFeature.basic(SALT_BOOT_USER, saltBootPasswd))
                .register(new DisableProxyAuthFeature())
                .register(new SetProxyTimeoutFeature(PROXY_TIMEOUT));
        saltPassword = Optional.ofNullable(gatewayConfig.getSaltPassword()).orElse(SALT_PASSWORD);
        signatureKey = gatewayConfig.getSignatureKey();
        this.saltErrorResolver = saltErrorResolver;
    } catch (Exception e) {
        throw new RuntimeException("Failed to create rest client with 2-way-ssl config", e);
    }
}
 
Example #12
Source File: HttpSBControllerImpl.java    From onos with Apache License 2.0 6 votes vote down vote up
private void authenticate(Client client, RestSBDevice device) {
    AuthenticationScheme authScheme = device.authentication();
    if (authScheme == AuthenticationScheme.NO_AUTHENTICATION) {
        log.debug("{} scheme is specified, ignoring authentication", authScheme);
        return;
    } else if (authScheme == AuthenticationScheme.OAUTH2) {
        String token = checkNotNull(device.token());
        client.register(OAuth2ClientSupport.feature(token));
    } else if (authScheme == AuthenticationScheme.BASIC) {
        String username = device.username();
        String password = device.password() == null ? "" : device.password();
        client.register(HttpAuthenticationFeature.basic(username, password));
    } else {
        // TODO: Add support for other authentication schemes here.
        throw new IllegalArgumentException(String.format("Unsupported authentication scheme: %s",
                authScheme.name()));
    }
}
 
Example #13
Source File: RESTApiClusterManager.java    From hbase with Apache License 2.0 6 votes vote down vote up
@Override
public void setConf(Configuration conf) {
  super.setConf(conf);
  if (conf == null) {
    // `Configured()` constructor calls `setConf(null)` before calling again with a real value.
    return;
  }

  final Class<? extends ClusterManager> clazz = conf.getClass(REST_API_DELEGATE_CLUSTER_MANAGER,
    HBaseClusterManager.class, ClusterManager.class);
  hBaseClusterManager = ReflectionUtils.newInstance(clazz, conf);

  serverHostname = conf.get(REST_API_CLUSTER_MANAGER_HOSTNAME, DEFAULT_SERVER_HOSTNAME);
  clusterName = conf.get(REST_API_CLUSTER_MANAGER_CLUSTER_NAME, DEFAULT_CLUSTER_NAME);

  // Add filter to Client instance to enable server authentication.
  String serverUsername = conf.get(REST_API_CLUSTER_MANAGER_USERNAME, DEFAULT_SERVER_USERNAME);
  String serverPassword = conf.get(REST_API_CLUSTER_MANAGER_PASSWORD, DEFAULT_SERVER_PASSWORD);
  client.register(HttpAuthenticationFeature.basic(serverUsername, serverPassword));

  this.retryCounterFactory = new RetryCounterFactory(new RetryConfig()
    .setMaxAttempts(conf.getInt(RETRY_ATTEMPTS_KEY, DEFAULT_RETRY_ATTEMPTS))
    .setSleepInterval(conf.getLong(RETRY_SLEEP_INTERVAL_KEY, DEFAULT_RETRY_SLEEP_INTERVAL)));
}
 
Example #14
Source File: JerseyClientUtil.java    From datacollector with Apache License 2.0 6 votes vote down vote up
public static void configurePasswordAuth(
    AuthenticationType authType,
    String username,
    String password,
    ClientBuilder clientBuilder
) {
  if (authType == AuthenticationType.BASIC) {
    clientBuilder.register(HttpAuthenticationFeature.basic(username, password));
  }

  if (authType == AuthenticationType.DIGEST) {
    clientBuilder.register(HttpAuthenticationFeature.digest(username, password));
  }

  if (authType == AuthenticationType.UNIVERSAL) {
    clientBuilder.register(HttpAuthenticationFeature.universal(username, password));
  }
}
 
Example #15
Source File: AlertManager.java    From datacollector with Apache License 2.0 6 votes vote down vote up
private void configurePasswordAuth(WebhookCommonConfig webhookConfig, WebTarget webTarget) throws StageException {
  if (webhookConfig.authType == AuthenticationType.BASIC) {
    webTarget.register(
        HttpAuthenticationFeature.basic(webhookConfig.username.get(), webhookConfig.password.get())
    );
  }

  if (webhookConfig.authType == AuthenticationType.DIGEST) {
    webTarget.register(
        HttpAuthenticationFeature.digest(webhookConfig.username.get(), webhookConfig.password.get())
    );
  }

  if (webhookConfig.authType == AuthenticationType.UNIVERSAL) {
    webTarget.register(
        HttpAuthenticationFeature.universal(webhookConfig.username.get(), webhookConfig.password.get())
    );
  }
}
 
Example #16
Source File: WebHookNotifier.java    From datacollector with Apache License 2.0 6 votes vote down vote up
private void configurePasswordAuth(WebhookCommonConfig webhookConfig, WebTarget webTarget) throws StageException {
  if (webhookConfig.authType == AuthenticationType.BASIC) {
    webTarget.register(
        HttpAuthenticationFeature.basic(webhookConfig.username.get(), webhookConfig.password.get())
    );
  }

  if (webhookConfig.authType == AuthenticationType.DIGEST) {
    webTarget.register(
        HttpAuthenticationFeature.digest(webhookConfig.username.get(), webhookConfig.password.get())
    );
  }

  if (webhookConfig.authType == AuthenticationType.UNIVERSAL) {
    webTarget.register(
        HttpAuthenticationFeature.universal(webhookConfig.username.get(), webhookConfig.password.get())
    );
  }
}
 
Example #17
Source File: TestUserGroupManager.java    From datacollector with Apache License 2.0 6 votes vote down vote up
private void testGetUsers(String usersListURI, HttpAuthenticationFeature loginFeature) throws Exception {
  Response response = ClientBuilder
      .newClient()
      .target(usersListURI)
      .register(loginFeature)
      .request()
      .get();
  Assert.assertEquals(200, response.getStatus());
  List<UserJson> usersList = response.readEntity(new GenericType<List<UserJson>>(){});
  Assert.assertNotNull(usersList);
  Assert.assertEquals(2, usersList.size());

  UserJson adminUser = usersList.get(0);
  Assert.assertEquals("admin", adminUser.getName());
  Assert.assertEquals(1, adminUser.getRoles().size());
  Assert.assertEquals(3, adminUser.getGroups().size());
  Assert.assertEquals("all", adminUser.getGroups().get(0));
  Assert.assertEquals("group1", adminUser.getGroups().get(1));
  Assert.assertEquals("group2", adminUser.getGroups().get(2));
}
 
Example #18
Source File: TestHttpAccessControl.java    From datacollector with Apache License 2.0 6 votes vote down vote up
private void testCORSGetRequest(String userInfoURI) throws Exception {
  HttpAuthenticationFeature authenticationFeature = HttpAuthenticationFeature.basic("admin", "admin");
  Response response = ClientBuilder.newClient()
      .target(userInfoURI)
      .register(authenticationFeature)
      .request()
      .header("Origin", "http://example.com")
      .header("Access-Control-Request-Method", "GET")
      .get();

  Assert.assertEquals(200, response.getStatus());

  MultivaluedMap<String, Object> responseHeader = response.getHeaders();

  List<Object> allowOriginHeader = responseHeader.get(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER);
  Assert.assertNotNull(allowOriginHeader);
  Assert.assertEquals(1, allowOriginHeader.size());
  Assert.assertEquals("http://example.com", allowOriginHeader.get(0));
}
 
Example #19
Source File: LDAPAuthenticationFallbackIT.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Test
public void testLdapAuthentication(){
  String userInfoURI = sdcURL  + "/rest/v1/system/info/currentUser";
  HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic(username, password);
  Response response = ClientBuilder
      .newClient()
      .register(feature)
      .target(userInfoURI)
      .request()
      .get();

  if (!result) {
    Assert.assertEquals(401, response.getStatus());
  } else{
    Assert.assertEquals(200, response.getStatus());
    Map userInfo = response.readEntity(Map.class);
    Assert.assertTrue(userInfo.containsKey("user"));
    Assert.assertEquals(username, userInfo.get("user"));
    Assert.assertTrue(userInfo.containsKey("roles"));
    List<String> roles = (List<String>) userInfo.get("roles");
    Assert.assertEquals(role.size(), roles.size());
    for(int i = 0; i < roles.size(); i++) {
      Assert.assertEquals(role.get(i), roles.get(i));
    }
  }
}
 
Example #20
Source File: LdapAuthenticationIT.java    From datacollector with Apache License 2.0 6 votes vote down vote up
/**
 * Assert authentication result using ldap-login.conf with given username and password.
 * All user for this test is configured so that role "admin" will be found and successfully authenticated.
 * @param ldapConf  The configuration for ldap-login.conf
 * @param username  username to login
 * @param password  password to login
 * @throws Exception
 */
public static void assertAuthenticationSuccess(String ldapConf, String username, String password) throws Exception{
  startSDCServer(ldapConf);

  String userInfoURI = sdcURL  + "/rest/v1/system/info/currentUser";
  HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic(username, password);
  Response response = ClientBuilder
      .newClient()
      .register(feature)
      .target(userInfoURI)
      .request()
      .get();

  Assert.assertEquals(200, response.getStatus());
  Map userInfo = response.readEntity(Map.class);
  Assert.assertTrue(userInfo.containsKey("user"));
  Assert.assertEquals(username, userInfo.get("user"));
  Assert.assertTrue(userInfo.containsKey("roles"));
  Assert.assertEquals(1, ((List)userInfo.get("roles")).size());
  Assert.assertEquals("admin", ((List)userInfo.get("roles")).get(0));
  stopSDCServer();
}
 
Example #21
Source File: LdapAuthenticationIT.java    From datacollector with Apache License 2.0 5 votes vote down vote up
/**
 * Test using search filter. If roleSearchFilter is provided and has {dn}, then
 * we apply the filter by replacing {dn} with user's full DN.
 * @throws Exception
 */
@Test
public void testEmptyPassword() throws Exception {
  String memberFilter = "ldap {\n" + // information for server 1
      "  com.streamsets.datacollector.http.LdapLoginModule required\n" +
      "  debug=\"false\"\n" +
      "  useLdaps=\"false\"\n" +
      "  contextFactory=\"com.sun.jndi.ldap.LdapCtxFactory\"\n" +
      "  hostname=\"" + server.getContainerIpAddress()+ "\"\n" +
      "  port=\"" + server.getMappedPort(LDAP_PORT) + "\"\n" +
      "  bindDn=\"" + BIND_DN + "\"\n" +
      "  bindPassword=\"" + BIND_PWD + "\"\n" +
      "  authenticationMethod=\"simple\"\n" +
      "  forceBindingLogin=\"false\"\n" +
      "  userBaseDn=\"ou=employees,dc=example,dc=org\"\n" +
      "  userRdnAttribute=\"uid\"\n" +
      "  userIdAttribute=\"uid\"\n" +
      "  userPasswordAttribute=\"userPassword\"\n" +
      "  userObjectClass=\"inetOrgPerson\"\n" +
      "  roleBaseDn=\"ou=departments,dc=example,dc=org\"\n" +
      "  roleNameAttribute=\"cn\"\n" +
      "  roleMemberAttribute=\"member\"\n" +
      "  roleObjectClass=\"groupOfNames\"\n" +
      "  roleFilter=\"member={dn}\";\n" +   // {} is invalid. Default(search by full DN) should be applied
      "};";

  startSDCServer(memberFilter);

  String userInfoURI = sdcURL  + "/rest/v1/system/info/currentUser";
  HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("user4", "");
  Response response = ClientBuilder
      .newClient()
      .register(feature)
      .target(userInfoURI)
      .request()
      .get();

  Assert.assertEquals(401, response.getStatus());
}
 
Example #22
Source File: JerseyClientHeaders.java    From tutorials with MIT License 5 votes vote down vote up
public static Response digestAuthenticationAtRequestLevel(String username, String password) {
    HttpAuthenticationFeature feature = HttpAuthenticationFeature.digest();

    Client client = ClientBuilder.newBuilder().register(feature).build();
    return client.target(TARGET)
            .path(MAIN_RESOURCE)
            .path(RESOURCE_AUTH_DIGEST)
            .request()
            .property(HTTP_AUTHENTICATION_DIGEST_USERNAME, username)
            .property(HTTP_AUTHENTICATION_DIGEST_PASSWORD, password)
            .get();
}
 
Example #23
Source File: JerseyClientHeaders.java    From tutorials with MIT License 5 votes vote down vote up
public static Response digestAuthenticationAtClientLevel(String username, String password) {
    HttpAuthenticationFeature feature = HttpAuthenticationFeature.digest(username, password);
    Client client = ClientBuilder.newBuilder().register(feature).build();
    return client.target(TARGET)
            .path(MAIN_RESOURCE)
            .path(RESOURCE_AUTH_DIGEST)
            .request()
            .get();
}
 
Example #24
Source File: JerseyClientHeaders.java    From tutorials with MIT License 5 votes vote down vote up
public static Response basicAuthenticationAtRequestLevel(String username, String password) {
    //To simplify we removed de SSL/TLS protection, but it's required to have an encryption
    // when using basic authentication schema as it's send only on Base64 encoding
    HttpAuthenticationFeature feature = HttpAuthenticationFeature.basicBuilder().build();
    Client client = ClientBuilder.newBuilder().register(feature).build();
    return client.target(TARGET)
            .path(MAIN_RESOURCE)
            .request()
            .property(HTTP_AUTHENTICATION_BASIC_USERNAME, username)
            .property(HTTP_AUTHENTICATION_BASIC_PASSWORD, password)
            .get();
}
 
Example #25
Source File: BoostrapResource.java    From usergrid with Apache License 2.0 5 votes vote down vote up
public Entity put(QueryParameters queryParameters){

        WebTarget resource = getTarget();
        resource = addParametersToResource( resource, queryParameters );

        HttpAuthenticationFeature feature = HttpAuthenticationFeature.basicBuilder()
            .credentials( "superuser", "superpassword" ).build();

        return resource.register( feature ).request().accept( MediaType.APPLICATION_JSON )
            .put( javax.ws.rs.client.Entity.json(""), Entity.class );
    }
 
Example #26
Source File: SetupResource.java    From usergrid with Apache License 2.0 5 votes vote down vote up
public Entity put(QueryParameters queryParameters){

        WebTarget resource = getTarget();
        resource = addParametersToResource( resource, queryParameters );

        HttpAuthenticationFeature feature = HttpAuthenticationFeature.basicBuilder()
            .credentials( "superuser", "superpassword" ).build();

        return resource.register( feature ).request()
            .accept( MediaType.APPLICATION_JSON ).put( javax.ws.rs.client.Entity.json(""), Entity.class );
    }
 
Example #27
Source File: SystemResource.java    From usergrid with Apache License 2.0 5 votes vote down vote up
public ApiResponse get(QueryParameters queryParameters){

            WebTarget resource = getTarget();
            resource = addParametersToResource( resource, queryParameters );

            HttpAuthenticationFeature feature = HttpAuthenticationFeature.basicBuilder()
                .credentials( "superuser", "superpassword" ).build();

            return resource.register( feature ).request().accept( MediaType.APPLICATION_JSON )
                .get(ApiResponse.class);
        }
 
Example #28
Source File: RestClient.java    From usergrid with Apache License 2.0 5 votes vote down vote up
public void superuserSetup() {

        HttpAuthenticationFeature feature = HttpAuthenticationFeature.basicBuilder()
            .credentials( "superuser", "superpassword" ).build();

        getTarget().path( "system/superuser/setup" ).register( feature ).request()
            .accept( MediaType.APPLICATION_JSON )
            .get( JsonNode.class );
    }
 
Example #29
Source File: RestClient.java    From product-private-paas with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor to verify the certificate and connect to the rest endpoint
 */
public RestClient(String username, String password) {
    SslConfigurator sslConfig = SslConfigurator.newInstance().trustStoreFile(Constants.CERTIFICATE_PATH)
            .trustStorePassword(Constants.CERTIFICATE_PASSWORD).keyStoreFile(Constants.CERTIFICATE_PATH)
            .keyPassword(Constants.CERTIFICATE_PASSWORD);
    SSLContext sslContext = sslConfig.createSSLContext();
    client = ClientBuilder.newBuilder().sslContext(sslContext).build();
    HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic(username, password);
    client.register(feature);
}
 
Example #30
Source File: GeoServerRestClient.java    From geowave with Apache License 2.0 5 votes vote down vote up
private WebTarget getWebTarget() {
  if (webTarget == null) {
    String url = getConfig().getUrl();
    if (url != null) {
      url = url.trim().toLowerCase(Locale.ROOT);
      Client client = null;
      if (url.startsWith("http://")) {
        client = ClientBuilder.newClient();
      } else if (url.startsWith("https://")) {
        final SslConfigurator sslConfig = SslConfigurator.newInstance();
        if (getConfig().getGsConfigProperties() != null) {
          loadSSLConfigurations(sslConfig, getConfig().getGsConfigProperties());
        }
        final SSLContext sslContext = sslConfig.createSSLContext();

        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
        client = ClientBuilder.newBuilder().sslContext(sslContext).build();
      }
      if (client != null) {
        client.register(
            HttpAuthenticationFeature.basic(getConfig().getUser(), getConfig().getPass()));
        try {
          webTarget = client.target(new URI(url));
        } catch (final URISyntaxException e) {
          LOGGER.error("Unable to parse geoserver URL: " + url, e);
        }
      }
    }
  }

  return webTarget;
}