Esempio n. 1
0
  /**
   * Handles a call by first verifying the optional request conditions and continue the processing
   * if possible. Note that in order to evaluate those conditions, {@link #getInfo()} or {@link
   * #getInfo(Variant)} methods might be invoked.
   *
   * @return The response entity.
   * @throws ResourceException
   */
  protected Representation doConditionalHandle() throws ResourceException {
    Representation result = null;

    if (getConditions().hasSome()) {
      RepresentationInfo resultInfo = null;

      if (existing) {
        if (isNegotiated()) {
          resultInfo = doGetInfo(getPreferredVariant(getVariants(Method.GET)));
        } else {
          resultInfo = doGetInfo();
        }

        if (resultInfo == null) {
          if ((getStatus() == null)
              || (getStatus().isSuccess() && !Status.SUCCESS_NO_CONTENT.equals(getStatus()))) {
            setStatus(Status.CLIENT_ERROR_NOT_FOUND);
          } else {
            // Keep the current status as the developer might prefer
            // a special status like 'method not authorized'.
          }
        } else {
          Status status = getConditions().getStatus(getMethod(), resultInfo);

          if (status != null) {
            setStatus(status);
          }
        }
      } else {
        Status status = getConditions().getStatus(getMethod(), resultInfo);

        if (status != null) {
          setStatus(status);
        }
      }

      if ((Method.GET.equals(getMethod()) || Method.HEAD.equals(getMethod()))
          && resultInfo instanceof Representation) {
        result = (Representation) resultInfo;
      } else if ((getStatus() != null) && getStatus().isSuccess()) {
        // Conditions were passed successfully, continue the normal
        // processing.
        if (isNegotiated()) {
          // Reset the list of variants, as the method differs.
          getVariants().clear();
          result = doNegotiatedHandle();
        } else {
          result = doHandle();
        }
      }
    } else {
      if (isNegotiated()) {
        result = doNegotiatedHandle();
      } else {
        result = doHandle();
      }
    }

    return result;
  }
Esempio n. 2
0
  /**
   * Looks up a {@link LayerInfo} or {@link LayerGroupInfo} named after the {@code <layer>} in the
   * requested resource {@code <layer>.kml} name
   *
   * @see org.restlet.Finder#findTarget(org.restlet.data.Request, org.restlet.data.Response)
   */
  @Override
  public Resource findTarget(final Request request, Response response) {
    if (!Method.GET.equals(request.getMethod())) {
      response.setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
      return null;
    }
    final String name = RESTUtils.getAttribute(request, "layer");
    if (name == null) {
      throw new RestletException("No layer name specified", Status.CLIENT_ERROR_BAD_REQUEST);
    }
    final Catalog catalog = geoserver.getCatalog();
    CatalogInfo layer = catalog.getLayerByName(name);
    MetadataMap mdmap;
    if (layer == null) {
      layer = catalog.getLayerGroupByName(name);
      if (layer == null) {
        throw new RestletException("Layer " + name + " not found", Status.CLIENT_ERROR_NOT_FOUND);
      }
      mdmap = ((LayerGroupInfo) layer).getMetadata();
    } else {
      mdmap = ((LayerInfo) layer).getMetadata();
    }

    Boolean enabled = mdmap.get(Properties.INDEXING_ENABLED, Boolean.class);
    if (enabled == null || !enabled.booleanValue()) {
      throw new RestletException("Layer " + name + " not found", Status.CLIENT_ERROR_NOT_FOUND);
    }
    final Context context = getContext();
    return new GeoSearchLayer(context, request, response, layer, geoserver);
  }
Esempio n. 3
0
  /**
   * Handles a call for a local entity. By default, only GET and HEAD methods are implemented.
   *
   * @param request The request to handle.
   * @param response The response to update.
   * @param decodedPath The URL decoded entity path.
   */
  @Override
  protected void handleLocal(Request request, Response response, String decodedPath) {
    int spi = decodedPath.indexOf("!/");
    String fileUri;
    String entryName;
    if (spi != -1) {
      fileUri = decodedPath.substring(0, spi);
      entryName = decodedPath.substring(spi + 2);
    } else {
      fileUri = decodedPath;
      entryName = "";
    }

    LocalReference fileRef = new LocalReference(fileUri);
    if (Protocol.FILE.equals(fileRef.getSchemeProtocol())) {
      final File file = fileRef.getFile();
      if (Method.GET.equals(request.getMethod()) || Method.HEAD.equals(request.getMethod())) {
        handleGet(request, response, file, entryName, getMetadataService());
      } else if (Method.PUT.equals(request.getMethod())) {
        handlePut(request, response, file, entryName);
      } else {
        response.setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
        response.getAllowedMethods().add(Method.GET);
        response.getAllowedMethods().add(Method.HEAD);
        response.getAllowedMethods().add(Method.PUT);
      }
    } else {
      response.setStatus(Status.SERVER_ERROR_NOT_IMPLEMENTED, "Only works on local files.");
    }
  }
  @Override
  public void handle(Request request, Response response) {
    super.handle(request, response);

    if (Method.GET.equals(request.getMethod())) {
      response.setEntity(getSwagger());
    } else {
      response.setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
    }
  }
