Java Code Examples for play.mvc.Http.Request

The following examples show how to use play.mvc.Http.Request. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: sunbird-lms-service   Source File: BaseController.java    License: MIT License 6 votes vote down vote up
protected CompletionStage<Result> handleRequest(
    String operation,
    JsonNode requestBodyJson,
    java.util.function.Function requestValidatorFn,
    String pathId,
    String pathVariable,
    boolean isJsonBodyRequired,
    Request httpRequest) {
  return handleRequest(
      operation,
      requestBodyJson,
      requestValidatorFn,
      pathId,
      pathVariable,
      null,
      isJsonBodyRequired,
      httpRequest);
}
 
Example 2
Source Project: sunbird-lms-service   Source File: BaseController.java    License: MIT License 6 votes vote down vote up
/**
 * Common exception response handler method.
 *
 * @param e Exception
 * @param request play.mvc.Http.Request
 * @return Result
 */
public Result createCommonExceptionResponse(Exception e, Request request) {
  Request req = request;
  ProjectCommonException exception = null;
  if (e instanceof ProjectCommonException) {
    exception = (ProjectCommonException) e;
  } else {
    exception =
        new ProjectCommonException(
            ResponseCode.internalError.getErrorCode(),
            ResponseCode.internalError.getErrorMessage(),
            ResponseCode.SERVER_ERROR.getResponseCode());
  }
  generateExceptionTelemetry(request, exception);
  // cleaning request info ...
  return Results.status(
      exception.getResponseCode(), Json.toJson(createResponseOnException(req, exception)));
}
 
Example 3
Source Project: sunbird-lms-service   Source File: BaseController.java    License: MIT License 6 votes vote down vote up
private static Map<String, Object> generateTelemetryInfoForError(Request request) {
  try {
    Map<String, Object> map = new HashMap<>();
    String reqContext = request.flash().get(JsonKey.CONTEXT);
    Map<String, Object> requestInfo =
        objectMapper.readValue(reqContext, new TypeReference<Map<String, Object>>() {});
    if (requestInfo != null) {
      Map<String, Object> contextInfo = (Map<String, Object>) requestInfo.get(JsonKey.CONTEXT);
      map.put(JsonKey.CONTEXT, contextInfo);
    }
    Map<String, Object> params = new HashMap<>();
    params.put(JsonKey.ERR_TYPE, JsonKey.API_ACCESS);
    map.put(JsonKey.PARAMS, params);
    return map;
  } catch (Exception ex) {
    ProjectCommonException.throwServerErrorException(ResponseCode.SERVER_ERROR);
  }
  return Collections.emptyMap();
}
 
Example 4
Source Project: raygun4java   Source File: RaygunPlayJavaRequestMessage.java    License: MIT License 6 votes vote down vote up
public RaygunPlayJavaRequestMessage(Request request) {
    try {
        httpMethod = request.method();
        ipAddress = request.remoteAddress();
        hostName = request.host();
        url = request.uri();
        headers = flattenMap(request.headers());

        Map<String, String[]> queryMap = request.queryString();

        if (queryMap != null) {
            queryString = flattenMap(queryMap);
        }

        Map<String, String[]> formMap = request.body().asFormUrlEncoded();

        if (formMap != null) {
            form = flattenMap(formMap);
        }
    } catch (NullPointerException e) {
        Logger.getLogger("Raygun4Java-Play2").info("Couldn't get all request params: " + e.getMessage());
    }
}
 
Example 5
Source Project: restcommander   Source File: FunctionalTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sends a DELETE request to the application under tests.
 * @param request
 * @param url relative url eg. <em>"/products/1234"</em>
 * @return the response
 */
public static Response DELETE(Request request, Object url) {
    String path = "";
    String queryString = "";
    String turl = url.toString();
    if (turl.contains("?")) {
        path = turl.substring(0, turl.indexOf("?"));
        queryString = turl.substring(turl.indexOf("?") + 1);
    } else {
        path = turl;
    }
    request.method = "DELETE";
    request.url = turl;
    request.path = path;
    request.querystring = queryString;
    if (savedCookies != null) request.cookies = savedCookies;
    request.body = new ByteArrayInputStream(new byte[0]);
    return makeRequest(request);
}
 
