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);
}
}
}
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;
}
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;
}
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));
}
}
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;
}
Aggregations