Esempio n. 5
0
  public Response sendRequest(Method method, String url, Representation representation) {
    this.logger.debug("Method: " + method.getName() + " url: " + url);

    Request request = new Request();
    request.setResourceRef(url);
    request.setMethod(method);

    if (!Method.GET.equals(method) && !Method.DELETE.equals(method)) {
      request.setEntity(representation);
    }

    request.setChallengeResponse(this.challenge);

    return this.restClient.handle(request);
  }
Esempio n. 6
0
  /**
   * Handles any call to this resource. The default implementation check the {@link
   * #isConditional()} and {@link #isNegotiated()} method to determine which one of the {@link
   * #doConditionalHandle()}, {@link #doNegotiatedHandle()} and {@link #doHandle()} methods should
   * be invoked. It also catches any {@link ResourceException} thrown and updates the response
   * status using the {@link #setStatus(Status, Throwable, String)} method.<br>
   * <br>
   * After handling, if the status is set to {@link Status#CLIENT_ERROR_METHOD_NOT_ALLOWED}, then
   * {@link #updateAllowedMethods()} is invoked to give the resource a chance to inform the client
   * about the allowed methods.
   *
   * @return The response entity.
   */
  @Override
  public Representation handle() {
    Representation result = null;

    // If the resource is not available after initialization and if this a
    // retrieval method, then return a "not found" response.
    if (!isExisting() && getMethod().isSafe()) {
      setStatus(Status.CLIENT_ERROR_NOT_FOUND);
    } else {
      try {
        if (isConditional()) {
          result = doConditionalHandle();
        } else if (isNegotiated()) {
          result = doNegotiatedHandle();
        } else {
          result = doHandle();
        }

        if (!getResponse().isEntityAvailable()) {
          // If the user manually set the entity, keep it
          getResponse().setEntity(result);
        }

        if (Status.CLIENT_ERROR_METHOD_NOT_ALLOWED.equals(getStatus())) {
          updateAllowedMethods();
        } else if (Method.GET.equals(getMethod())
            && Status.SUCCESS_OK.equals(getStatus())
            && (getResponseEntity() == null || !getResponseEntity().isAvailable())) {
          getLogger()
              .fine(
                  "A response with a 200 (Ok) status should have an entity. Changing the status to 204 (No content).");
          setStatus(Status.SUCCESS_NO_CONTENT);
        }
      } catch (Throwable t) {
        doCatch(t);
      }
    }

    return result;
  }
Esempio n. 7
0
 @Override
 public boolean supports(final Method method) {
   return Method.POST.equals(method) || Method.GET.equals(method) || super.supports(method);
 }
