use of com.disney.groovity.tags.Credentials.UserPass in project groovity by disney.
the class Ws method tag.
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public Object tag(Map attributes, Closure body) throws Exception {
Object url = resolve(attributes, URL);
if (url == null) {
throw new RuntimeException("ws() requires 'url' attribute");
}
ScriptHelper context = getScriptHelper(body);
Map variables = context.getBinding().getVariables();
URI uri;
URIBuilder builder;
ArrayList<Header> headers;
Function handlerFunction;
Optional<UserPass> userPass;
Optional<HttpSignatureSigner> signer;
final AtomicReference openMessage = new AtomicReference<>();
try {
builder = new URIBuilder(url.toString());
bind(context, Uri.CURRENT_URI_BUILDER, builder);
headers = new ArrayList<Header>();
bind(context, com.disney.groovity.tags.Header.CURRENT_LIST_FOR_HEADERS, headers);
Credentials.acceptCredentials(variables);
Signature.acceptSigner(variables);
Object oldOut = get(context, OUT);
StringWriter sw = new StringWriter();
Object rval = null;
bind(context, OUT, sw);
try {
rval = body.call();
if (rval instanceof Writable) {
((Writable) rval).writeTo(sw);
}
} finally {
bind(context, OUT, oldOut);
userPass = Credentials.resolveCredentials(variables);
signer = Signature.resolveSigner(variables);
}
String val = sw.toString().trim();
if (val.length() > 0) {
openMessage.set(val);
} else if (rval != null) {
openMessage.set(rval);
}
uri = builder.build();
handlerFunction = (Function) get(body, Handler.HANDLER_BINDING);
} catch (URISyntaxException e1) {
throw new RuntimeException("Invalid URI " + url, e1);
} finally {
unbind(context, Uri.CURRENT_URI_BUILDER);
unbind(context, com.disney.groovity.tags.Header.CURRENT_LIST_FOR_HEADERS);
unbind(context, Handler.HANDLER_BINDING);
}
final Closure closer = resolve(attributes, CLOSE, Closure.class);
final Closure errorHandler = resolve(attributes, ERROR, Closure.class);
final Class messageFormat = resolve(attributes, MESSAGE, Class.class);
final Integer timeout = resolve(attributes, TIMEOUT, Integer.class);
final AtomicReference<WebSocket> socket = new AtomicReference<>();
ClientEndpointConfig.Builder configBuilder = ClientEndpointConfig.Builder.create();
Session session;
try {
session = getContainer().connectToServer(new Endpoint() {
@Override
public void onOpen(Session session, EndpointConfig config) {
try {
openCount.incrementAndGet();
if (timeout != null) {
session.setMaxIdleTimeout(timeout * 1000);
}
WebSocket ws = new WebSocket(session);
socket.set(ws);
ws.setName(uri.toString());
if (handlerFunction != null) {
ws.setMessageHandler(arg -> {
synchronized (handlerFunction) {
handlerFunction.apply(arg);
}
}, messageFormat);
}
if (openMessage.get() != null) {
ws.call(openMessage.get());
}
} catch (Exception e) {
log.log(Level.SEVERE, "Error opening web socket session " + uri, e);
}
}
@Override
public void onClose(Session session, CloseReason reason) {
try {
closeCount.incrementAndGet();
openSessions.remove(session);
if (closer != null) {
if (closer.getMaximumNumberOfParameters() > 0) {
closer.call(reason);
} else {
closer.call();
}
}
} catch (Exception e) {
log.log(Level.SEVERE, "Error closing web socket session " + uri, e);
}
}
@Override
public void onError(Session session, Throwable th) {
try {
errorCount.incrementAndGet();
if (errorHandler == null) {
throw th;
}
errorHandler.call(th);
} catch (Throwable e) {
Level logLevel = Level.WARNING;
if (th != e) {
log.log(logLevel, "Error handling error for web socket session " + uri, e);
} else if (th instanceof IOException) {
logLevel = Level.FINE;
}
log.log(logLevel, "WebSocket client error: " + uri, th);
}
}
}, configBuilder.configurator(new ClientEndpointConfig.Configurator() {
public void beforeRequest(Map<String, List<String>> reqHeaders) {
// copy programmatic headers
for (Header header : headers) {
List<String> hl = reqHeaders.get(header.getName());
if (hl == null) {
hl = new ArrayList<>();
reqHeaders.put(header.getName(), hl);
}
hl.add(header.getValue());
}
Map<String, Map<String, String>> allChallenges = null;
if (userPass.isPresent() || signer.isPresent()) {
allChallenges = getChallenges(uri, reqHeaders);
}
if (userPass.isPresent()) {
UserPass user = userPass.get();
if (allChallenges != null) {
List<String> auths = reqHeaders.get(AUTHORIZATION_HEADER);
if (auths == null) {
auths = new ArrayList<>();
reqHeaders.put(AUTHORIZATION_HEADER, auths);
}
if (allChallenges.containsKey("basic")) {
StringBuilder authBuilder = new StringBuilder(user.getUser());
authBuilder.append(":");
char[] pass = user.getPass();
for (char c : pass) {
authBuilder.append(c);
}
try {
auths.add("Basic " + printBase64Binary(authBuilder.toString().getBytes("UTF-8")));
} catch (UnsupportedEncodingException e) {
log.severe(e.getMessage());
}
}
if (allChallenges.containsKey("digest")) {
final String digestUri = uri.getPath() + ((uri.getRawQuery() != null) ? "?" + uri.getRawQuery() : "");
Map<String, String> digestChallenge = allChallenges.get("digest");
if (log.isLoggable(Level.FINE)) {
log.fine("Generating digest auth for " + digestChallenge.toString());
}
DigestAuthorization digestAuth = new DigestAuthorization();
digestAuth.setUsername(user.getUser());
digestAuth.setQop("auth");
digestAuth.setCnonce(String.valueOf(ThreadLocalRandom.current().nextLong(10000000, 999999999999l)));
digestAuth.setNonceCount("000001");
digestAuth.setUri(digestUri);
for (Entry<String, String> entry : digestChallenge.entrySet()) {
String k = entry.getKey();
String v = entry.getValue();
if ("nonce".equalsIgnoreCase(k)) {
digestAuth.setNonce(v);
} else if ("realm".equalsIgnoreCase(k)) {
digestAuth.setRealm(v);
} else if ("opaque".equalsIgnoreCase(k)) {
digestAuth.setOpaque(v);
}
}
String signingString;
try {
signingString = digestAuth.generateSigningString(user.getUser(), new String(user.getPass()), new AuthorizationRequest() {
@Override
public String getURI() {
return digestUri;
}
@Override
public String getMethod() {
return "GET";
}
@Override
public List<String> getHeaders(String name) {
return reqHeaders.get(name);
}
});
MessageDigest md5 = MessageDigest.getInstance("MD5");
digestAuth.setDigest(md5.digest(signingString.toString().getBytes()));
if (log.isLoggable(Level.FINE)) {
log.fine("Generated digest auth " + digestAuth.toString());
}
auths.add(digestAuth.toString());
} catch (NoSuchAlgorithmException e) {
log.severe("Missing MD5 " + e.getMessage());
}
}
}
}
if (signer.isPresent()) {
if (allChallenges.containsKey("signature")) {
HttpSignatureSigner sig = signer.get();
HttpGet signReq = createRequest(uri, reqHeaders);
List<Header> beforeHeaders = Arrays.asList(signReq.getAllHeaders());
try {
sig.process(signReq, null);
} catch (HttpException | IOException e) {
log.log(Level.SEVERE, "Error processing http signature", e);
}
Header[] afterHeaders = signReq.getAllHeaders();
for (Header h : afterHeaders) {
if (!beforeHeaders.contains(h)) {
List<String> hl = reqHeaders.get(h.getName());
if (hl == null) {
hl = new ArrayList<>();
reqHeaders.put(h.getName(), hl);
}
hl.add(h.getValue());
if (log.isLoggable(Level.FINE)) {
log.fine("Copied HTTP signature header " + h);
}
}
}
}
}
}
}).build(), uri);
} catch (Exception e) {
errorCount.incrementAndGet();
throw e;
}
openSessions.add(session);
String var = resolve(attributes, VAR, String.class);
if (var != null) {
context.getBinding().setVariable(var, socket.get());
}
return socket.get();
}
use of com.disney.groovity.tags.Credentials.UserPass in project groovity by disney.
the class Http method tag.
@SuppressWarnings({ "rawtypes", "unchecked" })
public Object tag(Map attributes, Closure body) throws Exception {
Object url = resolve(attributes, "url");
if (url == null) {
throw new RuntimeException("<g:http> requires 'url' attribute");
}
Object var = resolve(attributes, VAR);
String method = "GET";
Object methodAtt = resolve(attributes, "method");
if (methodAtt != null) {
method = methodAtt.toString();
}
boolean followRedirects = true;
Object redirectsAtt = resolve(attributes, "redirects");
if (redirectsAtt != null) {
followRedirects = Boolean.parseBoolean(redirectsAtt.toString());
}
CookieOption cookieOption = CookieOption.DEFAULT;
Object cookiesAtt = resolve(attributes, "cookies");
if (cookiesAtt != null) {
cookieOption = CookieOption.valueOf(cookiesAtt.toString().toUpperCase());
}
Object timeout = resolve(attributes, TIMEOUT);
final int timeoutSeconds = timeout == null ? -1 : timeout instanceof Number ? ((Number) timeout).intValue() : Integer.parseInt(timeout.toString());
Object target = resolve(attributes, "to");
if (target instanceof Class) {
if (!Object.class.equals(target)) {
target = ((Class) target).newInstance();
}
}
if (target == null) {
target = Object.class;
}
Object async = resolve(attributes, "async");
if (async != null && !(async instanceof Boolean)) {
async = Boolean.valueOf(async.toString());
}
HttpEntity dataEntity = null;
Object data = resolve(attributes, "data");
HttpClientContext clientContext = resolve(attributes, "context", HttpClientContext.class);
if (clientContext == null) {
clientContext = HttpClientContext.create();
}
if (clientContext.getCookieStore() == null) {
// we don't want to let cookies be shared across contexts
clientContext.setCookieStore(new BasicCookieStore());
}
if (clientContext.getAuthCache() == null) {
// we also don't want to share credentials across contexts
clientContext.setAuthCache(new BasicAuthCache());
}
final HttpClientContext fContext = clientContext;
ScriptHelper context = getScriptHelper(body);
Object oldOut = get(context, OUT);
// execute body to assemble URL params, headers, post body
Map variables = context.getBinding().getVariables();
URI uri;
URIBuilder builder;
ArrayList<Header> headers;
Optional<UserPass> userPass;
Optional<HttpSignatureSigner> signer;
Optional<HttpRequestInterceptor> interceptor;
try {
builder = new URIBuilder(url.toString());
bind(context, Uri.CURRENT_URI_BUILDER, builder);
headers = new ArrayList<Header>();
bind(context, com.disney.groovity.tags.Header.CURRENT_LIST_FOR_HEADERS, headers);
Credentials.acceptCredentials(variables);
Signature.acceptSigner(variables);
acceptInterceptor(variables);
StringWriter sw = new StringWriter();
bind(context, OUT, sw);
try {
Object rval = body.call();
if (rval instanceof Writable) {
((Writable) rval).writeTo(sw);
}
} finally {
bind(context, OUT, oldOut);
userPass = Credentials.resolveCredentials(variables);
signer = Signature.resolveSigner(variables);
interceptor = resolveInterceptor(variables);
}
String val = sw.toString();
if (val.trim().length() > 0) {
dataEntity = new StringEntity(val);
}
uri = builder.build();
if (userPass.isPresent()) {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()), new UsernamePasswordCredentials(userPass.get().getUser(), new String(userPass.get().getPass())));
clientContext.setCredentialsProvider(credsProvider);
}
} catch (URISyntaxException e1) {
throw new RuntimeException("Invalid URI " + url, e1);
} finally {
unbind(context, Uri.CURRENT_URI_BUILDER);
unbind(context, com.disney.groovity.tags.Header.CURRENT_LIST_FOR_HEADERS);
}
final HttpRequestBase request = "POST".equalsIgnoreCase(method) ? new HttpPost(uri) : "PUT".equalsIgnoreCase(method) ? new HttpPut(uri) : "HEAD".equalsIgnoreCase(method) ? new HttpHead(uri) : "DELETE".equalsIgnoreCase(method) ? new HttpDelete(uri) : "OPTIONS".equalsIgnoreCase(method) ? new HttpOptions(uri) : new HttpGet(uri);
if (headers.size() > 0) {
request.setHeaders(headers.toArray(new Header[0]));
}
if (request instanceof HttpEntityEnclosingRequest) {
if (data != null) {
// decide on strategy to convert data to entity
if (data instanceof HttpEntity) {
dataEntity = (HttpEntity) data;
} else {
// look at content type for a hint
Header targetType = request.getFirstHeader("Content-Type");
if (targetType != null && targetType.getValue().contains("json")) {
CharArrayWriter caw = new CharArrayWriter();
new ModelJsonWriter(caw).visit(data);
dataEntity = new StringEntity(caw.toString());
} else if (targetType != null && targetType.getValue().contains("xml")) {
if (data instanceof groovy.util.Node) {
dataEntity = new StringEntity(XmlUtil.serialize((groovy.util.Node) data));
} else if (data instanceof GPathResult) {
dataEntity = new StringEntity(XmlUtil.serialize((GPathResult) data));
} else if (data instanceof Element) {
dataEntity = new StringEntity(XmlUtil.serialize((Element) data));
} else if (data instanceof Document) {
dataEntity = new StringEntity(XmlUtil.serialize(((Document) data).getDocumentElement()));
} else {
// if it's not an XML model assume it's a well formed XML string
dataEntity = new StringEntity(data.toString());
}
} else if ((targetType != null && targetType.getValue().contains("x-www-form-urlencoded")) || (targetType == null && (data instanceof Map || data instanceof List))) {
// key/value pairs, accept a map, a list of maps, or a list of NameValuePairs
Iterator source = data instanceof Map ? ((Map) data).entrySet().iterator() : ((List) data).iterator();
ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
while (source.hasNext()) {
Object next = source.next();
if (next instanceof Map.Entry) {
Map.Entry entry = (Entry) next;
pairs.add(new BasicNameValuePair(entry.getKey().toString(), entry.getValue() != null ? entry.getValue().toString() : ""));
} else if (next instanceof NameValuePair) {
pairs.add((NameValuePair) next);
} else if (next instanceof Map) {
Iterator<Map.Entry> sub = ((Map) next).entrySet().iterator();
while (sub.hasNext()) {
Map.Entry se = sub.next();
pairs.add(new BasicNameValuePair(se.getKey().toString(), se.getValue() != null ? se.getValue().toString() : ""));
}
}
}
dataEntity = new UrlEncodedFormEntity(pairs);
} else if (targetType != null && targetType.getValue().contains("multipart/form-data")) {
// list of maps, each map must contain "name" and "body", plus optional "type" and "filename"
Iterator<Map> parts = ((List<Map>) data).iterator();
MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
while (parts.hasNext()) {
Map part = parts.next();
Object pbody = part.get("body");
String name = (String) part.get("name");
String type = (String) part.get("type");
String filename = (String) part.get("filename");
ContentType ct = type != null ? ContentType.parse(type) : null;
if (pbody instanceof File) {
if (ct == null) {
ct = ContentType.DEFAULT_BINARY;
}
meBuilder.addBinaryBody(name, (File) pbody, ct, filename);
} else if (pbody instanceof byte[]) {
if (ct == null) {
ct = ContentType.DEFAULT_BINARY;
}
meBuilder.addBinaryBody(name, (byte[]) pbody, ct, filename);
} else if (pbody instanceof ContentBody) {
meBuilder.addPart(name, (ContentBody) pbody);
} else if (pbody instanceof InputStream) {
if (ct == null) {
ct = ContentType.DEFAULT_BINARY;
}
meBuilder.addBinaryBody(name, (InputStream) pbody, ct, filename);
} else {
if (ct == null) {
ct = ContentType.DEFAULT_TEXT;
}
meBuilder.addTextBody(name, pbody.toString(), ct);
}
}
dataEntity = meBuilder.build();
} else {
// no help from content type header, check for modeled XML
if (data instanceof groovy.util.Node) {
dataEntity = new StringEntity(XmlUtil.serialize((groovy.util.Node) data), ContentType.APPLICATION_XML);
} else if (data instanceof GPathResult) {
dataEntity = new StringEntity(XmlUtil.serialize((GPathResult) data), ContentType.APPLICATION_XML);
} else if (data instanceof Element) {
dataEntity = new StringEntity(XmlUtil.serialize((Element) data), ContentType.APPLICATION_XML);
} else if (data instanceof Document) {
dataEntity = new StringEntity(XmlUtil.serialize(((Document) data).getDocumentElement()), ContentType.APPLICATION_XML);
} else if (data instanceof byte[]) {
dataEntity = new ByteArrayEntity((byte[]) data);
} else if (data instanceof InputStream) {
dataEntity = new InputStreamEntity((InputStream) data);
} else if (data instanceof File) {
dataEntity = new FileEntity((File) data);
} else {
// best option left is to post the toString value of the data
dataEntity = new StringEntity(data.toString());
}
}
}
}
if (dataEntity != null) {
((HttpEntityEnclosingRequest) request).setEntity(dataEntity);
}
}
RequestConfig.Builder configBuilder = request.getConfig() == null ? RequestConfig.custom() : RequestConfig.copy(request.getConfig());
if (!followRedirects) {
configBuilder.setRedirectsEnabled(followRedirects);
}
configBuilder.setCookieSpec(cookieOption.getCookieSpec());
request.setConfig(configBuilder.build());
final String varName = var != null ? var.toString() : null;
ResponseHandler handler = null;
try {
Function handlerFunction = (Function) get(body, Handler.HANDLER_BINDING);
if (handlerFunction != null) {
handler = new ResponseHandler<Object>() {
@Override
public Object handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
return handlerFunction.apply(response);
}
};
}
unbind(body, Handler.HANDLER_BINDING);
} catch (Exception e) {
}
if (handler == null) {
handler = new AutoParsingResponseHandler(target);
}
final List<HttpRequestInterceptor> interceptors = new ArrayList<>();
if (signer.isPresent()) {
interceptors.add(signer.get());
}
if (interceptor.isPresent()) {
interceptors.add(interceptor.get());
}
final ResponseHandler rHandler = handler;
final boolean isAsync = (async != null && Boolean.TRUE.equals(async));
Callable<Object> requester = new Callable() {
public Object call() throws Exception {
TimeoutTask timeoutTask = null;
if (timeoutSeconds > 0) {
timeoutTask = new TimeoutTask(request);
timeoutTimer.schedule(timeoutTask, timeoutSeconds * 1000);
}
try {
Binding oldThreadBinding = null;
if (isAsync) {
oldThreadBinding = ScriptHelper.THREAD_BINDING.get();
Binding asyncBinding = new Binding();
asyncBinding.setVariable("request", request);
ScriptHelper.THREAD_BINDING.set(asyncBinding);
}
try {
for (HttpRequestInterceptor interceptor : interceptors) {
interceptor.process(request, null);
}
return httpClient.execute(request, rHandler, fContext);
} finally {
if (isAsync) {
if (oldThreadBinding == null) {
ScriptHelper.THREAD_BINDING.remove();
} else {
ScriptHelper.THREAD_BINDING.set(oldThreadBinding);
}
}
}
} catch (HttpResponseException e) {
if (isAsync) {
log.error("Async HTTP response error for " + request.getURI() + ": " + e.getMessage());
}
throw e;
} catch (Exception e) {
if (request.isAborted()) {
if (isAsync) {
log.error("Async <g:http> request timed out for " + request.getURI());
}
throw new TimeoutException("Timed out executing <g:http> for " + request.getURI());
} else {
if (isAsync) {
log.error("Async <g:http> request error for " + request.getURI(), e);
}
throw new RuntimeException("Error executing <g:http> for " + request.getURI(), e);
}
} finally {
if (timeoutTask != null) {
timeoutTask.cancel();
}
}
}
};
Object responseVar = null;
if (isAsync) {
// return the Future to the calling code
Future<Object> f = asyncExecutor.submit(requester);
responseVar = new Future<Object>() {
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return f.cancel(mayInterruptIfRunning);
}
@Override
public boolean isCancelled() {
return f.isCancelled();
}
@Override
public boolean isDone() {
return f.isDone();
}
@Override
public Object get() throws InterruptedException, ExecutionException {
GroovityStatistics.startExecution("http(async)");
try {
return f.get();
} finally {
GroovityStatistics.endExecution();
}
}
@Override
public Object get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
GroovityStatistics.startExecution("http(async)");
try {
return f.get(timeout, unit);
} finally {
GroovityStatistics.endExecution();
}
}
};
} else {
// return the parsed/handled response object
GroovityStatistics.startExecution("http(sync)");
try {
responseVar = requester.call();
} finally {
GroovityStatistics.endExecution();
}
}
if (varName != null) {
bind(context, varName, responseVar);
}
return responseVar;
}
Aggregations