@Override
  public void onResourceRequested() {

    // this is the callback that retrieves matching choices used to populate the dropdown

    Request request = getRequestCycle().getRequest();
    IRequestParameters params = request.getRequestParameters();

    // retrieve choices matching the search term

    String term = params.getParameterValue("term").toOptionalString();

    int page = params.getParameterValue("page").toInt(1);
    // select2 uses 1-based paging, but in wicket world we are used to
    // 0-based
    page -= 1;

    Response<T> response = new Response<T>();
    provider.query(term, page, response);

    // jsonize and write out the choices to the response

    WebResponse webResponse = (WebResponse) getRequestCycle().getResponse();
    webResponse.setContentType("application/json");

    OutputStreamWriter out =
        new OutputStreamWriter(webResponse.getOutputStream(), getRequest().getCharset());
    JSONWriter json = new JSONWriter(out);

    try {
      json.object();
      json.key("results").array();
      for (T item : response) {
        json.object();
        provider.toJson(item, json);
        json.endObject();
      }
      json.endArray();
      json.key("more").value(response.getHasMore()).endObject();
    } catch (JSONException e) {
      throw new RuntimeException("Could not write Json response", e);
    }

    try {
      out.flush();
    } catch (IOException e) {
      throw new RuntimeException("Could not write Json to servlet response", e);
    }
  }
  /**
   * * Invokes one of the resource methods annotated with {@link MethodMapping}.
   *
   * @param mappedMethod mapping info of the method.
   * @param attributes Attributes object for the current request.
   * @return the value returned by the invoked method
   */
  private Object invokeMappedMethod(MethodMappingInfo mappedMethod, Attributes attributes) {

    Method method = mappedMethod.getMethod();
    List parametersValues = new ArrayList();

    // Attributes objects
    PageParameters pageParameters = attributes.getParameters();
    WebResponse response = (WebResponse) attributes.getResponse();
    HttpMethod httpMethod = HttpUtils.getHttpMethod((WebRequest) RequestCycle.get().getRequest());

    LinkedHashMap<String, String> pathParameters =
        mappedMethod.populatePathParameters(pageParameters);
    Iterator<String> pathParamsIterator = pathParameters.values().iterator();
    Class<?>[] parameterTypes = method.getParameterTypes();

    for (int i = 0; i < parameterTypes.length; i++) {
      Object paramValue = null;
      MethodParameter methodParameter = new MethodParameter(parameterTypes[i], mappedMethod, i);
      Annotation annotation = ReflectionUtils.getAnnotationParam(i, method);
      // retrieve parameter value
      if (annotation != null)
        paramValue =
            extractParameterValue(methodParameter, pathParameters, annotation, pageParameters);
      else paramValue = extractParameterFromUrl(methodParameter, pathParamsIterator);
      // try to use the default value
      if (paramValue == null && !methodParameter.getDeaultValue().isEmpty())
        paramValue =
            toObject(methodParameter.getParameterClass(), methodParameter.getDeaultValue());

      if (paramValue == null && methodParameter.isRequired()) {
        response.sendError(
            400,
            "No suitable method found for URL '"
                + extractUrlFromRequest()
                + "' and HTTP method "
                + httpMethod);
        return null;
      }

      parametersValues.add(paramValue);
    }

    try {
      return method.invoke(this, parametersValues.toArray());
    } catch (Exception e) {
      response.sendError(500, "General server error.");
      throw new RuntimeException("Error invoking method '" + method.getName() + "'", e);
    }
  }
 /**
  * Method invoked to serialize the result of the invoked method and write this value to the
  * response.
  *
  * @param response The current response object.
  * @param result The object to write to response.
  * @param restMimeFormats
  */
 private void serializeObjectToResponse(WebResponse response, Object result, String mimeType) {
   try {
     response.setContentType(mimeType);
     objSerialDeserial.objectToResponse(result, response, mimeType);
   } catch (Exception e) {
     throw new RuntimeException("Error writing object to response.", e);
   }
 }
