Example #1
0
  /*
   * Creates the URL based on the configured host, port, and services context root path.
   */
  private UriBuilder generateEndpointUrl(String path, UriBuilder uriBuilder)
      throws UnknownHostException {
    UriBuilder builder = uriBuilder;
    if (host != null && port != null && servicesContextRoot != null) {
      builder = builder.host(host);

      try {
        int portInt = Integer.parseInt(port);
        builder = builder.port(portInt);
      } catch (NumberFormatException nfe) {
        LOGGER.debug(
            "Cannot convert the current DDF port: {} to an integer."
                + " Defaulting to port in invocation.",
            port);
        throw new UnknownHostException("Unable to determine port DDF is using.");
      }

      builder = builder.replacePath(path);
    } else {
      LOGGER.debug("DDF Port is null, unable to determine host DDF is running on.");
      throw new UnknownHostException("Unable to determine port DDF is using.");
    }

    return builder;
  }
Example #2
0
  /**
   * Get the URL for an asset on this server
   *
   * @return the asset URL
   */
  protected static URL getAssetURL(UriBuilder builder, String moduleName, String assetPath)
      throws MalformedURLException {
    // Should we fetch the context prefix from a property? XXX -jslott
    String assetPrefix = "webdav/content/modules/installed/";
    builder.replacePath(assetPrefix + moduleName + "/" + assetPath);

    return builder.build().toURL();
  }
Example #3
0
 private com.sun.jersey.api.client.WebResource makeResource(String path) {
   com.sun.jersey.api.client.WebResource resource = resource();
   UriBuilder b = resource.getUriBuilder();
   if (path.startsWith("/")) {
     b.replacePath(path);
   } else {
     b.path(path);
   }
   URI uri = b.build();
   return resource.uri(uri);
 }
