Search in sources :

Example 56 with DefaultClientConfig

use of com.sun.jersey.api.client.config.DefaultClientConfig in project druid by druid-io.

the class LookupIntrospectionResourceTest method testGetValue.

@Test
public void testGetValue() {
    Client client = Client.create(new DefaultClientConfig());
    WebResource service = client.resource(baseUri);
    ClientResponse resp = service.path("/druid/v1/lookups/introspect/lookupId1/values").accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
    String s = resp.getEntity(String.class);
    Assert.assertEquals("[value, value2]", s);
    Assert.assertEquals(200, resp.getStatus());
}
Also used : ClientResponse(com.sun.jersey.api.client.ClientResponse) DefaultClientConfig(com.sun.jersey.api.client.config.DefaultClientConfig) WebResource(com.sun.jersey.api.client.WebResource) Client(com.sun.jersey.api.client.Client) Test(org.junit.Test)

Example 57 with DefaultClientConfig

use of com.sun.jersey.api.client.config.DefaultClientConfig in project druid by druid-io.

the class LookupIntrospectionResourceTest method testGetKey.

@Test
public void testGetKey() {
    Client client = Client.create(new DefaultClientConfig());
    WebResource service = client.resource(baseUri);
    ClientResponse resp = service.path("/druid/v1/lookups/introspect/lookupId1/keys").accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
    String s = resp.getEntity(String.class);
    Assert.assertEquals("[key, key2]", s);
    Assert.assertEquals(200, resp.getStatus());
}
Also used : ClientResponse(com.sun.jersey.api.client.ClientResponse) DefaultClientConfig(com.sun.jersey.api.client.config.DefaultClientConfig) WebResource(com.sun.jersey.api.client.WebResource) Client(com.sun.jersey.api.client.Client) Test(org.junit.Test)

Example 58 with DefaultClientConfig

use of com.sun.jersey.api.client.config.DefaultClientConfig in project druid by druid-io.

the class LookupIntrospectionResourceTest method testGetMap.

@Test
public void testGetMap() {
    Client client = Client.create(new DefaultClientConfig());
    WebResource service = client.resource(baseUri);
    ClientResponse resp = service.path("/druid/v1/lookups/introspect/lookupId1/").accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
    String s = resp.getEntity(String.class);
    Assert.assertEquals("{\"key\":\"value\",\"key2\":\"value2\"}", s);
    Assert.assertEquals(200, resp.getStatus());
}
Also used : ClientResponse(com.sun.jersey.api.client.ClientResponse) DefaultClientConfig(com.sun.jersey.api.client.config.DefaultClientConfig) WebResource(com.sun.jersey.api.client.WebResource) Client(com.sun.jersey.api.client.Client) Test(org.junit.Test)

Example 59 with DefaultClientConfig

use of com.sun.jersey.api.client.config.DefaultClientConfig in project pentaho-kettle by pentaho.

the class WebServiceManager method createService.

