Search in sources :

Example 26 with HTTPBasicAuthFilter

use of com.sun.jersey.api.client.filter.HTTPBasicAuthFilter 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 27 with HTTPBasicAuthFilter

use of com.sun.jersey.api.client.filter.HTTPBasicAuthFilter in project ranger by apache.

the class KnoxClient method getTopologyList.

public List<String> getTopologyList(String topologyNameMatching, List<String> knoxTopologyList) {
    // sample URI: https://hdp.example.com:8443/gateway/admin/api/v1/topologies
    LOG.debug("Getting Knox topology list for topologyNameMatching : " + topologyNameMatching);
    List<String> topologyList = new ArrayList<String>();
    String errMsg = " You can still save the repository and start creating " + "policies, but you would not be able to use autocomplete for " + "resource names. Check ranger_admin.log for more info.";
    if (topologyNameMatching == null || topologyNameMatching.trim().isEmpty()) {
        topologyNameMatching = "";
    }
    String decryptedPwd = null;
    try {
        decryptedPwd = PasswordUtils.decryptPassword(password);
    } catch (Exception ex) {
        LOG.info("Password decryption failed; trying knox connection with received password string");
        decryptedPwd = null;
    } finally {
        if (decryptedPwd == null) {
            decryptedPwd = password;
        }
    }
    try {
        Client client = null;
        ClientResponse response = null;
        try {
            client = Client.create();
            client.addFilter(new HTTPBasicAuthFilter(userName, decryptedPwd));
            WebResource webResource = client.resource(knoxUrl);
            response = webResource.accept(EXPECTED_MIME_TYPE).get(ClientResponse.class);
            LOG.debug("Knox topology list response: " + response);
            if (response != null) {
                if (response.getStatus() == 200) {
                    String jsonString = response.getEntity(String.class);
                    LOG.debug("Knox topology list response JSON string: " + jsonString);
                    ObjectMapper objectMapper = new ObjectMapper();
                    JsonNode rootNode = objectMapper.readTree(jsonString);
                    JsonNode topologyNode = rootNode.findValue("topology");
                    if (topologyNode == null) {
                        return topologyList;
                    }
                    Iterator<JsonNode> elements = topologyNode.getElements();
                    while (elements.hasNext()) {
                        JsonNode element = elements.next();
                        JsonNode nameElement = element.get("name");
                        if (nameElement != null) {
                            String topologyName = nameElement.getValueAsText();
                            LOG.debug("Found Knox topologyName: " + topologyName);
                            if (knoxTopologyList != null && topologyName != null && knoxTopologyList.contains(topologyNameMatching)) {
                                continue;
                            }
                            if (topologyName != null && ("*".equals(topologyNameMatching) || topologyName.startsWith(topologyNameMatching))) {
                                topologyList.add(topologyName);
                            }
                        }
                    }
                } else {
                    LOG.error("Got invalid REST response from: " + knoxUrl + ", responseStatus: " + response.getStatus());
                }
            } else {
                String msgDesc = "Unable to get a valid response for " + "getTopologyList() call for KnoxUrl : [" + knoxUrl + "] - got null response.";
                LOG.error(msgDesc);
                HadoopException hdpException = new HadoopException(msgDesc);
                hdpException.generateResponseDataMap(false, msgDesc, msgDesc + errMsg, null, null);
                throw hdpException;
            }
        } finally {
            if (response != null) {
                response.close();
            }
            if (client != null) {
                client.destroy();
            }
        }
    } catch (HadoopException he) {
        throw he;
    } catch (Throwable t) {
        String msgDesc = "Exception on REST call to KnoxUrl : " + knoxUrl + ".";
        HadoopException hdpException = new HadoopException(msgDesc, t);
        LOG.error(msgDesc, t);
        hdpException.generateResponseDataMap(false, BaseClient.getMessage(t), msgDesc + errMsg, null, null);
        throw hdpException;
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("<== KnoxClient.getTopologyList() Topology Matching: " + topologyNameMatching + " Result : " + topologyList.toString());
    }
    return topologyList;
}
Also used : ClientResponse(com.sun.jersey.api.client.ClientResponse) ArrayList(java.util.ArrayList) WebResource(com.sun.jersey.api.client.WebResource) JsonNode(org.codehaus.jackson.JsonNode) HadoopException(org.apache.ranger.plugin.client.HadoopException) HTTPBasicAuthFilter(com.sun.jersey.api.client.filter.HTTPBasicAuthFilter) HadoopException(org.apache.ranger.plugin.client.HadoopException) BaseClient(org.apache.ranger.plugin.client.BaseClient) Client(com.sun.jersey.api.client.Client) ObjectMapper(org.codehaus.jackson.map.ObjectMapper)

Example 28 with HTTPBasicAuthFilter

use of com.sun.jersey.api.client.filter.HTTPBasicAuthFilter in project ranger by apache.

the class RangerRESTClient method buildClient.