Esempio n. 4
0
    @Override
    public void respond(IRequestCycle requestCycle) {
      String location = url.toString();

      if (location.startsWith("/")) {
        // context-absolute url
        location = requestCycle.getUrlRenderer().renderContextRelativeUrl(location);
      }

      if (config.isPreferStateful()) {
        // we need to persist the session before a redirect to https so the session lasts
        // across both http and https calls.
        Session.get().bind();
      }

      WebResponse response = (WebResponse) requestCycle.getResponse();
      response.sendRedirect(location);
    }
  /**
   * Utility method to convert string values to the corresponding objects.
   *
   * @param clazz the type of the object we want to obtain.
   * @param value the string value we want to convert.
   * @return the object corresponding to the converted string value, or null if value parameter is
   *     null
   */
  public static Object toObject(Class clazz, String value) throws IllegalArgumentException {
    if (value == null) return null;
    // we use the standard Wicket conversion mechanism to obtain the
    // converted value.
    try {
      IConverter converter = Application.get().getConverterLocator().getConverter(clazz);

      return converter.convertToObject(value, Session.get().getLocale());
    } catch (Exception e) {
      WebResponse response = (WebResponse) RequestCycle.get().getResponse();

      response.setStatus(400);
      response.write(
          "Could not find a suitable constructor for value '"
              + value
              + "' of type '"
              + clazz
              + "'");

      return null;
    }
  }
  /**
   * * Handles a REST request invoking one of the methods annotated with {@link MethodMapping}. If
   * the annotated method returns a value, this latter is automatically serialized to a given string
   * format (like JSON, XML, etc...) and written to the web response.<br>
   * If no method is found to serve the current request, a 400 HTTP code is returned to the client.
   * Similarly, a 401 HTTP code is return if the user doesn't own one of the roles required to
   * execute an annotated method (See {@link AuthorizeInvocation}).
   */
  @Override
  public final void respond(Attributes attributes) {
    PageParameters pageParameters = attributes.getParameters();
    WebResponse response = (WebResponse) attributes.getResponse();
    HttpMethod httpMethod = HttpUtils.getHttpMethod((WebRequest) RequestCycle.get().getRequest());
    int indexedParamCount = pageParameters.getIndexedCount();

    // mapped method are stored concatenating the number of the segments of
    // their URL and their HTTP method (see annotation MethodMapping)
    List<MethodMappingInfo> mappedMethodsCandidates =
        mappedMethods.get(indexedParamCount + "_" + httpMethod.getMethod());

    MethodMappingInfo mappedMethod =
        selectMostSuitedMethod(mappedMethodsCandidates, pageParameters);

    if (mappedMethod != null) {
      if (!hasAny(mappedMethod.getRoles())) {
        response.sendError(401, "User is not allowed to invoke method on server.");
        return;
      }

      onBeforeMethodInvoked(mappedMethod, attributes);
      Object result = invokeMappedMethod(mappedMethod, attributes);
      onAfterMethodInvoked(mappedMethod, attributes, result);

      // if the invoked method returns a value, it is written to response
      if (result != null) {
        serializeObjectToResponse(response, result, mappedMethod.getMimeOutputFormat());
      }
    } else {
      response.sendError(
          400,
          "No suitable method found for URL '"
              + extractUrlFromRequest()
              + "' and HTTP method "
              + httpMethod);
    }
  }
Esempio n. 7
0
  /**
   * @see
   *     org.apache.wicket.core.request.handler.IPageRequestHandler#respond(org.apache.wicket.request.IRequestCycle)
   */
  @Override
  public final void respond(final IRequestCycle requestCycle) {
    final RequestCycle rc = (RequestCycle) requestCycle;
    final WebResponse response = (WebResponse) requestCycle.getResponse();

    if (shouldRedirectToPage(requestCycle)) {
      // the page itself has been added to the request target, we simply issue a redirect
      // back to the page
      IRequestHandler handler = new RenderPageRequestHandler(new PageProvider(page));
      final String url = rc.urlFor(handler).toString();
      response.sendRedirect(url);
      return;
    }

    respondersFrozen = true;

    for (ITargetRespondListener listener : respondListeners) {
      listener.onTargetRespond(this);
    }

    final Application app = page.getApplication();

    page.send(app, Broadcast.BREADTH, this);

    // Determine encoding
    final String encoding = app.getRequestCycleSettings().getResponseRequestEncoding();

    // Set content type based on markup type for page
    update.setContentType(response, encoding);

    // Make sure it is not cached by a client
    response.disableCaching();

    final StringResponse bodyResponse = new StringResponse();
    update.writeTo(bodyResponse, encoding);
    CharSequence filteredResponse = invokeResponseFilters(bodyResponse);
    response.write(filteredResponse);
  }
Esempio n. 8
0
  public String getWorkspace() {
    String workspace = getWorkspaceFromUrl();

    if (workspace != null) {
      return workspace;
    }

    RequestCycle rc = RequestCycle.get();
    workspace = rc.getMetaData(WORKSPACE_METADATA);
    if (workspace == null) {
      WebRequest req = (WebRequest) RequestCycle.get().getRequest();
      WebResponse resp = (WebResponse) RequestCycle.get().getResponse();
      Cookie cookie = req.getCookie(COOKIE_NAME);
      workspace = getDefaultWorkspaceName();
      if (cookie != null) {
        if (cookie.getValue() != null) {
          workspace = cookie.getValue();
        }
      }
      if (!checkSession(workspace)) {
        workspace = getDefaultWorkspaceName();
      }
      if (workspace == null) {
        throw new IllegalStateException(
            "Could not resolve jcr workspace to use for this request " + req.getUrl());
      }
      Cookie c = new Cookie(COOKIE_NAME, workspace);
      c.setPath("/");
      if (workspace.toString().equals(getDefaultWorkspaceName()) == false) {
        resp.addCookie(c);
      } else if (cookie != null) {
        resp.clearCookie(cookie);
      }
      rc.setMetaData(WORKSPACE_METADATA, workspace);
    }
    return workspace;
  }
  @Override
  public void objectToResponse(Object targetObject, WebResponse response, String mimeType)
      throws WicketRuntimeException {
    setCharsetResponse(response);

    String strOutput;

    if (RestMimeTypes.TEXT_PLAIN.equals(mimeType)) {
      strOutput = targetObject == null ? "" : targetObject.toString();
    } else {
      strOutput = objectSerialDeserial.serializeObject(targetObject, mimeType);
    }

    response.write(strOutput);
  }