@Override
@SuppressWarnings("unchecked")
public <T> T createService(final String username, final String password, final Class<T> clazz) throws MalformedURLException {
    final Future<Object> resultFuture;
    synchronized (serviceCache) {
        // if this is true, a coder did not make sure that clearServices was called on disconnect
        if (lastUsername != null && !lastUsername.equals(username)) {
            throw new IllegalStateException();
        }
        final WebServiceSpecification webServiceSpecification = serviceNameMap.get(clazz);
        final String serviceName = webServiceSpecification.getServiceName();
        if (serviceName == null) {
            throw new IllegalStateException();
        }
        if (webServiceSpecification.getServiceType().equals(ServiceType.JAX_WS)) {
            // build the url handling whether or not baseUrl ends with a slash
            // String baseUrl = repositoryMeta.getRepositoryLocation().getUrl();
            final URL url = // $NON-NLS-1$ //$NON-NLS-2$
            new URL(baseUrl + (baseUrl.endsWith("/") ? "" : "/") + "webservices/" + serviceName + "?wsdl");
            String key = url.toString() + '_' + serviceName + '_' + clazz.getName();
            if (!serviceCache.containsKey(key)) {
                resultFuture = executor.submit(new Callable<Object>() {

                    @Override
                    public Object call() throws Exception {
                        Service service = Service.create(url, new QName(NAMESPACE_URI, serviceName));
                        T port = service.getPort(clazz);
                        // add TRUST_USER if necessary
                        if (StringUtils.isNotBlank(System.getProperty("pentaho.repository.client.attemptTrust"))) {
                            ((BindingProvider) port).getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, Collections.singletonMap(TRUST_USER, Collections.singletonList(username)));
                        } else {
                            // http basic authentication
                            ((BindingProvider) port).getRequestContext().put(BindingProvider.USERNAME_PROPERTY, username);
                            ((BindingProvider) port).getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, password);
                        }
                        // accept cookies to maintain session on server
                        ((BindingProvider) port).getRequestContext().put(BindingProvider.SESSION_MAINTAIN_PROPERTY, true);
                        // support streaming binary data
                        // TODO mlowery this is not portable between JAX-WS implementations (uses com.sun)
                        ((BindingProvider) port).getRequestContext().put(JAXWSProperties.HTTP_CLIENT_STREAMING_CHUNK_SIZE, 8192);
                        SOAPBinding binding = (SOAPBinding) ((BindingProvider) port).getBinding();
                        binding.setMTOMEnabled(true);
                        return port;
                    }
                });
                serviceCache.put(key, resultFuture);
            } else {
                resultFuture = serviceCache.get(key);
            }
        } else {
            if (webServiceSpecification.getServiceType().equals(ServiceType.JAX_RS)) {
                String key = baseUrl.toString() + '_' + serviceName + '_' + clazz.getName();
                if (!serviceCache.containsKey(key)) {
                    resultFuture = executor.submit(new Callable<Object>() {

                        @Override
                        public Object call() throws Exception {
                            ClientConfig clientConfig = new DefaultClientConfig();
                            Client client = Client.create(clientConfig);
                            client.addFilter(new HTTPBasicAuthFilter(username, password));
                            Class<?>[] parameterTypes = new Class<?>[] { Client.class, URI.class };
                            String factoryClassName = webServiceSpecification.getServiceClass().getName();
                            factoryClassName = factoryClassName.substring(0, factoryClassName.lastIndexOf("$"));
                            Class<?> factoryClass = Class.forName(factoryClassName);
                            Method method = factoryClass.getDeclaredMethod(webServiceSpecification.getServiceName(), parameterTypes);
                            T port = (T) method.invoke(null, new Object[] { client, new URI(baseUrl + "/plugin") });
                            return port;
                        }
                    });
                    serviceCache.put(key, resultFuture);
                } else {
                    resultFuture = serviceCache.get(key);
                }
            } else {
                resultFuture = null;
            }
        }
        try {
            if (clazz.isInterface()) {
                return UnifiedRepositoryInvocationHandler.forObject((T) resultFuture.get(), clazz);
            } else {
                return (T) resultFuture.get();
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            Throwable cause = e.getCause();
            if (cause != null) {
                if (cause instanceof RuntimeException) {
                    throw (RuntimeException) cause;
                } else if (cause instanceof MalformedURLException) {
                    throw (MalformedURLException) cause;
                }
            }
            throw new RuntimeException(e);
        }
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) URI(java.net.URI) URL(java.net.URL) Callable(java.util.concurrent.Callable) ClientConfig(com.sun.jersey.api.client.config.ClientConfig) DefaultClientConfig(com.sun.jersey.api.client.config.DefaultClientConfig) Client(com.sun.jersey.api.client.Client) ExecutionException(java.util.concurrent.ExecutionException) DefaultClientConfig(com.sun.jersey.api.client.config.DefaultClientConfig) QName(javax.xml.namespace.QName) IUserRoleListWebService(org.pentaho.platform.security.userrole.ws.IUserRoleListWebService) Service(javax.xml.ws.Service) IUnifiedRepositoryJaxwsWebService(org.pentaho.platform.repository2.unified.webservices.jaxws.IUnifiedRepositoryJaxwsWebService) ExecutorService(java.util.concurrent.ExecutorService) IRepositorySyncWebService(com.pentaho.pdi.ws.IRepositorySyncWebService) IAuthorizationPolicyWebService(org.pentaho.platform.security.policy.rolebased.ws.IAuthorizationPolicyWebService) IRoleAuthorizationPolicyRoleBindingDaoWebService(org.pentaho.platform.security.policy.rolebased.ws.IRoleAuthorizationPolicyRoleBindingDaoWebService) IUserRoleWebService(org.pentaho.platform.security.userroledao.ws.IUserRoleWebService) SOAPBinding(javax.xml.ws.soap.SOAPBinding) Method(java.lang.reflect.Method) HTTPBasicAuthFilter(com.sun.jersey.api.client.filter.HTTPBasicAuthFilter)