Example 6
Source Project: restcommander   Source File: UploadBinder.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public Object bind(String name, Annotation[] annotations, String value, Class actualClass, Type genericType) {
    if (value == null || value.trim().length() == 0) {
        return null;
    }
    try {
        List<Upload> uploads = (List<Upload>) Request.current().args.get("__UPLOADS");
        for (Upload upload : uploads) {
            if (upload.getFieldName().equals(value) && upload.getSize() > 0) {
                return upload;
            }
        }
        if (Params.current().get(value + "_delete_") != null) {
            return null;
        }
        return Binder.MISSING;
    } catch (Exception e) {
        Logger.error("", e);
        throw new UnexpectedException(e);
    }
}
 
Example 7
Source Project: restcommander   Source File: FileArrayBinder.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public File[] bind(String name, Annotation[] annotations, String value, Class actualClass, Type genericType) {
    if (value == null || value.trim().length() == 0) {
        return null;
    }
    List<Upload> uploads = (List<Upload>) Request.current().args.get("__UPLOADS");
    List<File> fileArray = new ArrayList<File>();
    for (Upload upload : uploads) {
        if (upload.getFieldName().equals(value)) {
            File file = upload.asFile();
            if (file.length() > 0) {
                fileArray.add(file);
            }
        }
    }
    return fileArray.toArray(new File[fileArray.size()]);
}
 
Example 8
Source Project: restcommander   Source File: FileBinder.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public File bind(String name, Annotation[] annotations, String value, Class actualClass, Type genericType) {
    if (value == null || value.trim().length() == 0) {
        return null;
    }
    List<Upload> uploads = (List<Upload>) Request.current().args.get("__UPLOADS");
    for (Upload upload : uploads) {
        if (upload.getFieldName().equals(value)) {
            File file = upload.asFile();
            if (file.length() > 0) {
                return file;
            }
            return null;
        }
    }
    return null;
}
 
Example 9
Source Project: restcommander   Source File: BinaryBinder.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public Object bind(String name, Annotation[] annotations, String value, Class actualClass, Type genericType) {
    if (value == null || value.trim().length() == 0) {
        return null;
    }
    try {
        Model.BinaryField b = (Model.BinaryField) actualClass.newInstance();
        List<Upload> uploads = (List<Upload>) Request.current().args.get("__UPLOADS");
        for (Upload upload : uploads) {
            if (upload.getFieldName().equals(value) && upload.getSize() > 0) {
                b.set(upload.asStream(), upload.getContentType());
                return b;
            }
        }
        if (Params.current().get(value + "_delete_") != null) {
            return null;
        }
        return Binder.MISSING;
    } catch (Exception e) {
        throw new UnexpectedException(e);
    }
}
 
Example 10
Source Project: restcommander   Source File: Controller.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Render a specific template.
 *
 * @param templateName The template name.
 * @param args The template data.
 */
protected static void renderTemplate(String templateName, Map<String,Object> args) {
    // Template datas
    Scope.RenderArgs templateBinding = Scope.RenderArgs.current();
    templateBinding.data.putAll(args);
    templateBinding.put("session", Scope.Session.current());
    templateBinding.put("request", Http.Request.current());
    templateBinding.put("flash", Scope.Flash.current());
    templateBinding.put("params", Scope.Params.current());
    templateBinding.put("errors", Validation.errors());
    try {
        Template template = TemplateLoader.load(template(templateName));
        throw new RenderTemplate(template, templateBinding.data);
    } catch (TemplateNotFoundException ex) {
        if (ex.isSourceAvailable()) {
            throw ex;
        }
        StackTraceElement element = PlayException.getInterestingStrackTraceElement(ex);
        if (element != null) {
            throw new TemplateNotFoundException(templateName, Play.classes.getApplicationClass(element.getClassName()), element.getLineNumber());
        } else {
            throw ex;
        }
    }
}
 
Example 11
Source Project: restcommander   Source File: ActionInvoker.java    License: Apache License 2.0 6 votes vote down vote up
public static Object invokeControllerMethod(Method method, Object[] forceArgs) throws Exception {
    if (Modifier.isStatic(method.getModifiers()) && !method.getDeclaringClass().getName().matches("^controllers\\..*\\$class$")) {
        return invoke(method, null, forceArgs == null ? getActionMethodArgs(method, null) : forceArgs);
    } else if (Modifier.isStatic(method.getModifiers())) {
        Object[] args = getActionMethodArgs(method, null);
        args[0] = Http.Request.current().controllerClass.getDeclaredField("MODULE$").get(null);
        return invoke(method, null, args);
    } else {
        Object instance = null;
        try {
            instance = method.getDeclaringClass().getDeclaredField("MODULE$").get(null);
        } catch (Exception e) {
            Annotation[] annotations = method.getDeclaredAnnotations();
            String annotation = Utils.getSimpleNames(annotations);
            if (!StringUtils.isEmpty(annotation)) {
                throw new UnexpectedException("Method public static void " + method.getName() + "() annotated with " + annotation + " in class " + method.getDeclaringClass().getName() + " is not static.");
            }
            // TODO: Find a better error report
            throw new ActionNotFoundException(Http.Request.current().action, e);
        }
        return invoke(method, instance, forceArgs == null ? getActionMethodArgs(method, instance) : forceArgs);
    }
}
 