Example #4
0
 private void _test(ClientRequest request, UriBuilder uriBuilder, String path) {
   request.clear();
   uriBuilder.replacePath(generateURL(path));
   try {
     ClientResponse<String> response = request.get(String.class);
     Assert.assertEquals(HttpResponseCodes.SC_OK, response.getStatus());
     MultivaluedMap<String, String> headers = response.getHeaders();
     for (Object key : headers.keySet()) {
       System.out.println(key + ": " + headers.get(key));
     }
     response.releaseConnection();
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
Example #5
0
  private Kml createRootNetworkLink(UriInfo uriInfo) throws UnknownHostException {
    Kml kml = KmlFactory.createKml();
    NetworkLink rootNetworkLink = kml.createAndSetNetworkLink();

    rootNetworkLink.setName(this.productName);
    rootNetworkLink.setSnippet(KmlFactory.createSnippet().withMaxLines(0));
    UriBuilder baseUrlBuidler = UriBuilder.fromUri(uriInfo.getBaseUri());
    baseUrlBuidler.replacePath("");
    this.baseUrl = baseUrlBuidler.build().toString();
    String descriptionHtml = description;
    Handlebars handlebars = new Handlebars(templateLoader);
    try {
      Template template = handlebars.compile("description");
      descriptionHtml = template.apply(this);
      LOGGER.debug(descriptionHtml);
    } catch (IOException e) {
      LOGGER.error("Failed to apply description Template", e);
    }
    rootNetworkLink.setDescription(descriptionHtml);
    rootNetworkLink.setOpen(true);
    rootNetworkLink.setVisibility(false);
    Link link = rootNetworkLink.createAndSetLink();
    UriBuilder builder = UriBuilder.fromUri(uriInfo.getBaseUri());
    builder =
        generateEndpointUrl(
            servicesContextRoot
                + FORWARD_SLASH
                + CATALOG_URL_PATH
                + FORWARD_SLASH
                + KML_TRANSFORM_PARAM
                + FORWARD_SLASH
                + "sources",
            builder);
    link.setHref(builder.build().toString());
    link.setViewRefreshMode(ViewRefreshMode.NEVER);
    link.setRefreshMode(RefreshMode.ON_INTERVAL);
    link.setRefreshInterval(REFRESH_INTERVAL);

    return kml;
  }
Example #6
0
  private void doFilter(
      HttpServletRequest request,
      HttpServletResponse response,
      FilterChain chain,
      String requestURI,
      String servletPath,
      String queryString)
      throws IOException, ServletException {
    // if we match the static content regular expression lets delegate to
    // the filter chain to use the default container servlets & handlers
    final Pattern p = getStaticContentPattern();
    if (p != null && p.matcher(servletPath).matches()) {
      chain.doFilter(request, response);
      return;
    }

    if (filterContextPath != null) {
      if (!servletPath.startsWith(filterContextPath)) {
        throw new ContainerException(
            LocalizationMessages.SERVLET_PATH_MISMATCH(servletPath, filterContextPath));
        // TODO:
        //            } else if (servletPath.length() == filterContextPath.length()) {
        //                // Path does not end in a slash, may need to redirect
        //                if
        // (webComponent.getResourceConfig().getFeature(ResourceConfig.FEATURE_REDIRECT)) {
        //                    URI l = UriBuilder.fromUri(request.getRequestURL().toString()).
        //                            path("/").
        //                            replaceQuery(queryString).build();
        //
        //                    response.setStatus(307);
        //                    response.setHeader("Location", l.toASCIIString());
        //                    return;
        //                } else {
        //                    requestURI += "/";
        //                }
      }
    }

    final UriBuilder absoluteUriBuilder = UriBuilder.fromUri(request.getRequestURL().toString());

    final URI baseUri =
        (filterContextPath == null)
            ? absoluteUriBuilder.replacePath(request.getContextPath()).path("/").build()
            : absoluteUriBuilder
                .replacePath(request.getContextPath())
                .path(filterContextPath)
                .path("/")
                .build();

    final URI requestUri =
        absoluteUriBuilder.replacePath(requestURI).replaceQuery(queryString).build();

    final int status = service(baseUri, requestUri, request, response).get();

    // If forwarding is configured and response is a 404 with no entity
    // body then call the next filter in the chain
    if (webComponent.forwardOn404 && status == 404 && !response.isCommitted()) {
      // lets clear the response to OK before we forward to the next in the chain
      // as OK is the default set by servlet containers before filters/servlets do any wor
      // so lets hide our footsteps and pretend we were never in the chain at all and let the
      // next filter or servlet return the 404 if they can't find anything to return
      //
      // We could add an optional flag to disable this step if anyone can ever find a case where
      // this causes a problem, though I suspect any problems will really be with downstream
      // servlets not correctly setting an error status if they cannot find something to return
      response.setStatus(HttpServletResponse.SC_OK);
      chain.doFilter(request, response);
    }
  }
Example #7
0
  /**
   * Receives standard HTTP requests from the public {@code service} method and dispatches them to
   * the {@code do}<i>XXX</i> methods defined in this class. This method is an HTTP-specific version
   * of the {@link javax.servlet.Servlet#service} method. There's no need to override this method.
   *
   * @param request the {@link HttpServletRequest} object that contains the request the client made
   *     of the servlet
   * @param response the {@link HttpServletResponse} object that contains the response the servlet
   *     returns to the client
   * @throws IOException if an input or output error occurs while the servlet is handling the HTTP
   *     request
   * @throws ServletException if the HTTP request cannot be handled
   * @see javax.servlet.Servlet#service
   */
  @Override
  protected void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    /**
     * There is an annoying edge case where the service method is invoked for the case when the URI
     * is equal to the deployment URL minus the '/', for example
     * http://locahost:8080/HelloWorldWebApp
     */
    final String servletPath = request.getServletPath();
    String pathInfo = request.getPathInfo();
    StringBuffer requestURL = request.getRequestURL();
    String requestURI = request.getRequestURI();
    final boolean checkPathInfo = pathInfo == null || pathInfo.isEmpty() || pathInfo.equals("/");
    if (checkPathInfo && !request.getRequestURI().endsWith("/")) {
      // Only do this if the last segment of the servlet path does not contain '.'
      // This handles the case when the extension mapping is used with the servlet
      // see issue 506
      // This solution does not require parsing the deployment descriptor,
      // however still leaves it broken for the very rare case if a standard path
      // servlet mapping would include dot in the last segment (e.g. /.webresources/*)
      // and somebody would want to hit the root resource without the trailing slash
      int i = servletPath.lastIndexOf('/');
      if (servletPath.substring(i + 1).indexOf('.') < 0) {
        // TODO (+ handle request URL with invalid characters - see the creation of
        // absoluteUriBuilder bellow)
        //                if
        // (webComponent.getResourceConfig().getFeature(ResourceConfig.FEATURE_REDIRECT)) {
        //                    URI l = UriBuilder.fromUri(request.getRequestURL().toString()).
        //                            path("/").
        //                            replaceQuery(request.getQueryString()).build();
        //
        //                    response.setStatus(307);
        //                    response.setHeader("Location", l.toASCIIString());
        //                    return;
        //                } else {
        //                pathInfo = "/";
        //                requestURL.append("/");
        //                requestURI += "/";
        //                }
      }
    }

    /**
     * The HttpServletRequest.getRequestURL() contains the complete URI minus the query and fragment
     * components.
     */
    UriBuilder absoluteUriBuilder;
    try {
      absoluteUriBuilder = UriBuilder.fromUri(requestURL.toString());
    } catch (IllegalArgumentException iae) {
      final Response.Status badRequest = Response.Status.BAD_REQUEST;
      if (webComponent.configSetStatusOverSendError) {
        response.reset();
        response.setStatus(badRequest.getStatusCode(), badRequest.getReasonPhrase());
      } else {
        response.sendError(badRequest.getStatusCode(), badRequest.getReasonPhrase());
      }
      return;
    }

    /**
     * The HttpServletRequest.getPathInfo() and HttpServletRequest.getServletPath() are in decoded
     * form.
     *
     * <p>On some servlet implementations the getPathInfo() removed contiguous '/' characters. This
     * is problematic if URIs are embedded, for example as the last path segment. We need to work
     * around this and not use getPathInfo for the decodedPath.
     */
    final String decodedBasePath = request.getContextPath() + servletPath + "/";

    final String encodedBasePath = UriComponent.encode(decodedBasePath, UriComponent.Type.PATH);

    if (!decodedBasePath.equals(encodedBasePath)) {
      throw new ProcessingException(
          "The servlet context path and/or the "
              + "servlet path contain characters that are percent encoded");
    }

    final URI baseUri;
    final URI requestUri;
    try {
      baseUri = absoluteUriBuilder.replacePath(encodedBasePath).build();

      String queryParameters = request.getQueryString();
      if (queryParameters == null) {
        queryParameters = "";
      }

      requestUri = absoluteUriBuilder.replacePath(requestURI).replaceQuery(queryParameters).build();
    } catch (UriBuilderException ex) {
      final Response.Status badRequest = Response.Status.BAD_REQUEST;
      if (webComponent.configSetStatusOverSendError) {
        response.reset();
        response.setStatus(badRequest.getStatusCode(), badRequest.getReasonPhrase());
      } else {
        response.sendError(badRequest.getStatusCode(), badRequest.getReasonPhrase());
      }
      return;
    }

    service(baseUri, requestUri, request, response);
  }