public void intercept(InterceptorStack stack, ResourceMethod method, Object resourceInstance)
      throws InterceptionException {
    Consumes consumesAnnotation = method.getMethod().getAnnotation(Consumes.class);
    List<String> supported = Arrays.asList(consumesAnnotation.value());

    String contentType = request.getContentType();
    if (!supported.isEmpty() && !supported.contains(contentType)) {
      unsupported(
          String.format(
              "Request with media type [%s]. Expecting one of %s.", contentType, supported));
      return;
    }

    try {
      Deserializer deserializer = deserializers.deserializerFor(contentType, container);
      if (deserializer == null) {
        unsupported(
            String.format("Unable to handle media type [%s]: no deserializer found.", contentType));
        return;
      }

      Object[] deserialized = deserializer.deserialize(request.getInputStream(), method);
      Object[] parameters = methodInfo.getParameters();

      for (int i = 0; i < deserialized.length; i++) {
        if (deserialized[i] != null) {
          parameters[i] = deserialized[i];
        }
      }

      stack.next(method, resourceInstance);
    } catch (IOException e) {
      throw new InterceptionException(e);
    }
  }
  @Override
  public void intercept(InterceptorStack stack, ControllerMethod method, Object instance)
      throws InterceptionException {
    try {
      stack.next(method, instance);
    } catch (Exception e) {

      StringWriter sw = new StringWriter();
      PrintWriter pw = new PrintWriter(sw);

      Throwable cause = e.getCause();
      if (cause != null) {
        if (cause instanceof ConstraintViolationException) {
          Set<ConstraintViolation<?>> constraintViolations =
              ((ConstraintViolationException) cause).getConstraintViolations();
          pw.printf("\nConstraint Violations: \n");
          for (ConstraintViolation<?> constraintViolation : constraintViolations) {
            pw.printf("\t" + constraintViolation.getConstraintDescriptor().getAnnotation() + "\n");
          }
          pw.printf("\n");
          log.error(sw.toString());
        }
        cause.printStackTrace(pw);
      } else {
        e.printStackTrace(pw);
      }

      pw.close();
      result.include("stacktrace", sw.toString());
      throw e;
    }
  }
Esempio n. 3
0
  @Override
  public void intercept(InterceptorStack stack, ControllerMethod method, Object controllerInstance)
      throws InterceptionException {
    Map<String, Object> parameters =
        (Map<String, Object>) session.getAttribute(FLASH_INCLUDED_PARAMETERS);

    if (parameters != null) {
      parameters = new HashMap<>(parameters);

      session.removeAttribute(FLASH_INCLUDED_PARAMETERS);
      for (Entry<String, Object> parameter : parameters.entrySet()) {
        result.include(parameter.getKey(), parameter.getValue());
      }
    }
    response.addRedirectListener(
        new RedirectListener() {
          @Override
          public void beforeRedirect() {
            Map<String, Object> included = result.included();
            if (!included.isEmpty()) {
              try {
                session.setAttribute(FLASH_INCLUDED_PARAMETERS, new HashMap<>(included));
              } catch (IllegalStateException e) {
                LOGGER.warn(
                    "HTTP Session was invalidated. It is not possible to include "
                        + "Result parameters on Flash Scope",
                    e);
              }
            }
          }
        });
    stack.next(method, controllerInstance);
  }
 public void intercept(InterceptorStack stack, ResourceMethod method, Object resourceInstance)
     throws InterceptionException {
   try {
     stack.next(method, resourceInstance);
   } catch (Exception e) {
     logger.error(e);
     result.use(Results.http()).body("Ocorreu um erro na aplicação");
   }
 }
  @Override
  public void intercept(InterceptorStack stack, ResourceMethod method, Object instance)
      throws InterceptionException {

    if (user.isSignedIn()) {
      stack.next(method, instance);
    } else if (isAjaxRequest()) {
      result.use(http()).sendError(SC_UNAUTHORIZED);
    } else {
      result.redirectTo("/?urlAfterLogin=" + getReferer());
    }
  }
 public void intercept(
     final InterceptorStack stack, final ResourceMethod method, final Object instance) {
   Transaction transaction = null;
   try {
     transaction = session.beginTransaction();
     stack.next(method, instance);
     transaction.commit();
   } finally {
     if (transaction.isActive()) {
       transaction.rollback();
     }
   }
 }
  public void intercept(InterceptorStack stack, ResourceMethod method, Object resourceInstance) {
    if (usuarioSession.getUsuario() != null) {
      Permission methodPermission = method.getMethod().getAnnotation(Permission.class);
      Permission controllerPermission =
          method.getResource().getType().getAnnotation(Permission.class);
      if (this.hasAccess(methodPermission) && this.hasAccess(controllerPermission)) {
        stack.next(method, resourceInstance);
      } else {
        result.redirectTo(LoginController.class).acessoNegado();
      }

    } else {
      result.redirectTo(LoginController.class).login();
    }
  }
  public void intercept(
      InterceptorStack stack, ResourceMethod ignorableMethod, Object resourceInstance)
      throws InterceptionException {

    try {
      ResourceMethod method = translator.translate(requestInfo);

      methodInfo.setResourceMethod(method);
      stack.next(method, resourceInstance);
    } catch (ResourceNotFoundException e) {
      resourceNotFoundHandler.couldntFind(requestInfo);
    } catch (MethodNotAllowedException e) {
      LOGGER.debug(e.getMessage(), e);
      methodNotAllowedHandler.deny(requestInfo, e.getAllowedMethods());
    }
  }
  /**
   * Melhoria aplicada ao método, caso o objeto (parâmetro) que foi informado não foi encontrado na
   * consulta do banco de dados, somente irá retornar 404 (Result.nothing()) se o usuário colocou o
   * parâmetro como <code>required=true</code>.
   *
   * @param stack
   * @param method
   * @param resourceInstance
   * @throws InterceptionException
   */
  public void intercept(InterceptorStack stack, ResourceMethod method, Object resourceInstance)
      throws InterceptionException {
    Annotation[][] annotations = method.getMethod().getParameterAnnotations();

    String[] names = provider.parameterNamesFor(method.getMethod());

    Class<?>[] types = method.getMethod().getParameterTypes();

    Object[] args = flash.consumeParameters(method);

    for (int i = 0; i < names.length; i++) {
      Iterable<LoadObject> loads = Iterables.filter(asList(annotations[i]), LoadObject.class);

      if (!isEmpty(loads)) {
        Object loaded = this.load(names[i], types[i]);

        if (loaded == null) {
          // Caso tenha a anotação LoadObject, o fluxo da aplicação será definido de acordo
          // com as definições feitas na anotação.
          LoadObject next = loads.iterator().next();

          if (next != null && next.required()) {
            if (next.redirectToWhenObjectNotFound() != null
                && !next.redirectToWhenObjectNotFound().isEmpty()) {
              logger.info(
                  "Entity not found, the page will be redirected to "
                      + next.redirectToWhenObjectNotFound());
              result.redirectTo(next.redirectToWhenObjectNotFound());
            } else {
              logger.info(
                  "Entity not found, the redirect URL was not specified, then i will be return nothing.");
              result.nothing();
              return;
            }
          }
        }

        if (args != null) args[i] = loaded;
        else request.setAttribute(names[i], loaded);
      }
    }
    flash.includeParameters(method, args);

    stack.next(method, resourceInstance);
  }