Example 60 with DefaultClientConfig

use of com.sun.jersey.api.client.config.DefaultClientConfig in project ranger by apache.

the class KMSClient method getKeyList.

public List<String> getKeyList(final String keyNameMatching, final List<String> existingKeyList) {
    String[] providers = null;
    try {
        providers = createProvider(provider);
    } catch (IOException | URISyntaxException e) {
        return null;
    }
    final String errMsg = errMessage;
    List<String> lret = null;
    for (int i = 0; i < providers.length; i++) {
        lret = new ArrayList<String>();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Getting Kms Key list for keyNameMatching : " + keyNameMatching);
        }
        String uri = providers[i] + (providers[i].endsWith("/") ? KMS_LIST_API_ENDPOINT : ("/" + KMS_LIST_API_ENDPOINT));
        Client client = null;
        ClientResponse response = null;
        boolean isKerberos = false;
        try {
            ClientConfig cc = new DefaultClientConfig();
            cc.getProperties().put(ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true);
            client = Client.create(cc);
            if (authType != null && authType.equalsIgnoreCase(AUTH_TYPE_KERBEROS)) {
                isKerberos = true;
            }
            Subject sub = new Subject();
            if (!isKerberos) {
                uri = uri.concat("?user.name=" + username);
                WebResource webResource = client.resource(uri);
                response = webResource.accept(EXPECTED_MIME_TYPE).get(ClientResponse.class);
                LOG.info("Init Login: security not enabled, using username");
                sub = SecureClientLogin.login(username);
            } else {
                if (!StringUtils.isEmpty(rangerPrincipal) && !StringUtils.isEmpty(rangerKeytab)) {
                    LOG.info("Init Lookup Login: security enabled, using rangerPrincipal/rangerKeytab");
                    if (StringUtils.isEmpty(nameRules)) {
                        nameRules = "DEFAULT";
                    }
                    String shortName = new HadoopKerberosName(rangerPrincipal).getShortName();
                    uri = uri.concat("?doAs=" + shortName);
                    sub = SecureClientLogin.loginUserFromKeytab(rangerPrincipal, rangerKeytab, nameRules);
                } else {
                    LOG.info("Init Login: using username/password");
                    String shortName = new HadoopKerberosName(username).getShortName();
                    uri = uri.concat("?doAs=" + shortName);
                    String decryptedPwd = PasswordUtils.decryptPassword(password);
                    sub = SecureClientLogin.loginUserWithPassword(username, decryptedPwd);
                }
            }
            final WebResource webResource = client.resource(uri);
            response = Subject.doAs(sub, new PrivilegedAction<ClientResponse>() {

                @Override
                public ClientResponse run() {
                    return webResource.accept(EXPECTED_MIME_TYPE).get(ClientResponse.class);
                }
            });
            if (LOG.isDebugEnabled()) {
                LOG.debug("getKeyList():calling " + uri);
            }
            if (response != null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("getKeyList():response.getStatus()= " + response.getStatus());
                }
                if (response.getStatus() == 200) {
                    String jsonString = response.getEntity(String.class);
                    Gson gson = new GsonBuilder().setPrettyPrinting().create();
                    @SuppressWarnings("unchecked") List<String> keys = gson.fromJson(jsonString, List.class);
                    if (keys != null) {
                        for (String key : keys) {
                            if (existingKeyList != null && existingKeyList.contains(key)) {
                                continue;
                            }
                            if (keyNameMatching == null || keyNameMatching.isEmpty() || key.startsWith(keyNameMatching)) {
                                if (LOG.isDebugEnabled()) {
                                    LOG.debug("getKeyList():Adding kmsKey " + key);
                                }
                                lret.add(key);
                            }
                        }
                        return lret;
                    }
                } else if (response.getStatus() == 401) {
                    LOG.info("getKeyList():response.getStatus()= " + response.getStatus() + " for URL " + uri + ", so returning null list");
                    String msgDesc = response.getEntity(String.class);
                    HadoopException hdpException = new HadoopException(msgDesc);
                    hdpException.generateResponseDataMap(false, msgDesc, msgDesc + errMsg, null, null);
                    lret = null;
                    throw hdpException;
                } else if (response.getStatus() == 403) {
                    LOG.info("getKeyList():response.getStatus()= " + response.getStatus() + " for URL " + uri + ", so returning null list");
                    String msgDesc = response.getEntity(String.class);
                    HadoopException hdpException = new HadoopException(msgDesc);
                    hdpException.generateResponseDataMap(false, msgDesc, msgDesc + errMsg, null, null);
                    lret = null;
                    throw hdpException;
                } else {
                    LOG.info("getKeyList():response.getStatus()= " + response.getStatus() + " for URL " + uri + ", so returning null list");
                    String jsonString = response.getEntity(String.class);
                    LOG.info(jsonString);
                    lret = null;
                }
            } else {
                String msgDesc = "Unable to get a valid response for " + "expected mime type : [" + EXPECTED_MIME_TYPE + "] URL : " + uri + " - got null response.";
                LOG.error(msgDesc);
                HadoopException hdpException = new HadoopException(msgDesc);
                hdpException.generateResponseDataMap(false, msgDesc, msgDesc + errMsg, null, null);
                lret = null;
                throw hdpException;
            }
        } catch (HadoopException he) {
            lret = null;
            throw he;
        } catch (Throwable t) {
            String msgDesc = "Exception while getting Kms Key List. URL : " + uri;
            HadoopException hdpException = new HadoopException(msgDesc, t);
            LOG.error(msgDesc, t);
            hdpException.generateResponseDataMap(false, BaseClient.getMessage(t), msgDesc + errMsg, null, null);
            lret = null;
            throw hdpException;
        } finally {
            if (response != null) {
                response.close();
            }
            if (client != null) {
                client.destroy();
            }
            if (lret == null) {
                if (i != providers.length - 1)
                    continue;
            }
        }
    }
    return lret;
}
Also used : ClientResponse(com.sun.jersey.api.client.ClientResponse) DefaultClientConfig(com.sun.jersey.api.client.config.DefaultClientConfig) GsonBuilder(com.google.gson.GsonBuilder) HadoopKerberosName(org.apache.hadoop.security.HadoopKerberosName) WebResource(com.sun.jersey.api.client.WebResource) Gson(com.google.gson.Gson) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) HadoopException(org.apache.ranger.plugin.client.HadoopException) Subject(javax.security.auth.Subject) PrivilegedAction(java.security.PrivilegedAction) BaseClient(org.apache.ranger.plugin.client.BaseClient) Client(com.sun.jersey.api.client.Client) ClientConfig(com.sun.jersey.api.client.config.ClientConfig) DefaultClientConfig(com.sun.jersey.api.client.config.DefaultClientConfig)

