@Override public byte[] bytes() throws IOException { throw new Err(Status.BAD_REQUEST); }
@Override public String text() throws IOException { throw new Err(Status.BAD_REQUEST); }
@Override public void writeTo(final OutputStream output) throws Exception { throw new Err(Status.BAD_REQUEST); }
private Err typeError(final Class<?> type) { return new Err(Status.BAD_REQUEST, "Can't convert to " + ByteBuffer.class.getName() + " to " + type); } }
@Override public void writeResponseContent(final String content) { try { rsp.send(content); } catch (Throwable ex) { throw new Err(Status.SERVER_ERROR, ex); } }
private static Err handle405(final Set<Route.Definition> routeDefs, final String method, final String path, final MediaType type, final List<MediaType> accept) { if (alternative(routeDefs, method, path).size() > 0) { return new Err(Status.METHOD_NOT_ALLOWED, method); } return null; }
private List<String> paramNames() { try { return req.paramNames(); } catch (Exception ex) { throw new Err(Status.BAD_REQUEST, "Unable to get parameter names", ex); } }
/** * Get a request local attribute. * * @param name Attribute's name. * @param <T> Target type. * @return A local attribute. * @throws Err with {@link Status#BAD_REQUEST}. */ @Nonnull default <T> T get(final String name) { Optional<T> opt = ifGet(name); return opt.orElseThrow( () -> new Err(Status.BAD_REQUEST, "Required local attribute: " + name + " is not present")); }
/** * Get a flash attribute value or throws {@link Err BAD_REQUEST error} if missing. * * @param name Attribute's name. * @return Flash attribute. * @throws Err Bad request error if flash attribute is missing. */ @Nonnull default String flash(final String name) throws Err { return ifFlash(name) .orElseThrow(() -> new Err(Status.BAD_REQUEST, "Required flash attribute: '" + name + "' is not present")); }
@Override @SuppressWarnings("unchecked") public <T> T get(final List<MediaType> types) { Supplier<Object> provider = MediaType .matcher(types) .first(ImmutableList.copyOf(data.keySet())) .map(it -> data.remove(it)) .orElseThrow( () -> new Err(Status.NOT_ACCEPTABLE, Joiner.on(", ").join(types))); return (T) provider.get(); }
public static RouteWithFilter notFound(final String method, final String path) { return new FallbackRoute("404", method, path, MediaType.ALL, (req, rsp, chain) -> { if (!rsp.status().isPresent()) { throw new Err(Status.NOT_FOUND, req.path(true)); } }); }
private List<String> params(final String name, final Function<String, String> xss) { try { List<String> values = new ArrayList<>(); String pathvar = route.vars().get(name); if (pathvar != null) { values.add(pathvar); } values.addAll(req.params(name)); if (xss == null) { return values; } for (int i = 0; i < values.size(); i++) { values.set(i, xss.apply(values.get(i))); } return values; } catch (Throwable ex) { throw new Err(Status.BAD_REQUEST, "Parameter '" + name + "' resulted in error", ex); } }
@Override public Object adapt(int code, WebContext context) { Status statusCode = Status.valueOf(code); if (statusCode.isError()) { throw new Err(statusCode); } // Any other result is already handled by pac4j via webcontext return null; } }
private static Err handle406or415(final Set<Route.Definition> routeDefs, final String method, final String path, final MediaType contentType, final List<MediaType> accept) { for (Route.Definition routeDef : routeDefs) { Optional<Route> route = routeDef.matches(method, path, MediaType.all, MediaType.ALL); if (route.isPresent() && !route.get().pattern().contains("*")) { if (!routeDef.canProduce(accept)) { return new Err(Status.NOT_ACCEPTABLE, accept.stream() .map(MediaType::name) .collect(Collectors.joining(", "))); } if (!contentType.isAny()) { return new Err(Status.UNSUPPORTED_MEDIA_TYPE, contentType.name()); } } } return null; }
static Provider profileProvider(AtomicReference<Registry> registry, Class profile, Function<Request, UserProfile> unauthenticated) { return () -> { Request req = registry.get().require(Request.class); ProfileManager pm = req.require(ProfileManager.class); Object result = pm.getAll(req.ifSession().isPresent()).stream() .filter(profile::isInstance) .findFirst() .orElse(null); if (result == null) { if (unauthenticated == null) { throw new Err(Status.FORBIDDEN, "Not found: " + profile.getSimpleName()); } result = unauthenticated.apply(req); } return result; }; } }
@Override public void send(final Object data, final SuccessCallback success, final OnError err) throws Exception { requireNonNull(data, "Message required."); requireNonNull(success, "Success callback required."); requireNonNull(err, "Error callback required."); synchronized (this) { if (isOpen()) { new WebSocketRendererContext( renderers, ws, produces, StandardCharsets.UTF_8, locale, success, err).render(data); } else { throw new Err(WebSocket.NORMAL, "WebSocket is closed."); } } }
@SuppressWarnings("rawtypes") @Override public void handle(final Request req, final Response rsp) throws Exception { CommonProfile user = req.require(CommonProfile.class); Config config = req.require(Config.class); WebContext ctx = req.require(WebContext.class); AuthorizationChecker authorizationChecker = req.require(AuthorizationChecker.class); Map<String, Authorizer> authorizers = config.getAuthorizers(); log.debug("checking access for: {}", user); if (!authorizationChecker.isAuthorized(ctx, Arrays.asList(user), this.authorizer, authorizers)) { log.debug("forbidden: {}", user); throw new Err(Status.FORBIDDEN); } log.debug("authorized: {}", user); }
/** * Start an application. Fire the {@link #onStart(Throwing.Runnable)} event and the * {@link #onStarted(Throwing.Runnable)} events. * * @param args Application arguments. */ public void start(final String... args) { try { start(args, null); } catch (Throwable x) { stop(); String msg = "An error occurred while starting the application:"; if (throwBootstrapException) { throw new Err(Status.SERVICE_UNAVAILABLE, msg, x); } else { logger(this).error(msg, x); } } }
public void handle(final Client<?, ?> client, final HttpAction action) { if (!rsp.committed()) { int statusCode = action.getCode(); // on error, let jooby handle it if (statusCode >= 400) { if (client instanceof IndirectBasicAuthClient) { rsp.status(statusCode).end(); } else { throw new Err(statusCode, action); } } } } }
@Override public void handle(final Request req, final Response rsp, final Route.Chain chain) throws Throwable { /** * Get or generate a token */ Session session = req.session(); String token = session.get(name).toOptional().orElseGet(() -> { String newToken = generator.apply(req); session.set(name, newToken); return newToken; }); req.set(name, token); if (requireToken.test(req)) { String candidate = req.header(name).toOptional() .orElseGet(() -> req.param(name).toOptional().orElse(null)); if (!token.equals(candidate)) { throw new Err(Status.FORBIDDEN, "Invalid Csrf token: " + candidate); } } chain.next(req, rsp); } }