Esempio n. 8
0
  /**
   * Constructor.
   *
   * @param helper The parent HTTP client helper.
   * @param method The method name.
   * @param requestUri The request URI.
   * @param hasEntity Indicates if the call will have an entity to send to the server.
   * @throws IOException
   */
  public HttpMethodCall(
      HttpClientHelper helper, final String method, String requestUri, boolean hasEntity)
      throws IOException {
    super(helper, method, requestUri);
    this.clientHelper = helper;

    if (requestUri.startsWith("http")) {
      if (method.equalsIgnoreCase(Method.GET.getName())) {
        this.httpMethod = new GetMethod(requestUri);
      } else if (method.equalsIgnoreCase(Method.POST.getName())) {
        this.httpMethod = new PostMethod(requestUri);
      } else if (method.equalsIgnoreCase(Method.PUT.getName())) {
        this.httpMethod = new PutMethod(requestUri);
      } else if (method.equalsIgnoreCase(Method.HEAD.getName())) {
        this.httpMethod = new HeadMethod(requestUri);
      } else if (method.equalsIgnoreCase(Method.DELETE.getName())) {
        this.httpMethod = new DeleteMethod(requestUri);
      } else if (method.equalsIgnoreCase(Method.CONNECT.getName())) {
        final HostConfiguration host = new HostConfiguration();
        host.setHost(new URI(requestUri, false));
        this.httpMethod = new ConnectMethod(host);
      } else if (method.equalsIgnoreCase(Method.OPTIONS.getName())) {
        this.httpMethod = new OptionsMethod(requestUri);
      } else if (method.equalsIgnoreCase(Method.TRACE.getName())) {
        this.httpMethod = new TraceMethod(requestUri);
      } else {
        this.httpMethod =
            new EntityEnclosingMethod(requestUri) {
              @Override
              public String getName() {
                return method;
              }
            };
      }

      this.httpMethod.setFollowRedirects(this.clientHelper.isFollowRedirects());
      this.httpMethod.setDoAuthentication(false);

      if (this.clientHelper.getRetryHandler() != null) {
        try {
          this.httpMethod
              .getParams()
              .setParameter(
                  HttpMethodParams.RETRY_HANDLER,
                  Engine.loadClass(this.clientHelper.getRetryHandler()).newInstance());
        } catch (Exception e) {
          this.clientHelper
              .getLogger()
              .log(
                  Level.WARNING,
                  "An error occurred during the instantiation of the retry handler.",
                  e);
        }
      }

      this.responseHeadersAdded = false;
      setConfidential(
          this.httpMethod.getURI().getScheme().equalsIgnoreCase(Protocol.HTTPS.getSchemeName()));
    } else {
      throw new IllegalArgumentException("Only HTTP or HTTPS resource URIs are allowed here");
    }
  }
  private Representation handle(ParameterList request) {
    Logger log = getLogger();
    log.info("Handle on OP");
    ConcurrentMap<String, Object> attribs = getContext().getAttributes();
    ServerManager manager = (ServerManager) attribs.get("openid_manager");
    log.info("OP endpoint = " + manager.getOPEndpointUrl());

    String mode =
        request.hasParameter("openid.mode") ? request.getParameterValue("openid.mode") : null;

    Message response;
    String responseText;

    if ("associate".equals(mode)) {
      // --- process an association request ---
      response = manager.associationResponse(request);
      responseText = response.keyValueFormEncoding();
    } else if ("checkid_setup".equals(mode) || "checkid_immediate".equals(mode)) {
      // interact with the user and obtain data needed to continue
      List<?> userData = userInteraction(request, manager.getOPEndpointUrl());

      String userSelectedId = (String) userData.get(0);
      String userSelectedClaimedId = (String) userData.get(1);
      Boolean authenticatedAndApproved = (Boolean) userData.get(2);

      // --- process an authentication request ---
      response =
          manager.authResponse(
              request,
              userSelectedId,
              userSelectedClaimedId,
              authenticatedAndApproved.booleanValue());

      if (response instanceof DirectError) {
        Form f = new Form();
        @SuppressWarnings("unchecked")
        Map<String, String> m = (Map<String, String>) response.getParameterMap();
        for (String key : m.keySet()) {
          f.add(key, m.get(key));
        }
        return f.getWebRepresentation();
      } else {
        // caller will need to decide which of the following to use:

        // option1: GET HTTP-redirect to the return_to URL
        // return new
        // StringRepresentation(response.getDestinationUrl(true));
        redirectSeeOther(response.getDestinationUrl(true));
        return new EmptyRepresentation();

        // option2: HTML FORM Redirection
        // RequestDispatcher dispatcher =
        // getServletContext().getRequestDispatcher("formredirection.jsp");
        // httpReq.setAttribute("prameterMap",
        // response.getParameterMap());
        // httpReq.setAttribute("destinationUrl",
        // response.getDestinationUrl(false));
        // dispatcher.forward(request, response);
        // return null;
      }
    } else if ("check_authentication".equals(mode)) {
      // --- processing a verification request ---
      response = manager.verify(request);
      log.info("OpenID : " + response.keyValueFormEncoding());
      responseText = response.keyValueFormEncoding();
    } else if (Method.GET.equals(getMethod())) {
      // Could be a discovery request
      sendXRDSLocation();
      return new StringRepresentation("XRDS Discovery Information");
    } else {
      // --- error response ---
      response = DirectError.createDirectError("Unknown request");
      responseText = response.keyValueFormEncoding();
    }

    // return the result to the user
    return new StringRepresentation(responseText);
  }