@Override public void handle(RestxRequestMatch match, RestxRequest req, RestxResponse resp, RestxContext ctx) throws IOException { String path = match.getPathParam("path"); File file = root.resolve(path).toFile(); if (!file.exists()) { // nothing to do, send NO_CONTENT to be idempotent resp.setStatus(HttpStatus.NO_CONTENT); return; } if (file.isDirectory()) { if (file.list().length > 0) { throw new WebException(HttpStatus.UNAUTHORIZED, "can't delete non empty directory"); } } java.nio.file.Files.delete(file.toPath()); resp.setStatus(HttpStatus.NO_CONTENT); }
/** * Writes this web exception in a RestxResponse. * * This implementation uses the status, contentType and content found on the exception. * Override it to provide custom response. * Note that the implementation is also responsible for logging the exception. * * * @param restxRequest * @param restxResponse the response to write to * @throws IOException in case of IO error. */ public void writeTo(RestxRequest restxRequest, RestxResponse restxResponse) throws IOException { // by default log stack trace at debug level only if (logger.isDebugEnabled()) { logger.debug("request raised WebException - " + restxRequest, this); } restxResponse.setStatus(getStatus()); restxResponse.setContentType(getContentType()); restxResponse.getWriter().print(getContent()); } }
/** * Returns the content to use in the HTTP response generated for this exception. * * Developer's note: override to provide a content different from the exception message. * Alternatively you can override the writeTo method for full control over the response. * * @return the content to use in the response. */ public String getContent() { return getMessage(); }
out.println(ex.toJSON()); } catch (WebException ex) { ex.writeTo(restxRequest, restxResponse); } catch (IllegalArgumentException | IllegalStateException ex) { logger.warn("request raised " + ex.getClass().getSimpleName() + ": " + ex.getMessage(), ex);
out.println(ex.toJSON()); } catch (WebException ex) { ex.writeTo(restxRequest, restxResponse); } catch (IllegalArgumentException | IllegalStateException ex) { logger.warn("request raised " + ex.getClass().getSimpleName() + ": " + ex.getMessage(), ex);
@Override public void handle(RestxRequestMatch match, RestxRequest req, RestxResponse resp, RestxContext ctx) throws IOException { String path = match.getPathParam("path"); File file = root.resolve(path).toFile(); if (!file.exists()) { // nothing to do, send NO_CONTENT to be idempotent resp.setStatus(HttpStatus.NO_CONTENT); return; } if (file.isDirectory()) { if (file.list().length > 0) { throw new WebException(HttpStatus.UNAUTHORIZED, "can't delete non empty directory"); } } java.nio.file.Files.delete(file.toPath()); resp.setStatus(HttpStatus.NO_CONTENT); }
/** * Writes this web exception in a RestxResponse. * * This implementation uses the status, contentType and content found on the exception. * Override it to provide custom response. * Note that the implementation is also responsible for logging the exception. * * * @param restxRequest * @param restxResponse the response to write to * @throws IOException in case of IO error. */ public void writeTo(RestxRequest restxRequest, RestxResponse restxResponse) throws IOException { // by default log stack trace at debug level only if (logger.isDebugEnabled()) { logger.debug("request raised WebException - " + restxRequest, this); } restxResponse.setStatus(getStatus()); restxResponse.setContentType(getContentType()); restxResponse.getWriter().print(getContent()); } }
/** * Returns the content to use in the HTTP response generated for this exception. * * Developer's note: override to provide a content different from the exception message. * Alternatively you can override the writeTo method for full control over the response. * * @return the content to use in the response. */ public String getContent() { return getMessage(); }
@Override public void check(RestxRequest request, RestxRequestMatch requestMatch, Permission permission) { if (permissionFactory.isOpen(permission)) { return; } Optional<? extends RestxPrincipal> principal = RestxSession.current().getPrincipal(); if (!principal.isPresent()) { logger.debug("no principal found: request={}", request); throw new WebException(HttpStatus.UNAUTHORIZED); } Optional<? extends Permission> match = permission.has(principal.get(), createRoleInterpolationMapFrom(request, requestMatch)); if (match.isPresent()) { logger.debug("permission matched: request={} principal={} perm={}", request, principal.get(), match.get()); return; } logger.debug("permission not matched: request={} principal={} permission={}", request, principal.get(), permission); throw new WebException(HttpStatus.FORBIDDEN); }
@Override public void check(RestxRequest request, RestxRequestMatch requestMatch, Permission permission) { if (permissionFactory.isOpen(permission)) { return; } Optional<? extends RestxPrincipal> principal = RestxSession.current().getPrincipal(); if (!principal.isPresent()) { logger.debug("no principal found: request={}", request); throw new WebException(HttpStatus.UNAUTHORIZED); } Optional<? extends Permission> match = permission.has(principal.get(), createRoleInterpolationMapFrom(request, requestMatch)); if (match.isPresent()) { logger.debug("permission matched: request={} principal={} perm={}", request, principal.get(), match.get()); return; } logger.debug("permission not matched: request={} principal={} permission={}", request, principal.get(), permission); throw new WebException(HttpStatus.FORBIDDEN); }
@Override public void handle(RestxRequestMatch match, RestxRequest req, RestxResponse resp, RestxContext ctx) throws IOException { String base64Pwd = req.getHeader("Authorization").get().substring("basic ".length()); String auth = new String(BaseEncoding.base64().decode(base64Pwd), Charsets.UTF_8); int i = auth.indexOf(':'); if (i < 0) { throw new WebException(HttpStatus.BAD_REQUEST, "Invalid Basic Authentication. It must have the form <user>:<pwd>. It was: " + auth); } String u = auth.substring(0, i); String pwd = auth.substring(i + 1); Optional<? extends RestxPrincipal> principal = authenticator.authenticate( u, pwd, ImmutableMap.<String, Object>of()); if (principal.isPresent()) { logger.debug("http basic authenticated '{}'", principal.get().getName()); RestxSession.current().authenticateAs(principal.get()); } else { throw new WebException(HttpStatus.UNAUTHORIZED); } ctx.nextHandlerMatch().handle(req, resp, ctx); }
@Override public void handle(RestxRequestMatch match, RestxRequest req, RestxResponse resp, RestxContext ctx) throws IOException { String base64Pwd = req.getHeader("Authorization").get().substring("basic ".length()); String auth = new String(BaseEncoding.base64().decode(base64Pwd), Charsets.UTF_8); int i = auth.indexOf(':'); if (i < 0) { throw new WebException(HttpStatus.BAD_REQUEST, "Invalid Basic Authentication. It must have the form <user>:<pwd>. It was: " + auth); } String u = auth.substring(0, i); String pwd = auth.substring(i + 1); Optional<? extends RestxPrincipal> principal = authenticator.authenticate( u, pwd, ImmutableMap.<String, Object>of()); if (principal.isPresent()) { logger.debug("http basic authenticated '{}'", principal.get().getName()); RestxSession.current().authenticateAs(principal.get()); } else { throw new WebException(HttpStatus.UNAUTHORIZED); } ctx.nextHandlerMatch().handle(req, resp, ctx); }
throw new WebException(HttpStatus.UNAUTHORIZED); throw new WebException(HttpStatus.UNAUTHORIZED); } else { resp.setStatus(HttpStatus.CREATED); throw new WebException(HttpStatus.UNAUTHORIZED);
public void handleIn(RestxRequest req, RestxResponse resp) { if (req.getHeader("If-None-Match").equals(Optional.of(value))) { throw new WebException(HttpStatus.NOT_MODIFIED); } else { cacheControl.writeTo(resp); resp.setHeader("ETag", value); } }
@GET("/@/api-docs/schemas/{fqcn}") @RolesAllowed(AdminModule.RESTX_ADMIN_ROLE) public String getJsonSchema(String fqcn) { SchemaFactoryWrapper visitor = new SchemaFactoryWrapper(); try { mapper.acceptJsonFormatVisitor(mapper.constructType(Class.forName(fqcn)), visitor); } catch (JsonMappingException e) { throw new IllegalStateException(e); } catch (ClassNotFoundException e) { throw new WebException(HttpStatus.NOT_FOUND); } try { return mapper.writerWithDefaultPrettyPrinter() .writeValueAsString(visitor.finalSchema()); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } }
public void handleIn(RestxRequest req, RestxResponse resp) { if (req.getHeader("If-None-Match").equals(Optional.of(value))) { throw new WebException(HttpStatus.NOT_MODIFIED); } else { cacheControl.writeTo(resp); resp.setHeader("ETag", value); } }
@GET("/@/api-docs/schemas/{fqcn}") @RolesAllowed(AdminModule.RESTX_ADMIN_ROLE) public String getJsonSchema(String fqcn) { SchemaFactoryWrapper visitor = new SchemaFactoryWrapper(); try { mapper.acceptJsonFormatVisitor(mapper.constructType(Class.forName(fqcn)), visitor); } catch (JsonMappingException e) { throw new IllegalStateException(e); } catch (ClassNotFoundException e) { throw new WebException(HttpStatus.NOT_FOUND); } try { return mapper.writerWithDefaultPrettyPrinter() .writeValueAsString(visitor.finalSchema()); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } }
throw new WebException(HttpStatus.UNAUTHORIZED); throw new WebException(HttpStatus.UNAUTHORIZED); } else { resp.setStatus(HttpStatus.CREATED); throw new WebException(HttpStatus.UNAUTHORIZED);
} catch (Exception e) { logger.warn("restx-admin tried sudoing request with {}, but it failed: {}", su.get(), e.toString()); throw new WebException(HttpStatus.BAD_REQUEST, "invalid su session '" + su.get() + "': " + e.toString());
@Override public void handle(RestxRequestMatch match, RestxRequest req, RestxResponse resp, RestxContext ctx) throws IOException { String path = match.getPathParam("path"); File file = root.resolve(path).toFile(); if (!file.exists()) { notFound(match, resp); return; } if (file.isFile()) { resp.setStatus(HttpStatus.OK); resp.setContentType(HTTP.getContentTypeFromExtension(file.getName()).or("application/binary")); Files.asByteSource(file).copyTo(resp.getOutputStream()); } else if (file.isDirectory() && allowDirectoryListing) { resp.setStatus(HttpStatus.OK); resp.setContentType("application/json"); PrintWriter writer = resp.getWriter(); writer.println("["); Path dir = file.toPath(); for (Iterator<Path> iterator = java.nio.file.Files.newDirectoryStream(dir).iterator(); iterator.hasNext(); ) { Path s = iterator.next(); boolean isDirectory = s.toFile().isDirectory(); writer.println("\"" + dir.relativize(s) + (isDirectory ? "/" : "") + "\"" + (iterator.hasNext() ? "," : "") +""); } writer.println("]"); } else { throw new WebException(HttpStatus.UNAUTHORIZED); } }