private Client buildClient() {
    Client client = null;
    if (mIsSSL) {
        KeyManager[] kmList = getKeyManagers();
        TrustManager[] tmList = getTrustManagers();
        SSLContext sslContext = getSSLContext(kmList, tmList);
        ClientConfig config = new DefaultClientConfig();
        // to handle List<> unmarshalling
        config.getClasses().add(JacksonJsonProvider.class);
        HostnameVerifier hv = new HostnameVerifier() {

            public boolean verify(String urlHostName, SSLSession session) {
                return session.getPeerHost().equals(urlHostName);
            }
        };
        config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(hv, sslContext));
        client = Client.create(config);
    }
    if (client == null) {
        ClientConfig config = new DefaultClientConfig();
        // to handle List<> unmarshalling
        config.getClasses().add(JacksonJsonProvider.class);
        client = Client.create(config);
    }
    if (!StringUtils.isEmpty(mUsername) && !StringUtils.isEmpty(mPassword)) {
        client.addFilter(new HTTPBasicAuthFilter(mUsername, mPassword));
    }
    // Set Connection Timeout and ReadTime for the PolicyRefresh
    client.setConnectTimeout(mRestClientConnTimeOutMs);
    client.setReadTimeout(mRestClientReadTimeOutMs);
    return client;
}
Also used : DefaultClientConfig(com.sun.jersey.api.client.config.DefaultClientConfig) SSLSession(javax.net.ssl.SSLSession) SSLContext(javax.net.ssl.SSLContext) HTTPBasicAuthFilter(com.sun.jersey.api.client.filter.HTTPBasicAuthFilter) TrustManager(javax.net.ssl.TrustManager) HostnameVerifier(javax.net.ssl.HostnameVerifier) Client(com.sun.jersey.api.client.Client) ClientConfig(com.sun.jersey.api.client.config.ClientConfig) DefaultClientConfig(com.sun.jersey.api.client.config.DefaultClientConfig) KeyManager(javax.net.ssl.KeyManager) HTTPSProperties(com.sun.jersey.client.urlconnection.HTTPSProperties)

Example 29 with HTTPBasicAuthFilter

use of com.sun.jersey.api.client.filter.HTTPBasicAuthFilter in project coprhd-controller by CoprHD.

the class ScaleIORestClient method authenticate.

@Override
protected void authenticate() {
    log.info("Authenticating");
    _client.removeAllFilters();
    _client.addFilter(new HTTPBasicAuthFilter(_username, _password));
    if (log.isDebugEnabled()) {
        _client.addFilter(new LoggingFilter(System.out));
    }
    URI requestURI = _base.resolve(URI.create(ScaleIOConstants.API_LOGIN));
    ClientResponse response = _client.resource(requestURI).type(MediaType.APPLICATION_JSON).get(ClientResponse.class);
    if (response.getClientResponseStatus() != ClientResponse.Status.OK && response.getClientResponseStatus() != ClientResponse.Status.CREATED) {
        throw ScaleIOException.exceptions.authenticationFailure(_base.toString());
    }
    _authToken = response.getEntity(String.class).replace("\"", "");
    _client.removeAllFilters();
    _client.addFilter(new HTTPBasicAuthFilter(_username, _authToken));
    if (log.isDebugEnabled()) {
        _client.addFilter(new LoggingFilter(System.out));
    }
}
Also used : ClientResponse(com.sun.jersey.api.client.ClientResponse) LoggingFilter(com.sun.jersey.api.client.filter.LoggingFilter) HTTPBasicAuthFilter(com.sun.jersey.api.client.filter.HTTPBasicAuthFilter) URI(java.net.URI)

Example 30 with HTTPBasicAuthFilter

use of com.sun.jersey.api.client.filter.HTTPBasicAuthFilter in project coprhd-controller by CoprHD.

the class ECSApiFactory method getRESTClient.

/**
 * Create ECS API client
 *
 * @param endpoint ECS endpoint
 * @return
 */
public ECSApi getRESTClient(URI endpoint, String username, String password) {
    ECSApi ecsApi = _clientMap.get(endpoint.toString() + ":" + username + ":" + password);
    if (ecsApi == null) {
        Client jerseyClient = new ApacheHttpClient(_clientHandler);
        jerseyClient.addFilter(new HTTPBasicAuthFilter(username, password));
        RESTClient restClient = new RESTClient(jerseyClient);
        ecsApi = new ECSApi(endpoint, restClient);
        _clientMap.putIfAbsent(endpoint.toString() + ":" + username + ":" + password, ecsApi);
    }
    return ecsApi;
}
Also used : ApacheHttpClient(com.sun.jersey.client.apache.ApacheHttpClient) ApacheHttpClient(com.sun.jersey.client.apache.ApacheHttpClient) HttpClient(org.apache.commons.httpclient.HttpClient) Client(com.sun.jersey.api.client.Client) HTTPBasicAuthFilter(com.sun.jersey.api.client.filter.HTTPBasicAuthFilter)

Aggregations

HTTPBasicAuthFilter (com.sun.jersey.api.client.filter.HTTPBasicAuthFilter)45 Client (com.sun.jersey.api.client.Client)31 WebResource (com.sun.jersey.api.client.WebResource)19 ClientResponse (com.sun.jersey.api.client.ClientResponse)15 ClientConfig (com.sun.jersey.api.client.config.ClientConfig)14 DefaultClientConfig (com.sun.jersey.api.client.config.DefaultClientConfig)14 LoggingFilter (com.sun.jersey.api.client.filter.LoggingFilter)7 ArrayList (java.util.ArrayList)7 ClientFilter (com.sun.jersey.api.client.filter.ClientFilter)6 HTTPSProperties (com.sun.jersey.client.urlconnection.HTTPSProperties)5 ApacheHttpClient (com.sun.jersey.client.apache.ApacheHttpClient)4 HostnameVerifier (javax.net.ssl.HostnameVerifier)4 SSLSession (javax.net.ssl.SSLSession)4 ClientHandlerException (com.sun.jersey.api.client.ClientHandlerException)3 ClientRequest (com.sun.jersey.api.client.ClientRequest)3 MultivaluedMapImpl (com.sun.jersey.core.util.MultivaluedMapImpl)3 FormDataMultiPart (com.sun.jersey.multipart.FormDataMultiPart)3 FileInputStream (java.io.FileInputStream)3 URI (java.net.URI)3 KeyStore (java.security.KeyStore)3