private static void sendError(RakamHttpRequest request, HttpResponseStatus status) { HttpServer.returnError(request, status.reasonPhrase(), status); }
@ApiOperation(value = "Install recipe", response = SuccessMessage.class) @POST @ProtectEndpoint(writeOperation = true) @Path("/install") public void installUIRecipe(RakamHttpRequest request, @Named("user_id") Project project) { String contentType = request.headers().get(CONTENT_TYPE); ExportType exportType = Arrays.stream(ExportType.values()) .filter(f -> f.contentType.equals(contentType)) .findAny() .orElse(ExportType.YAML); boolean override = ImmutableList.of(TRUE.toString()).equals(request.params().get("override")); request.bodyHandler(body -> { UIRecipe recipe; try { recipe = exportType.mapper.readValue(body, UIRecipe.class); } catch (IOException e) { returnError(request, e.getMessage(), HttpResponseStatus.BAD_REQUEST); return; } try { UIRecipeHandler.RecipeResult install = installer.install(recipe, project.userId, project.project, override); request.response(JsonHelper.encode(install)).end(); } catch (Exception e) { returnError(request, "Error loading recipe: " + e.getMessage(), HttpResponseStatus.BAD_REQUEST); } }); }
recipe = exportType.mapper.readValue(body, Recipe.class); } catch (IOException e) { returnError(request, e.getMessage(), HttpResponseStatus.BAD_REQUEST); return; request.response(JsonHelper.encode(SuccessMessage.success())).end(); } catch (Exception e) { returnError(request, "Error loading recipe: " + e.getMessage(), HttpResponseStatus.BAD_REQUEST);
final List<String> query = params.get("query"); if (query.isEmpty()) { HttpServer.returnError(request, BAD_REQUEST.reasonPhrase(), BAD_REQUEST); return; HttpServer.returnError(request, FORBIDDEN.reasonPhrase(), FORBIDDEN); return; read = JsonHelper.readSafe(body, ExportQuery.class); } catch (IOException e) { HttpServer.returnError(request, "Couldn't parse body: " + e.getMessage(), BAD_REQUEST); return; HttpServer.returnError(request, "Couldn't generate file: " + ex.getMessage(), BAD_REQUEST); return;
body = future.get(); } catch (Throwable e) { returnError(request, "Error executing callback code", INTERNAL_SERVER_ERROR); LOGGER.warn(e, "Error executing webhook callback"); String prefix = "webhook." + key.project + "." + key.identifier; } else { if (!(body instanceof ScriptObjectMirror)) { returnError(request, "The script must return an object {collection: '', properties: {}}", BAD_REQUEST); returnError(request, "JSON couldn't parsed: " + message, BAD_REQUEST); return; } catch (IOException e) { returnError(request, "JSON couldn't parsed: " + e.getMessage(), BAD_REQUEST); return; } catch (RakamException e) { LogUtil.logException(request, e); returnError(request, e.getMessage(), e.getStatusCode()); return; } catch (HttpRequestException e) { returnError(request, e.getMessage(), e.getStatusCode()); return; } catch (IllegalArgumentException e) { LogUtil.logException(request, e); returnError(request, e.getMessage(), BAD_REQUEST); return; } catch (Exception e) { LOGGER.error(e, "Error while collecting event");
@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(); }); }
@JsonRequest @ApiOperation(value = "Set user properties once", request = User.class, response = Integer.class) @ApiResponses(value = {@ApiResponse(code = 404, message = "User does not exist.")}) @Path("/set_properties_once") public void setPropertiesOnce(RakamHttpRequest request) { request.bodyHandler(s -> { User req; try { req = JsonHelper.readSafe(s, User.class); } catch (IOException e) { returnError(request, e.getMessage(), BAD_REQUEST); return; } String project = apiKeyService.getProjectOfApiKey(req.api.apiKey, WRITE_KEY); DefaultFullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, wrappedBuffer(OK_MESSAGE)); response.headers().set(ACCESS_CONTROL_ALLOW_ORIGIN, request.headers().get(ORIGIN)); List<Cookie> cookies = mapProperties(project, req, request); if (cookies != null) { response.headers().add(SET_COOKIE, STRICT.encode(cookies)); } String headerList = getHeaderList(response.headers().iterator()); if (headerList != null) { response.headers().set(ACCESS_CONTROL_EXPOSE_HEADERS, headerList); } // TODO: we may cache these values and reduce the db hit. service.setUserPropertiesOnce(project, req.id, req.properties); request.response(OK_MESSAGE).end(); }); }
} catch (Exception e) { LogUtil.logException(request, e); returnError(request, e.getMessage(), BAD_REQUEST); return;
returnError(request, result.getError().toString(), BAD_REQUEST); return; } catch (Exception e) { LOGGER.error(e); returnError(request, "Error while generating CSV.", INTERNAL_SERVER_ERROR); return; } catch (Exception e) { LOGGER.error(e); returnError(request, "Error while generating CSV.", INTERNAL_SERVER_ERROR); return;
LOGGER.warn("Error while processing webhook script: " + e.getMessage()); String message = e.getCause() != null ? e.getCause().getMessage() : e.getMessage(); returnError(request, "Error while executing webhook script: " + message, BAD_REQUEST); } catch (Exception e) { LOGGER.error(e); returnError(request, "An error occurred.", INTERNAL_SERVER_ERROR);
@Override public void operationComplete(Future<Object> future) throws Exception { if (future.await(1, TimeUnit.SECONDS)) { Object body = future.getNow(); if (body == null) { return; } if (!(body instanceof ScriptObjectMirror)) { returnError(request, "The script must return an object or array {collection: '', properties: {}}", BAD_REQUEST); } ScriptObjectMirror json = (ScriptObjectMirror) ((ScriptObjectMirror) body).eval("JSON"); Object stringify = json.callMember("stringify", body); request.response(stringify.toString()).end(); } else { byte[] bytes = JsonHelper.encodeAsBytes(errorMessage("Webhook code timeouts.", INTERNAL_SERVER_ERROR)); request.response(bytes, INTERNAL_SERVER_ERROR).end(); } } });
req = JsonHelper.readSafe(s, User.class); } catch (IOException e) { returnError(request, e.getMessage(), BAD_REQUEST); return;
@Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { server.uncaughtExceptionHandler.handle(request, cause); cause.printStackTrace(); HttpServer.returnError(request, "An error occurred", INTERNAL_SERVER_ERROR); ctx.close(); }
return; } catch (UnrecognizedPropertyException e) { returnError(request, "Unrecognized field: " + e.getPropertyName(), BAD_REQUEST); return; } catch (InvalidFormatException e) { returnError(request, format("Field value couldn't validated: %s ", e.getOriginalMessage()), BAD_REQUEST); return; } catch (JsonMappingException e) { returnError(request, e.getCause() != null ? e.getCause().getMessage() : e.getMessage(), BAD_REQUEST); return; } catch (JsonParseException e) { returnError(request, format("Couldn't parse json: %s ", e.getOriginalMessage()), BAD_REQUEST); return; } catch (IOException e) { returnError(request, format("Error while mapping json: ", e.getMessage()), BAD_REQUEST); return;
json = mapper.readValue(o, jsonClazz); } catch (UnrecognizedPropertyException e) { returnError(request, "Unrecognized field: " + e.getPropertyName(), BAD_REQUEST); return; } catch (InvalidFormatException e) { returnError(request, format("Field value couldn't validated: %s ", e.getOriginalMessage()), BAD_REQUEST); return; } catch (JsonMappingException e) { returnError(request, e.getCause() != null ? e.getCause().getClass().getName() + ": " +e.getCause().getMessage() : e.getMessage(), BAD_REQUEST); return; } catch (JsonParseException e) { returnError(request, format("Couldn't parse json: %s ", e.getOriginalMessage()), BAD_REQUEST); return; }catch (DateTimeParseException e) { returnError(request, format("Couldn't parse date value '%s' in json: %s ", e.getParsedString(), e.getMessage()), BAD_REQUEST); return; } catch (IOException e) { returnError(request, format("Error while mapping json: ", e.getMessage()), BAD_REQUEST); return;
request = createRequest(ctx); HttpServer.returnError(request, cause.getMessage(), BAD_REQUEST); HttpServer.returnError(request, e); String errorMessage = "Body is too large"; server.uncaughtExceptionHandler.handle(request, new HttpRequestException(errorMessage, REQUEST_ENTITY_TOO_LARGE)); HttpServer.returnError(request, "Body is too large.", REQUEST_ENTITY_TOO_LARGE); ctx.close();