@Path("/display/*") @GET public void display(RakamHttpRequest request) { if (!database.isPresent()) { throw new RakamException("Custom page feature is not implemented", NOT_IMPLEMENTED); } String path = request.path().substring(21); String[] projectCustomPage = path.split("/", 3); byte[] bytes; try { InputStream file = database.get().getFile(Integer.parseInt(projectCustomPage[0]), projectCustomPage[1], projectCustomPage[2]); if (file == null) { request.response(NOT_FOUND.reasonPhrase(), NOT_FOUND).end(); } bytes = ByteStreams.toByteArray(file); } catch (IOException e) { throw Throwables.propagate(e); } HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK); response.headers().set(CONTENT_TYPE, "text/html"); HttpHeaders.setContentLength(response, bytes.length); request.context().write(response); request.context().write(Unpooled.wrappedBuffer(bytes)); ChannelFuture lastContentFuture = request.context().writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); if (!HttpHeaders.isKeepAlive(request)) { lastContentFuture.addListener(ChannelFutureListener.CLOSE); } }
@ApiOperation(value = "Export recipe", response = UIRecipe.class, authorizations = @Authorization(value = "master_key") ) @GET @Path("/export") public void exportUIRecipe(@HeaderParam("Accept") String contentType, @Named("user_id") Project project, RakamHttpRequest request) throws JsonProcessingException { request.bodyHandler(s -> { UIRecipe export = installer.export(project.userId, project.project); ExportType exportType = Arrays.stream(ExportType.values()) .filter(f -> f.contentType.equals(contentType)) .findAny() .orElse(ExportType.YAML); ByteBuf buffer; try { buffer = Unpooled.wrappedBuffer(exportType.mapper.writeValueAsBytes(export)); } catch (JsonProcessingException e) { throw Throwables.propagate(e); } DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buffer); response.headers().add(CONTENT_TYPE, exportType.contentType); if (request.headers().contains(ORIGIN)) { response.headers().set(ACCESS_CONTROL_ALLOW_ORIGIN, request.headers().get(ORIGIN)); } request.response(response).end(); }); }
@Override public Collection<Cookie> cookies() { return request.cookies(); }
@Path("/data") @GET @IgnoreApi public void data(RakamHttpRequest request) { Map<String, List<String>> params = request.params(); List<String> api_key = params.get("read_key"); if (api_key == null || api_key.isEmpty()) { request.response("\"read_key is missing\"", BAD_REQUEST).end(); return; } // since this endpoint is created for clients to read the ab-testing rule, // the permission is WRITE_KEY String project = apiKeyService.getProjectOfApiKey(api_key.get(0), ApiKeyService.AccessKeyType.WRITE_KEY); request.response(JsonHelper.encodeAsBytes(metadata.getReports(project))) .end(); }
@GET @IgnoreApi @ApiOperation(value = "Collect event", response = Integer.class) @Path("/collect/*") public void collectGet(RakamHttpRequest request) { String identifier = request.path().substring(20); List<String> writeKeyList = request.params().get("write_key"); if (writeKeyList == null || writeKeyList.isEmpty()) { throw new RakamException("write_key query parameter is null", FORBIDDEN); } String project = apiKeyService.getProjectOfApiKey(writeKeyList.get(0), WRITE_KEY); call(request, project, identifier, request.params(), request.headers(), null); }
@POST @IgnoreApi @ApiOperation(value = "Collect event", response = Integer.class) @Path("/collect/*") public void collectPost(RakamHttpRequest request) { String identifier = request.path().substring(20); List<String> writeKeyList = request.params().get("write_key"); if (writeKeyList == null || writeKeyList.isEmpty()) { throw new RakamException("write_key query parameter is null", FORBIDDEN); } String project = apiKeyService.getProjectOfApiKey(writeKeyList.get(0), WRITE_KEY); request.bodyHandler(inputStream -> { String data; try { data = new String(ByteStreams.toByteArray(inputStream), CharsetUtil.UTF_8); } catch (IOException e) { throw new RakamException("Unable to parse data: " + e.getMessage(), INTERNAL_SERVER_ERROR); } call(request, project, identifier, request.params(), request.headers(), data); }); }
@ApiOperation(value = "Batch operation on a single user properties", request = SingleUserBatchOperationRequest.class, response = Integer.class, authorizations = {@Authorization(value = "write_key")}) @ApiResponses(value = {@ApiResponse(code = 404, message = "User does not exist.")}) @Path("/batch") @JsonRequest public void batchSingleUserOperations(RakamHttpRequest request) { request.bodyHandler(s -> { SingleUserBatchOperationRequest req; try { req = JsonHelper.read(s, SingleUserBatchOperationRequest.class); } catch (Exception e) { returnError(request, e.getMessage(), BAD_REQUEST); return; } String project = apiKeyService.getProjectOfApiKey(req.api.apiKey, WRITE_KEY); InetAddress socketAddress = ((InetSocketAddress) request.context().channel() .remoteAddress()).getAddress(); DefaultFullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, wrappedBuffer(OK_MESSAGE)); List<Cookie> cookies = mapEvent(mapper -> mapper.map(project, req.data, new HttpRequestParams(request), socketAddress)); service.batch(project, req.data); setBrowser(request, response); if (cookies != null && !cookies.isEmpty()) { response.headers().add(SET_COOKIE, STRICT.encode(cookies)); } request.response(response).end(); }); }
@Path("/callback") @JsonRequest public void callback(RakamHttpRequest request) { request.bodyHandler(inputStream -> { String post; try { response.headers().add(SET_COOKIE, STRICT.encode(loginResponseForUser.getCookies())); request.response(response).end(); });
@GET @ApiOperation(value = "Show webhook images", response = Integer.class) @Path("/image/*") public void image(RakamHttpRequest request) { String substring = request.path().substring("/ui/webhook/image".length() + 1); if (!substring.matches("^[A-Za-z0-9-]+$")) { throw new RakamException(FORBIDDEN); } URL resource = getClass().getResource("/webhook/" + substring + "/image.png"); if (resource == null) { throw new RakamException(NOT_FOUND); } byte[] script; try { script = ByteStreams.toByteArray(resource.openStream()); } catch (IOException e) { throw Throwables.propagate(e); } DefaultFullHttpResponse resp = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(script)); resp.headers().add(ACCESS_CONTROL_ALLOW_ORIGIN, "*"); resp.headers().add(CACHE_CONTROL, "private, max-age=86400"); HttpHeaders.setContentLength(resp, script.length); resp.headers().set(CONTENT_TYPE, "image/png"); request.response(resp).end(); }
public static void returnError(RakamHttpRequest request, String message, HttpResponseStatus statusCode) { byte[] bytes; try { bytes = DEFAULT_MAPPER.writeValueAsBytes(new ErrorMessage(ImmutableList.of(JsonAPIError.title(message)), null)); } catch (JsonProcessingException e) { throw new RuntimeException(); } request.response(bytes, statusCode).headers().set("Content-Type", "application/json"); request.end(); }
public void handle(RakamHttpRequest request) { String path = cleanPath(request.path()); int lastIndex = path.length() - 1; if (lastIndex > 0 && path.charAt(lastIndex) == '/') { path = path.substring(0, lastIndex); } HttpMethod method = request.getMethod(); final HttpRequestHandler handler = routes.get(new PatternBinding(method, path)); if (handler != null) { if (handler instanceof WebSocketService) { request.context().attr(PATH).set(path); } handler.handle(request); } else { for (Map.Entry<PatternBinding, HttpRequestHandler> prefixRoute : prefixRoutes) { if (method.equals(prefixRoute.getKey().method) && path.startsWith(prefixRoute.getKey().pattern)) { prefixRoute.getValue().handle(request); return; } } noMatch.handle(request); } }
.error(e.getMessage() + "\n" + request.getUri() + "\n" + collect + "Body:\n" + data + "\n--------\n"); return; request.response(saved ? "1" : "0").end(); } else { byte[] bytes = JsonHelper.encodeAsBytes(errorMessage("Webhook code timeouts.", INTERNAL_SERVER_ERROR)); request.response(bytes, INTERNAL_SERVER_ERROR).end();
public void main(RakamHttpRequest request) { if (!request.getDecoderResult().isSuccess()) { sendError(request, BAD_REQUEST); return; } if (request.getMethod() != GET) { sendError(request, NOT_FOUND); return; } final String uri = request.path(); int idx = uri.indexOf("/static/"); File file; if (idx > -1) { final String path = sanitizeUri(uri); if (path == null) { sendError(request, FORBIDDEN); return; } file = new File(path); } else { file = new File(directory.getPath(), "index.html"); } sendFile(request, file); }
@GET @Path("/") public void export(RakamHttpRequest request) { final Map<String, List<String>> params = request.params(); final List<String> query = params.get("query"); if (query.isEmpty()) { response.headers().set("Content-Disposition", "attachment;filename=\"exported_people." + read.exportFormat.name().toLowerCase(Locale.ENGLISH) + "\""); request.context().write(response); ChannelFuture lastContentFuture = request.context().writeAndFlush(Unpooled.wrappedBuffer(result));
@Override public HttpHeaders headers() { return request.headers(); } }
@Override public String getServerName() { return request.context().channel().localAddress().toString(); }
String ifModifiedSince = request.headers().get(IF_MODIFIED_SINCE); if (ifModifiedSince != null && !ifModifiedSince.isEmpty()) { SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US); request.context().write(response); request.context().write(defaultFileRegion, request.context().newProgressivePromise()); ChannelFuture lastContentFuture = request.context().writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
@Override public String getPathTranslated() { return request.path(); }