@Override public Promise<Result> apply(UserProfile profile) throws Throwable { if (profile != null) { logger.debug("authorizerName: {}", authorizerName); if (authorizationChecker.isAuthorized(context, profile, authorizerName, config.getAuthorizers())) { logger.debug("authenticated and authorized -> grant access"); // when called from Scala if (delegate == null) { return Promise.pure(null); } else { return delegate.call(ctx); } } else { logger.debug("forbidden"); return forbidden(context, currentClients, profile); } } else { if (startAuthentication(context, currentClients)) { logger.debug("Starting authentication"); saveRequestedUrl(context, currentClients); return Promise.promise(() -> redirectToIdentityProvider(context, currentClients)); } else { logger.debug("unauthorized"); return unauthorized(context, currentClients); } } } });
final WS.Response response = AC.url(relativeUri, acHost, Option.none()).setTimeout(requestTimeoutMillis).get().get(requestTimeoutMillis, TimeUnit.MILLISECONDS); if (response.getStatus() == 200)
private Promise<HttpResponse> execute(BoundRequestBuilder builder) { try { final Promise<HttpResponse> smartFuture = new Promise<>(); prepare(builder).execute(new AsyncCompletionHandler<HttpResponse>() { @Override public HttpResponse onCompleted(Response response) throws Exception { HttpResponse httpResponse = new HttpAsyncResponse(response); smartFuture.invoke(httpResponse); return httpResponse; } @Override public void onThrowable(Throwable t) { // An error happened - must "forward" the exception to // the one waiting for the result smartFuture.invokeWithException(t); } }); return smartFuture; } catch (Exception e) { throw new RuntimeException(e); } }
final EntityTransaction ftx = tx; F.Promise<T> committedResult = (ftx == null) ? result : result.map(t -> { if (ftx.getRollbackOnly()) { ftx.rollback(); }); committedResult.onFailure(t -> { if (ftx != null) { try { if (ftx.isActive()) { ftx.rollback(); } } catch (Throwable e) {} committedResult.onRedeem(t -> { try { fem.close();
play.libs.Akka.asPromise(ask(actorRef,msg, timeout)).map( new play.libs.F.Function<java.lang.Object, play.mvc.Result>() { public play.mvc.Result apply(java.lang.Object response){
public static <A, B, C, D, E> Promise<F.E5<A, B, C, D, E>> waitEither(Promise<A> tA, Promise<B> tB, Promise<C> tC, Promise<D> tD, Promise<E> tE) { final Promise<F.E5<A, B, C, D, E>> result = new Promise<>(); Promise<F.Tuple<Integer, Promise<Object>>> t = waitEitherInternal(tA, tB, tC, tD, tE); t.onRedeem(new F.Action<Promise<F.Tuple<Integer, Promise<Object>>>>() { @Override public void invoke(Promise<F.Tuple<Integer, Promise<Object>>> completed) { F.Tuple<Integer, Promise<Object>> value = completed.getOrNull(); switch (value._1) { case 1: result.invoke(F.E5.<A, B, C, D, E>_1((A) value._2.getOrNull())); break; case 2: result.invoke(F.E5.<A, B, C, D, E>_2((B) value._2.getOrNull())); break; case 3: result.invoke(F.E5.<A, B, C, D, E>_3((C) value._2.getOrNull())); break; case 4: result.invoke(F.E5.<A, B, C, D, E>_4((D) value._2.getOrNull())); break; case 5: result.invoke(F.E5.<A, B, C, D, E>_5((E) value._2.getOrNull())); break; } } }); return result; }
public static <T> Promise<T> waitAny(Promise<T>... futures) { final Promise<T> result = new Promise<>(); F.Action<Promise<T>> action = new F.Action<Promise<T>>() { @Override public void invoke(Promise<T> completed) { synchronized (this) { if (result.isDone()) { return; } } T resultOrNull = completed.getOrNull(); if(resultOrNull != null) { result.invoke(resultOrNull); } else { result.invokeWithException(completed.exception); } } }; for (Promise<T> f : futures) { f.onRedeem(action); } return result; } }
public static <A, B, C, D> Promise<F.E4<A, B, C, D>> waitEither(Promise<A> tA, Promise<B> tB, Promise<C> tC, Promise<D> tD) { final Promise<F.E4<A, B, C, D>> result = new Promise<>(); Promise<F.Tuple<Integer, Promise<Object>>> t = waitEitherInternal(tA, tB, tC, tD); t.onRedeem(new F.Action<Promise<F.Tuple<Integer, Promise<Object>>>>() { @Override public void invoke(Promise<F.Tuple<Integer, Promise<Object>>> completed) { F.Tuple<Integer, Promise<Object>> value = completed.getOrNull(); switch (value._1) { case 1: result.invoke(F.E4.<A, B, C, D>_1((A) value._2.getOrNull())); break; case 2: result.invoke(F.E4.<A, B, C, D>_2((B) value._2.getOrNull())); break; case 3: result.invoke(F.E4.<A, B, C, D>_3((C) value._2.getOrNull())); break; case 4: result.invoke(F.E4.<A, B, C, D>_4((D) value._2.getOrNull())); break; } } }); return result; }
@Override public F.Promise<SimpleResult> call(Http.Context context) throws Throwable { final String authHeader = context.request().getHeader(AUTHORIZATION); if (authHeader == null) { context.response().setHeader(WWW_AUTHENTICATE, REALM); return F.Promise.pure((SimpleResult) unauthorized()); } final String auth = authHeader.substring(6); final String[] credString = org.apache.commons.codec.binary.StringUtils.newStringUtf8(Base64.decodeBase64(auth)).split(":"); if (credString.length != 2) { return F.Promise.pure((SimpleResult) unauthorized()); } final String username = credString[0]; final String password = credString[1]; return (StringUtils.equals(username, play.Play.application().configuration().getString("rest.auth.user", "")) && StringUtils.equals(password, play.Play.application().configuration().getString("rest.auth.pass", ""))) ? delegate.call(context) : F.Promise.pure((SimpleResult) unauthorized()); } }
public static <A, B, C> Promise<F.E3<A, B, C>> waitEither(Promise<A> tA, Promise<B> tB, Promise<C> tC) { final Promise<F.E3<A, B, C>> result = new Promise<>(); Promise<F.Tuple<Integer, Promise<Object>>> t = waitEitherInternal(tA, tB, tC); t.onRedeem(new F.Action<Promise<F.Tuple<Integer, Promise<Object>>>>() { @Override public void invoke(Promise<F.Tuple<Integer, Promise<Object>>> completed) { F.Tuple<Integer, Promise<Object>> value = completed.getOrNull(); switch (value._1) { case 1: result.invoke(F.E3.<A, B, C>_1((A) value._2.getOrNull())); break; case 2: result.invoke(F.E3.<A, B, C>_2((B) value._2.getOrNull())); break; case 3: result.invoke(F.E3.<A, B, C>_3((C) value._2.getOrNull())); break; } } }); return result; }
protected <T> F.Promise<Result> withJsonBody(Class<T> klass, ToPromiseResult<T> f) { JsonNode jsonNode = request().body().asJson(); if (jsonNode == null) { return pure(badRequest("could not parse body to JSON")); } else { try { T obj = play.libs.Json.fromJson(jsonNode, klass); F.Tuple<Integer, Object> r = f.apply(obj); return pure(Results.status(r._1, toJson(r._2))); } catch (ConstraintViolationException ex) { return pure((badRequest(createJsonResponse(ex)))); } catch (RuntimeException e) { if (e.getCause() instanceof JsonProcessingException) { return pure(badRequest(handleProcessingException((JsonProcessingException) e.getCause()))); } else { throw e; } } } }
/** * If is called in a 'HttpRequest' invocation context, waits until request is served and schedules job then. * * Otherwise is the same as now(); * * If you want to schedule a job to run after some other job completes, wait till a promise redeems of just override * first Job's call() to schedule the second one. * * @return the job completion */ public Promise<V> afterRequest() { InvocationContext current = Invoker.InvocationContext.current(); if (current == null || !Http.invocationType.equals(current.getInvocationType())) { return now(); } Promise<V> smartFuture = new Promise<>(); Callable<V> callable = getJobCallingCallable(smartFuture); JobsPlugin.addAfterRequestAction(callable); return smartFuture; }
public Promise<Response> execute() { final scala.concurrent.Promise<Response> scalaPromise = scala.concurrent.Promise$.MODULE$.<Response>apply(); try { WS.client().executeRequest(request, new AsyncCompletionHandler<com.ning.http.client.Response>() { @Override public com.ning.http.client.Response onCompleted(com.ning.http.client.Response response) { final com.ning.http.client.Response ahcResponse = response; scalaPromise.success(new Response(ahcResponse)); return response; } @Override public void onThrowable(Throwable t) { scalaPromise.failure(t); } }); } catch (IOException exception) { scalaPromise.failure(exception); } return new Promise<Response>(scalaPromise.future()); } }
public static <A, B> Promise<F.Either<A, B>> waitEither(Promise<A> tA, Promise<B> tB) { final Promise<F.Either<A, B>> result = new Promise<>(); Promise<F.Tuple<Integer, Promise<Object>>> t = waitEitherInternal(tA, tB); t.onRedeem(new F.Action<Promise<F.Tuple<Integer, Promise<Object>>>>() { @Override public void invoke(Promise<F.Tuple<Integer, Promise<Object>>> completed) { F.Tuple<Integer, Promise<Object>> value = completed.getOrNull(); switch (value._1) { case 1: result.invoke(F.Either.<A, B>_1((A) value._2.getOrNull())); break; case 2: result.invoke(F.Either.<A, B>_2((B) value._2.getOrNull())); break; } } }); return result; }
@Override public void setHerculesMatches(String userId, AcHost acHost, Issue issue, final List<Pattern> patterns) { LOGGER.trace("Setting hercules property on issue {} to {} matches", issue.getKey(), patterns.size()); final ObjectNode herculesProperty = Json.newObject(); herculesProperty.put("matches", patterns.size()); herculesProperty.put("articles", patterns.stream().map(Pattern::getPageName).collect(Collectors.joining("|"))); final WS.WSRequestHolder url = AC.url("/rest/api/2/issue/" + issue.getKey() + "/properties/hercules", acHost, Option.none()).setContentType("application/json"); final WS.Response response = url.put(herculesProperty).get(30, TimeUnit.SECONDS); // HTTP 201 created if (response.getStatus() >= 400) { LOGGER.error("Error setting 'hercules' property on issue {}, response [{}] {}", issue.getKey(), response.getStatus(), response.getStatusText()); } else { LOGGER.trace("Property 'hercules' set on issue {}", issue.getKey()); } } }
private void addComment(final AcHost acHost, final Issue issue, final String commentBody) { LOGGER.debug("Adding comment to the issue {}", issue.getKey()); final ObjectNode commentJson = Json.newObject(); commentJson.put("body", commentBody); final WS.WSRequestHolder url = AC.url("/rest/api/2/issue/" + issue.getKey() + "/comment", acHost, Option.none()).setContentType("application/json"); final WS.Response response = url.post(commentJson).get(30, TimeUnit.SECONDS); // HTTP 201 created if (response.getStatus() != 201) { LOGGER.error("Error adding comment to the issue {}, [{}] {}", issue.getKey(), response.getStatus(), response.getStatusText()); } else { LOGGER.debug("Successfully added comment to the issue {}", issue.getKey()); } } }
public static <V> void waitFor(Future<V> task, final Invocation invocation) { if (task instanceof Promise) { Promise<V> smartFuture = (Promise<V>) task; smartFuture.onRedeem(new F.Action<F.Promise<V>>() { @Override public void invoke(Promise<V> result) { executor.submit(invocation); } }); } else { synchronized (WaitForTasksCompletion.class) { if (instance == null) { instance = new WaitForTasksCompletion(); Logger.warn("Start WaitForTasksCompletion"); instance.start(); } instance.queue.put(task, invocation); } } }
@Override public Issue fetchRenderedIssue(final String userId, final AcHost tenant, final Long issueId) { final WS.WSRequestHolder requestHolder = getRequestHolder(tenant, issueId); requestHolder.setQueryParameter("expand", "renderedFields"); final WS.Response response; try { response = requestHolder.get().get(30, TimeUnit.SECONDS); } catch (Exception e) { LOGGER.warn("Unknown error retrieving issue: " + e.getMessage()); return null; } return handleResponse(tenant, issueId, response); }
public static <A, B, C, D> Promise<F.T4<A, B, C, D>> wait4(Promise<A> tA, Promise<B> tB, Promise<C> tC, Promise<D> tD) { final Promise<F.T4<A, B, C, D>> result = new Promise<>(); Promise<List<Object>> t = waitAll(new Promise[]{tA, tB, tC, tD}); t.onRedeem(new F.Action<Promise<List<Object>>>() { @Override public void invoke(Promise<List<Object>> completed) { List<Object> values = completed.getOrNull(); if(values != null) { result.invoke(new F.T4((A) values.get(0), (B) values.get(1), (C) values.get(2), (D) values.get(3))); } else { result.invokeWithException(completed.exception); } } }); return result; }