Esempio n. 10
0
  /**
   * This is Wicket's main method to execute a request
   *
   * @param request
   * @param response
   * @param chain
   * @return false, if the request could not be processed
   * @throws IOException
   * @throws ServletException
   */
  boolean processRequest(
      ServletRequest request, final ServletResponse response, final FilterChain chain)
      throws IOException, ServletException {
    final ThreadContext previousThreadContext = ThreadContext.detach();

    // Assume we are able to handle the request
    boolean res = true;

    final ClassLoader previousClassLoader = Thread.currentThread().getContextClassLoader();
    final ClassLoader newClassLoader = getClassLoader();

    try {
      if (previousClassLoader != newClassLoader) {
        Thread.currentThread().setContextClassLoader(newClassLoader);
      }

      HttpServletRequest httpServletRequest = (HttpServletRequest) request;
      HttpServletResponse httpServletResponse = (HttpServletResponse) response;

      // Make sure getFilterPath() gets called before checkIfRedirectRequired()
      String filterPath = getFilterPath(httpServletRequest);

      if (filterPath == null) {
        throw new IllegalStateException("filter path was not configured");
      }

      if (shouldIgnorePath(httpServletRequest)) {
        log.debug("Ignoring request {}", httpServletRequest.getRequestURL());
        if (chain != null) {
          chain.doFilter(request, response);
        }
        return false;
      }

      String redirectURL = checkIfRedirectRequired(httpServletRequest);
      if (redirectURL == null) {
        // No redirect; process the request
        ThreadContext.setApplication(application);

        WebRequest webRequest = application.createWebRequest(httpServletRequest, filterPath);
        WebResponse webResponse = application.createWebResponse(webRequest, httpServletResponse);

        RequestCycle requestCycle = application.createRequestCycle(webRequest, webResponse);
        if (!requestCycle.processRequestAndDetach()) {
          if (chain != null) {
            chain.doFilter(request, response);
          }
          res = false;
        } else {
          webResponse.flush();
        }
      } else {
        if (Strings.isEmpty(httpServletRequest.getQueryString()) == false) {
          redirectURL += "?" + httpServletRequest.getQueryString();
        }

        try {
          // send redirect - this will discard POST parameters if the request is POST
          // - still better than getting an error because of lacking trailing slash
          httpServletResponse.sendRedirect(httpServletResponse.encodeRedirectURL(redirectURL));
        } catch (IOException e) {
          throw new RuntimeException(e);
        }
      }
    } finally {
      ThreadContext.restore(previousThreadContext);

      if (newClassLoader != previousClassLoader) {
        Thread.currentThread().setContextClassLoader(previousClassLoader);
      }

      if (response.isCommitted()) {
        response.flushBuffer();
      }
    }
    return res;
  }
 @Override
 protected void setHeaders(final WebResponse response) {
   response.setStatus(HttpServletResponse.SC_NOT_FOUND);
 }
 /**
  * Sets the charset for the current response.
  *
  * @param response the current response
  */
 private void setCharsetResponse(WebResponse response) {
   if (response.getContainerResponse() instanceof ServletResponse) {
     ServletResponse sResponse = (ServletResponse) response.getContainerResponse();
     sResponse.setCharacterEncoding(charset);
   }
 }
Esempio n. 13
0
 @Override
 protected void setHeaders(WebResponse response) {
   super.setHeaders(response);
   // Protection against ClickJacking, prevents the page from being rendered in an iframe element
   response.setHeader("X-Frame-Options", "deny");
 }
Esempio n. 14
0
 @Override
 protected void configureResponse(WebResponse response) {
   super.configureResponse(response);
   response.setStatus(HttpServletResponse.SC_FORBIDDEN);
 }
Esempio n. 15
0
 @Override
 public void setContentType(WebResponse response, String encoding) {
   response.setContentType("text/xml; charset=" + encoding);
 }
Esempio n. 16
0
 @Override
 protected void setHeaders(WebResponse response) {
   response.disableCaching();
   super.setHeaders(response);
 }