Example 12
Source Project: restcommander   Source File: FunctionalTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * sends a GET request to the application under tests.
 * @param request
 * @param url relative url such as <em>"/products/1234"</em>
 * @return the response
 */
public static Response GET(Request request, Object url) {
    String path = "";
    String queryString = "";
    String turl = url.toString();
    if (turl.contains("?")) {
        path = turl.substring(0, turl.indexOf("?"));
        queryString = turl.substring(turl.indexOf("?") + 1);
    } else {
        path = turl;
    }
    request.method = "GET";
    request.url = turl;
    request.path = path;
    request.querystring = queryString;
    request.body = new ByteArrayInputStream(new byte[0]);
    if (savedCookies != null) request.cookies = savedCookies;
    return makeRequest(request);
}
 
Example 13
Source Project: NationStatesPlusPlus   Source File: RMBController.java    License: MIT License 6 votes vote down vote up
private static Function<JsonNode, Promise<Result>> getAsyncResult(final Request request, final Response response, final String cacheLen) {
	return new Function<JsonNode, Promise<Result>>() {
		@Override
		public Promise<Result> apply(final JsonNode node) throws Throwable {
			return Promise.wrap(akka.dispatch.Futures.future((new Callable<Result>() {
				@Override
				public Result call() throws Exception {
					Result result = Utils.handleDefaultGetHeaders(request, response, String.valueOf(node.hashCode()), cacheLen);
					if (result != null) {
						return result;
					}
					return Results.ok(node).as("application/json");
				}
				
			}), Akka.system().dispatcher()));
		}
	};
}
 
Example 14
Source Project: restcommander   Source File: FunctionalTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sends a POST request to the application under tests.
 * @param request
 * @param url relative url such as <em>"/products/1234"</em>
 * @param contenttype content-type of the request
 * @param body posted data
 * @return the response
 */
public static Response POST(Request request, Object url, String contenttype, InputStream body) {
    String path = "";
    String queryString = "";
    String turl = url.toString();
    if (turl.contains("?")) {
        path = turl.substring(0, turl.indexOf("?"));
        queryString = turl.substring(turl.indexOf("?") + 1);
    } else {
        path = turl;
    }
    request.method = "POST";
    request.contentType = contenttype;
    request.url = turl;
    request.path = path;
    request.querystring = queryString;
    request.body = body;
    if (savedCookies != null) request.cookies = savedCookies;
    return makeRequest(request);
}
 
Example 15
Source Project: sunbird-lms-service   Source File: BaseController.java    License: MIT License 5 votes vote down vote up
protected CompletionStage<Result> handleRequest(
    String operation,
    JsonNode requestBodyJson,
    Function requestValidatorFn,
    Request httpRequest) {
  return handleRequest(
      operation, requestBodyJson, requestValidatorFn, null, null, true, httpRequest);
}
 
Example 16
Source Project: sunbird-lms-service   Source File: BaseController.java    License: MIT License 5 votes vote down vote up
protected CompletionStage<Result> handleRequest(
    String operation,
    String pathId,
    String pathVariable,
    boolean isJsonBodyRequired,
    Request httpRequest) {
  return handleRequest(
      operation, null, null, pathId, pathVariable, isJsonBodyRequired, httpRequest);
}
 
Example 17
Source Project: sunbird-lms-service   Source File: BaseController.java    License: MIT License 5 votes vote down vote up
protected CompletionStage<Result> handleRequest(
    String operation,
    JsonNode requestBodyJson,
    Function requestValidatorFn,
    Map<String, String> headers,
    Request httpRequest) {
  return handleRequest(
      operation, requestBodyJson, requestValidatorFn, null, null, headers, true, httpRequest);
}
 
Example 18
Source Project: sunbird-lms-service   Source File: BaseController.java    License: MIT License 5 votes vote down vote up
protected CompletionStage<Result> handleRequest(
    String operation,
    Function requestValidatorFn,
    String pathId,
    String pathVariable,
    Request httpRequest) {
  return handleRequest(
      operation, null, requestValidatorFn, pathId, pathVariable, false, httpRequest);
}
 