Aggregations

DefaultClientConfig (com.sun.jersey.api.client.config.DefaultClientConfig)65 ClientConfig (com.sun.jersey.api.client.config.ClientConfig)55 Client (com.sun.jersey.api.client.Client)42 WebResource (com.sun.jersey.api.client.WebResource)21 HTTPBasicAuthFilter (com.sun.jersey.api.client.filter.HTTPBasicAuthFilter)15 ClientResponse (com.sun.jersey.api.client.ClientResponse)14 HTTPSProperties (com.sun.jersey.client.urlconnection.HTTPSProperties)9 HostnameVerifier (javax.net.ssl.HostnameVerifier)7 SSLSession (javax.net.ssl.SSLSession)7 TrustManager (javax.net.ssl.TrustManager)7 ClientHandlerException (com.sun.jersey.api.client.ClientHandlerException)6 URLConnectionClientHandler (com.sun.jersey.client.urlconnection.URLConnectionClientHandler)6 IOException (java.io.IOException)6 VisibleForTesting (com.google.common.annotations.VisibleForTesting)5 ClientFilter (com.sun.jersey.api.client.filter.ClientFilter)5 LoggingFilter (com.sun.jersey.api.client.filter.LoggingFilter)5 SecureRandom (java.security.SecureRandom)5 SSLContext (javax.net.ssl.SSLContext)5 URISyntaxException (java.net.URISyntaxException)4 ArrayList (java.util.ArrayList)4