Example 19
Source Project: restcommander   Source File: FunctionalTest.java    License: Apache License 2.0 5 votes vote down vote up
public static void makeRequest(final Request request, final Response response) {
    final Future invocationResult = TestEngine.functionalTestsExecutor.submit(new Invoker.Invocation() {

        @Override
        public void execute() throws Exception {
        	renderArgs.clear();
            ActionInvoker.invoke(request, response);
            
            if(RenderArgs.current().data != null) {
            	renderArgs.putAll(RenderArgs.current().data);
            }
        }

        @Override
        public InvocationContext getInvocationContext() {
            ActionInvoker.resolve(request, response);
            return new InvocationContext(Http.invocationType,
                    request.invokedMethod.getAnnotations(),
                    request.invokedMethod.getDeclaringClass().getAnnotations());
        }

    });
    try {
        invocationResult.get(30, TimeUnit.SECONDS);
        if (savedCookies == null) {
            savedCookies = new HashMap<String, Http.Cookie>();
        }
        for(Map.Entry<String,Http.Cookie> e : response.cookies.entrySet()) {
            // If Max-Age is unset, browsers discard on exit; if
            // 0, they discard immediately.
            if(e.getValue().maxAge == null || e.getValue().maxAge > 0) {
                savedCookies.put(e.getKey(), e.getValue());
            }
        }
        response.out.flush();
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
 
Example 20
Source Project: sunbird-lms-service   Source File: BaseController.java    License: MIT License 5 votes vote down vote up
protected CompletionStage<Result> handleRequest(
    String operation,
    JsonNode requestBodyJson,
    Function requestValidatorFn,
    String pathId,
    String pathVariable,
    Map<String, String> headers,
    boolean isJsonBodyRequired,
    Request httpRequest) {
  try {
    org.sunbird.common.request.Request request = null;
    if (!isJsonBodyRequired) {
      request = createAndInitRequest(operation, httpRequest);
    } else {
      request = createAndInitRequest(operation, requestBodyJson, httpRequest);
    }
    if (pathId != null) {
      request.getRequest().put(pathVariable, pathId);
      request.getContext().put(pathVariable, pathId);
    }
    if (requestValidatorFn != null) requestValidatorFn.apply(request);
    if (headers != null) request.getContext().put(JsonKey.HEADER, headers);

    ProjectLogger.log(
        "BaseController:handleRequest for operation: "
            + operation
            + " requestId: "
            + request.getRequestId(),
        LoggerEnum.INFO.name());
    return actorResponseHandler(getActorRef(), request, timeout, null, httpRequest);
  } catch (Exception e) {
    ProjectLogger.log(
        "BaseController:handleRequest for operation: "
            + operation
            + " Exception occurred with error message = "
            + e.getMessage(),
        e);
    return CompletableFuture.completedFuture(createCommonExceptionResponse(e, httpRequest));
  }
}
 
Example 21
Source Project: sunbird-lms-service   Source File: BaseController.java    License: MIT License 5 votes vote down vote up
protected CompletionStage<Result> handleSearchRequest(
    String operation,
    JsonNode requestBodyJson,
    Function requestValidatorFn,
    String pathId,
    String pathVariable,
    Map<String, String> headers,
    String esObjectType,
    Request httpRequest) {
  try {
    org.sunbird.common.request.Request request = null;
    if (null != requestBodyJson) {
      request = createAndInitRequest(operation, requestBodyJson, httpRequest);
    } else {
      ProjectCommonException.throwClientErrorException(ResponseCode.invalidRequestData, null);
    }
    if (pathId != null) {
      request.getRequest().put(pathVariable, pathId);
      request.getContext().put(pathVariable, pathId);
    }
    if (requestValidatorFn != null) requestValidatorFn.apply(request);
    if (headers != null) request.getContext().put(JsonKey.HEADER, headers);
    if (StringUtils.isNotBlank(esObjectType)) {
      List<String> esObjectTypeList = new ArrayList<>();
      esObjectTypeList.add(esObjectType);
      ((Map) (request.getRequest().get(JsonKey.FILTERS)))
          .put(JsonKey.OBJECT_TYPE, esObjectTypeList);
    }
    request.getRequest().put(JsonKey.REQUESTED_BY, httpRequest.flash().get(JsonKey.USER_ID));
    return actorResponseHandler(getActorRef(), request, timeout, null, httpRequest);
  } catch (Exception e) {
    ProjectLogger.log(
        "BaseController:handleRequest: Exception occurred with error message = " + e.getMessage(),
        e);
    return CompletableFuture.completedFuture(createCommonExceptionResponse(e, httpRequest));
  }
}
 
Example 22
Source Project: sunbird-lms-service   Source File: BaseController.java    License: MIT License 5 votes vote down vote up
/**
 * This method will create failure response
 *
 * @param request Request
 * @param code ResponseCode
 * @param headerCode ResponseCode
 * @return Response
 */
public static Response createFailureResponse(
    Request request, ResponseCode code, ResponseCode headerCode) {

  Response response = new Response();
  response.setVer(getApiVersion(request.path()));
  response.setId(getApiResponseId(request));
  response.setTs(ProjectUtil.getFormattedDate());
  response.setResponseCode(headerCode);
  response.setParams(createResponseParamObj(code, null, request.flash().get(JsonKey.REQUEST_ID)));
  return response;
}
 
Example 23
Source Project: restcommander   Source File: CorePlugin.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Intercept /@status and check that the Authorization header is valid. 
 * Then ask each plugin for a status dump and send it over the HTTP response.
 *
 * You can ask the /@status using the authorization header and putting your status secret key in it.
 * Prior to that you would be required to start play with  a -DstatusKey=yourkey
 */
@Override
public boolean rawInvocation(Request request, Response response) throws Exception {
    if (Play.mode == Mode.DEV && request.path.equals("/@kill")) {
        System.out.println("@KILLED");
        if (Play.standalonePlayServer) {
            System.exit(0);
        } else {
            Logger.error("Cannot execute @kill since Play is not running as standalone server");
        }
    }
    if (request.path.equals("/@status") || request.path.equals("/@status.json")) {
        if(!Play.started) {
            response.print("Application is not started");
            response.status = 503;
            return true;
        }
        response.contentType = request.path.contains(".json") ? "application/json" : "text/plain";
        Header authorization = request.headers.get("authorization");
        if (authorization != null && (Crypto.sign("@status").equals(authorization.value()) || System.getProperty("statusKey", Play.secretKey).equals(authorization.value()))) {
            response.print(computeApplicationStatus(request.path.contains(".json")));
            response.status = 200;
            return true;
        }
        response.status = 401;
        if (response.contentType.equals("application/json")) {
            response.print("{\"error\": \"Not authorized\"}");
        } else {
            response.print("Not authorized");
        }
        return true;
    }
    return super.rawInvocation(request, response);
}
 
Example 24
Source Project: sunbird-lms-service   Source File: BaseController.java    License: MIT License 5 votes vote down vote up
/**
 * This method will handle response in case of exception
 *
 * @param request play.mvc.Http.Request
 * @param exception ProjectCommonException
 * @return Response
 */
public static Response createResponseOnException(
    Request request, ProjectCommonException exception) {
  ProjectLogger.log(
      exception != null ? exception.getMessage() : "Message is not coming",
      exception,
      generateTelemetryInfoForError(request));
  Response response = new Response();
  response.setVer("");
  if (request != null) {
    response.setVer(getApiVersion(request.path()));
  }
  response.setId(getApiResponseId(request));
  response.setTs(ProjectUtil.getFormattedDate());
  response.setResponseCode(ResponseCode.getHeaderResponseCode(exception.getResponseCode()));
  ResponseCode code = ResponseCode.getResponse(exception.getCode());
  if (code == null) {
    code = ResponseCode.SERVER_ERROR;
  }
  response.setParams(
      createResponseParamObj(
          code, exception.getMessage(), request.flash().get(JsonKey.REQUEST_ID)));
  if (response.getParams() != null) {
    response.getParams().setStatus(response.getParams().getStatus());
    if (exception.getCode() != null) {
      response.getParams().setStatus(exception.getCode());
    }
    if (!StringUtils.isBlank(response.getParams().getErrmsg())
        && response.getParams().getErrmsg().contains("{0}")) {
      response.getParams().setErrmsg(exception.getMessage());
    }
  }
  return response;
}
 
Example 25
Source Project: sunbird-lms-service   Source File: BaseController.java    License: MIT License 5 votes vote down vote up
/**
 * This method will create common response for all controller method
 *
 * @param response Object
 * @param key String
 * @param request play.mvc.Http.Request
 * @return Result
 */
public Result createCommonResponse(Object response, String key, Request request) {
  Response courseResponse = (Response) response;
  if (!StringUtils.isBlank(key)) {
    Object value = courseResponse.getResult().get(JsonKey.RESPONSE);
    courseResponse.getResult().remove(JsonKey.RESPONSE);
    courseResponse.getResult().put(key, value);
  }
  return BaseController.createSuccessResponse(request, courseResponse);
}
 
Example 26
Source Project: sunbird-lms-service   Source File: BaseController.java    License: MIT License 5 votes vote down vote up
private void generateExceptionTelemetry(Request request, ProjectCommonException exception) {
  try {
    String reqContext = request.flash().get(JsonKey.CONTEXT);
    Map<String, Object> requestInfo =
        objectMapper.readValue(reqContext, new TypeReference<Map<String, Object>>() {});
    org.sunbird.common.request.Request reqForTelemetry = new org.sunbird.common.request.Request();
    Map<String, Object> params = (Map<String, Object>) requestInfo.get(JsonKey.ADDITIONAL_INFO);
    params.put(JsonKey.LOG_TYPE, JsonKey.API_ACCESS);
    params.put(JsonKey.MESSAGE, "");
    params.put(JsonKey.METHOD, request.method());
    params.put("err", exception.getResponseCode() + "");
    params.put("errtype", exception.getCode());
    long startTime = (Long) params.get(JsonKey.START_TIME);
    params.put(JsonKey.DURATION, calculateApiTimeTaken(startTime));
    removeFields(params, JsonKey.START_TIME);
    params.put(JsonKey.STATUS, String.valueOf(exception.getResponseCode()));
    params.put(JsonKey.LOG_LEVEL, "error");
    params.put(JsonKey.STACKTRACE, generateStackTrace(exception.getStackTrace()));
    reqForTelemetry.setRequest(
        generateTelemetryRequestForController(
            TelemetryEvents.ERROR.getName(),
            params,
            (Map<String, Object>) requestInfo.get(JsonKey.CONTEXT)));
    TelemetryWriter.write(reqForTelemetry);
  } catch (Exception ex) {
    ex.printStackTrace();
  }
}
 
Example 27
Source Project: sunbird-lms-service   Source File: BaseController.java    License: MIT License 5 votes vote down vote up
private Result createClientErrorResponse(Request httpReq, ClientErrorResponse response) {
  ClientErrorResponse errorResponse = response;
  generateExceptionTelemetry(httpReq, errorResponse.getException());
  Response responseObj = createResponseOnException(httpReq, errorResponse.getException());
  responseObj.getResult().putAll(errorResponse.getResult());
  return Results.status(errorResponse.getException().getResponseCode(), Json.toJson(responseObj));
}
 
Example 28
Source Project: sunbird-lms-service   Source File: BaseController.java    License: MIT License 5 votes vote down vote up
public void setContextData(Http.Request httpReq, org.sunbird.common.request.Request reqObj) {
  try {
    String reqContext = httpReq.flash().get(JsonKey.CONTEXT);
    Map<String, Object> requestInfo =
        objectMapper.readValue(reqContext, new TypeReference<Map<String, Object>>() {});
    reqObj.setRequestId(httpReq.flash().get(JsonKey.REQUEST_ID));
    reqObj.getContext().putAll((Map<String, Object>) requestInfo.get(JsonKey.CONTEXT));
    reqObj.getContext().putAll((Map<String, Object>) requestInfo.get(JsonKey.ADDITIONAL_INFO));
  } catch (Exception ex) {
    ProjectCommonException.throwServerErrorException(ResponseCode.SERVER_ERROR);
  }
}
 
Example 29
Source Project: sunbird-lms-service   Source File: BaseController.java    License: MIT License 5 votes vote down vote up
public Map<String, String> getAllRequestHeaders(Request request) {
  Map<String, String> map = new HashMap<>();
  Map<String, List<String>> headers = request.getHeaders().toMap();
  Iterator<Map.Entry<String, List<String>>> itr = headers.entrySet().iterator();
  while (itr.hasNext()) {
    Map.Entry<String, List<String>> entry = itr.next();
    map.put(entry.getKey(), entry.getValue().get(0));
  }
  return map;
}
 
Example 30
Source Project: ground   Source File: GroundUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static Result handleException(Throwable e, Request request) {
  if (e.getCause().getCause() instanceof GroundException) {
    return badRequest(GroundUtils.getClientError(request, e.getCause().getCause(), ExceptionType.ITEM_NOT_FOUND));
  } else {
    return internalServerError(GroundUtils.getServerError(request, e.getCause().getCause()));
  }
}