コード例 #1
0
ファイル: URI.java プロジェクト: sourcewarehouse/JCGO
 /**
  * Compares the URI with the given object for equality. If the object is not a <code>URI</code>,
  * then the method returns false. Otherwise, the following criteria are observed:
  *
  * <ul>
  *   <li>The scheme of the URIs must either be null (undefined) in both cases, or equal, ignorant
  *       of case.
  *   <li>The raw fragment of the URIs must either be null (undefined) in both cases, or equal,
  *       ignorant of case.
  *   <li>Both URIs must be of the same type (opaque or hierarchial)
  *   <li><strong>For opaque URIs:</strong>
  *       <ul>
  *         <li>The raw scheme-specific parts must be equal.
  *       </ul>
  *   <li>For hierarchical URIs:
  *       <ul>
  *         <li>The raw paths must be equal, ignorant of case.
  *         <li>The raw queries are either both undefined or both equal, ignorant of case.
  *         <li>The raw authority sections are either both undefined or:
  *         <li><strong>For registry-based authorities:</strong>
  *             <ul>
  *               <li>they are equal.
  *             </ul>
  *         <li><strong>For server-based authorities:</strong>
  *             <ul>
  *               <li>the hosts are equal, ignoring case
  *               <li>the ports are equal
  *               <li>the user information components are equal
  *             </ul>
  *       </ul>
  * </ul>
  *
  * @param obj the obj to compare the URI with.
  * @return <code>true</code> if the objects are equal, according to the specification above.
  */
 public boolean equals(Object obj) {
   if (!(obj instanceof URI)) return false;
   URI uriObj = (URI) obj;
   if (scheme == null) {
     if (uriObj.getScheme() != null) return false;
   } else if (!(scheme.equalsIgnoreCase(uriObj.getScheme()))) return false;
   if (rawFragment == null) {
     if (uriObj.getRawFragment() != null) return false;
   } else if (!(rawFragment.equalsIgnoreCase(uriObj.getRawFragment()))) return false;
   boolean opaqueThis = isOpaque();
   boolean opaqueObj = uriObj.isOpaque();
   if (opaqueThis && opaqueObj)
     return rawSchemeSpecificPart.equals(uriObj.getRawSchemeSpecificPart());
   else if (!opaqueThis && !opaqueObj) {
     boolean common =
         rawPath.equalsIgnoreCase(uriObj.getRawPath())
             && ((rawQuery == null && uriObj.getRawQuery() == null)
                 || rawQuery.equalsIgnoreCase(uriObj.getRawQuery()));
     if (rawAuthority == null && uriObj.getRawAuthority() == null) return common;
     if (host == null) return common && rawAuthority.equalsIgnoreCase(uriObj.getRawAuthority());
     return common
         && host.equalsIgnoreCase(uriObj.getHost())
         && port == uriObj.getPort()
         && (rawUserInfo == null
             ? uriObj.getRawUserInfo() == null
             : rawUserInfo.equalsIgnoreCase(uriObj.getRawUserInfo()));
   } else return false;
 }
コード例 #2
0
  @Override
  public UriBuilder uri(URI uri) {
    if (uri == null) {
      throw new IllegalArgumentException("URI parameter is null");
    }

    if (uri.getRawFragment() != null) {
      fragment = uri.getRawFragment();
    }

    if (uri.isOpaque()) {
      scheme = uri.getScheme();
      ssp = uri.getRawSchemeSpecificPart();
      return this;
    }

    if (uri.getScheme() == null) {
      if (ssp != null) {
        if (uri.getRawSchemeSpecificPart() != null) {
          ssp = uri.getRawSchemeSpecificPart();
          return this;
        }
      }
    } else {
      scheme = uri.getScheme();
    }

    ssp = null;
    if (uri.getRawAuthority() != null) {
      if (uri.getRawUserInfo() == null && uri.getHost() == null && uri.getPort() == -1) {
        authority = uri.getRawAuthority();
        userInfo = null;
        host = null;
        port = -1;
      } else {
        authority = null;
        if (uri.getRawUserInfo() != null) {
          userInfo = uri.getRawUserInfo();
        }
        if (uri.getHost() != null) {
          host = uri.getHost();
        }
        if (uri.getPort() != -1) {
          port = uri.getPort();
        }
      }
    }

    if (uri.getRawPath() != null && uri.getRawPath().length() > 0) {
      path.setLength(0);
      path.append(uri.getRawPath());
    }
    if (uri.getRawQuery() != null && uri.getRawQuery().length() > 0) {
      query.setLength(0);
      query.append(uri.getRawQuery());
    }

    return this;
  }
コード例 #3
0
  /**
   * Validate the instance
   *
   * <p>Unlike all other validators:
   *
   * <ul>
   *   <li>this is the only one which will, if required, go over the net to grab new schemas;
   *   <li>this is the only one which can spawn a {@link ValidationContext} with a different root
   *       schema (if the ref represents an absolute {@link URI});
   *   <li>this is the only validator implementation which can spawn errors (ie, {@link
   *       ValidationReport#isError()} returns {@code true}) and not only failures.
   * </ul>
   *
   * @return the report from the spawned validator
   */
  @Override
  public ValidationReport validate(final ValidationContext context, final JsonNode instance)
      throws JsonValidationFailureException {
    final ValidationReport report = context.createReport();

    final String ref = context.getSchema().get(keyword).getTextValue();

    final URI uri, baseURI;
    final JsonPointer pointer;

    try {
      uri = new URI(ref);
      baseURI = new URI(uri.getScheme(), uri.getSchemeSpecificPart(), null);
      pointer = new JsonPointer(uri.getRawFragment());
    } catch (URISyntaxException e) {
      throw new RuntimeException(
          "PROBLEM: invalid URI found (" + ref + "), syntax validation should have caught that", e);
    }

    final ValidationContext ctx;
    try {
      ctx = context.fromURI(baseURI);
    } catch (IOException e) {
      report.error(
          String.format(
              "cannot download schema at ref %s: %s: " + "%s",
              ref, e.getClass().getName(), e.getMessage()));
      return report;
    } catch (IllegalArgumentException e) {
      report.error(String.format("cannot use ref %s: %s", ref, e.getMessage()));
      return report;
    }

    return ctx.getValidator(pointer, instance).validate(ctx, instance);
  }
コード例 #4
0
 /**
  * Update the query (encoded) of this MutableUri.
  *
  * @param rawQuery new query element (encoded)
  * @throws URISyntaxException if the new equivalent URI is invalid
  */
 public void setRawQuery(String rawQuery) throws URISyntaxException {
   uri =
       create(
           uri.getScheme(),
           uri.getRawUserInfo(),
           uri.getHost(),
           uri.getPort(),
           uri.getRawPath(),
           rawQuery,
           uri.getRawFragment());
 }
コード例 #5
0
 /** Convert a java.net.URI to a Uri. */
 public static Uri fromJavaUri(URI uri) {
   if (uri.isOpaque()) {
     throw new IllegalArgumentException("No support for opaque Uris " + uri.toString());
   }
   return new UriBuilder()
       .setScheme(uri.getScheme())
       .setAuthority(uri.getRawAuthority())
       .setPath(uri.getRawPath())
       .setQuery(uri.getRawQuery())
       .setFragment(uri.getRawFragment())
       .toUri();
 }
コード例 #6
0
 private String extractFullPath(String uriString) {
   URI uri = validateAndConvertToURI(uriString);
   StringBuilder pathBuilder = new StringBuilder(uri.getRawPath());
   String query = uri.getRawQuery();
   if (query != null) {
     pathBuilder.append('?');
     pathBuilder.append(query);
   }
   String fragment = uri.getRawFragment();
   if (fragment != null) {
     pathBuilder.append(fragment);
   }
   return pathBuilder.toString();
 }
コード例 #7
0
ファイル: RewriteClient.java プロジェクト: hxgong/rest.li
  private URI rewriteUri(URI uri) {
    assert _serviceName.equals(LoadBalancerUtil.getServiceNameFromUri(uri));

    String path = LoadBalancerUtil.getRawPathFromUri(uri);

    UriBuilder builder = UriBuilder.fromUri(_uri);
    if (path != null) {
      builder.path(path);
    }
    builder.replaceQuery(uri.getRawQuery());
    builder.fragment(uri.getRawFragment());
    URI rewrittenUri = builder.build();

    debug(_log, "rewrite uri ", uri, " -> ", rewrittenUri);

    return rewrittenUri;
  }
コード例 #8
0
ファイル: URI.java プロジェクト: sourcewarehouse/JCGO
 /**
  * Relativizes the given URI against this URI. The following algorithm is used:
  *
  * <ul>
  *   <li>If either URI is opaque, the given URI is returned.
  *   <li>If the schemes of the URIs differ, the given URI is returned.
  *   <li>If the authority components of the URIs differ, then the given URI is returned.
  *   <li>If the path of this URI is not a prefix of the supplied URI, then the given URI is
  *       returned.
  *   <li>If all the above conditions hold, a new URI is created using the query and fragment
  *       components of the given URI, along with a path computed by removing the path of this URI
  *       from the start of the path of the supplied URI.
  * </ul>
  *
  * @param uri the URI to relativize agsint this URI
  * @return the resulting URI
  * @throws NullPointerException if the uri is null
  */
 public URI relativize(URI uri) {
   if (isOpaque() || uri.isOpaque()) return uri;
   if (scheme == null && uri.getScheme() != null) return uri;
   if (scheme != null && !(scheme.equals(uri.getScheme()))) return uri;
   if (rawAuthority == null && uri.getRawAuthority() != null) return uri;
   if (rawAuthority != null && !(rawAuthority.equals(uri.getRawAuthority()))) return uri;
   if (!(uri.getRawPath().startsWith(rawPath))) return uri;
   try {
     return new URI(
         null,
         null,
         uri.getRawPath().substring(rawPath.length()),
         uri.getRawQuery(),
         uri.getRawFragment());
   } catch (URISyntaxException e) {
     throw (Error)
         new InternalError("Relativized URI variant could not " + "be constructed").initCause(e);
   }
 }
コード例 #9
0
ファイル: OpenID.java プロジェクト: eclettica/play1
 /** Normalize the given openid as a standard openid */
 public static String normalize(String openID) {
   openID = openID.trim();
   if (!openID.startsWith("http://") && !openID.startsWith("https://")) {
     openID = "http://" + openID;
   }
   try {
     URI url = new URI(openID);
     String frag = url.getRawFragment();
     if (frag != null && frag.length() > 0) {
       openID = openID.replace("#" + frag, "");
     }
     if (url.getPath().equals("")) {
       openID += "/";
     }
     openID = new URI(openID).toString();
   } catch (Exception e) {
     throw new RuntimeException(openID + " is not a valid URL");
   }
   return openID;
 }
コード例 #10
0
 private void setHeaders(MultivaluedMap<String, Object> headers) {
   this.headers = headers;
   Object location = headers.getFirst(HttpHeaders.LOCATION);
   if (location != null) {
     if (location instanceof URI) {
       final URI locationUri = (URI) location;
       if (!locationUri.isAbsolute()) {
         final URI base =
             (statusType.getStatusCode() == Status.CREATED.getStatusCode())
                 ? request.getAbsolutePath()
                 : request.getBaseUri();
         location =
             UriBuilder.fromUri(base)
                 .path(locationUri.getRawPath())
                 .replaceQuery(locationUri.getRawQuery())
                 .fragment(locationUri.getRawFragment())
                 .build();
       }
       headers.putSingle(HttpHeaders.LOCATION, location);
     }
   }
 }
コード例 #11
0
ファイル: HttpRequestFilter.java プロジェクト: jwalter/soapui
  @SuppressWarnings("deprecation")
  @Override
  public void filterHttpRequest(SubmitContext context, HttpRequestInterface<?> request) {
    HttpRequestBase httpMethod =
        (HttpRequestBase) context.getProperty(BaseHttpRequestTransport.HTTP_METHOD);

    String path = PropertyExpander.expandProperties(context, request.getPath());
    StringBuffer query = new StringBuffer();
    String encoding =
        System.getProperty("soapui.request.encoding", StringUtils.unquote(request.getEncoding()));

    StringToStringMap responseProperties =
        (StringToStringMap) context.getProperty(BaseHttpRequestTransport.RESPONSE_PROPERTIES);

    MimeMultipart formMp =
        "multipart/form-data".equals(request.getMediaType())
                && httpMethod instanceof HttpEntityEnclosingRequestBase
            ? new MimeMultipart()
            : null;

    RestParamsPropertyHolder params = request.getParams();

    for (int c = 0; c < params.getPropertyCount(); c++) {
      RestParamProperty param = params.getPropertyAt(c);

      String value = PropertyExpander.expandProperties(context, param.getValue());
      responseProperties.put(param.getName(), value);

      List<String> valueParts =
          sendEmptyParameters(request) || (!StringUtils.hasContent(value) && param.getRequired())
              ? RestUtils.splitMultipleParametersEmptyIncluded(
                  value, request.getMultiValueDelimiter())
              : RestUtils.splitMultipleParameters(value, request.getMultiValueDelimiter());

      // skip HEADER and TEMPLATE parameter encoding (TEMPLATE is encoded by
      // the URI handling further down)
      if (value != null
          && param.getStyle() != ParameterStyle.HEADER
          && param.getStyle() != ParameterStyle.TEMPLATE
          && !param.isDisableUrlEncoding()) {
        try {
          if (StringUtils.hasContent(encoding)) {
            value = URLEncoder.encode(value, encoding);
            for (int i = 0; i < valueParts.size(); i++)
              valueParts.set(i, URLEncoder.encode(valueParts.get(i), encoding));
          } else {
            value = URLEncoder.encode(value);
            for (int i = 0; i < valueParts.size(); i++)
              valueParts.set(i, URLEncoder.encode(valueParts.get(i)));
          }
        } catch (UnsupportedEncodingException e1) {
          SoapUI.logError(e1);
          value = URLEncoder.encode(value);
          for (int i = 0; i < valueParts.size(); i++)
            valueParts.set(i, URLEncoder.encode(valueParts.get(i)));
        }
        // URLEncoder replaces space with "+", but we want "%20".
        value = value.replaceAll("\\+", "%20");
        for (int i = 0; i < valueParts.size(); i++)
          valueParts.set(i, valueParts.get(i).replaceAll("\\+", "%20"));
      }

      if (param.getStyle() == ParameterStyle.QUERY && !sendEmptyParameters(request)) {
        if (!StringUtils.hasContent(value) && !param.getRequired()) continue;
      }

      switch (param.getStyle()) {
        case HEADER:
          for (String valuePart : valueParts) httpMethod.addHeader(param.getName(), valuePart);
          break;
        case QUERY:
          if (formMp == null || !request.isPostQueryString()) {
            for (String valuePart : valueParts) {
              if (query.length() > 0) query.append('&');

              query.append(URLEncoder.encode(param.getName()));
              query.append('=');
              if (StringUtils.hasContent(valuePart)) query.append(valuePart);
            }
          } else {
            try {
              addFormMultipart(
                  request, formMp, param.getName(), responseProperties.get(param.getName()));
            } catch (MessagingException e) {
              SoapUI.logError(e);
            }
          }

          break;
        case TEMPLATE:
          try {
            value =
                getEncodedValue(
                    value,
                    encoding,
                    param.isDisableUrlEncoding(),
                    request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
            path = path.replaceAll("\\{" + param.getName() + "\\}", value == null ? "" : value);
          } catch (UnsupportedEncodingException e) {
            SoapUI.logError(e);
          }
          break;
        case MATRIX:
          try {
            value =
                getEncodedValue(
                    value,
                    encoding,
                    param.isDisableUrlEncoding(),
                    request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
          } catch (UnsupportedEncodingException e) {
            SoapUI.logError(e);
          }

          if (param.getType().equals(XmlBoolean.type.getName())) {
            if (value.toUpperCase().equals("TRUE") || value.equals("1")) {
              path += ";" + param.getName();
            }
          } else {
            path += ";" + param.getName();
            if (StringUtils.hasContent(value)) {
              path += "=" + value;
            }
          }
          break;
        case PLAIN:
          break;
      }
    }

    if (request.getSettings().getBoolean(HttpSettings.FORWARD_SLASHES))
      path = PathUtils.fixForwardSlashesInPath(path);

    if (PathUtils.isHttpPath(path)) {
      try {
        // URI(String) automatically URLencodes the input, so we need to
        // decode it first...
        URI uri = new URI(path, request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
        context.setProperty(BaseHttpRequestTransport.REQUEST_URI, uri);
        java.net.URI oldUri = httpMethod.getURI();
        httpMethod.setURI(
            HttpUtils.createUri(
                oldUri.getScheme(),
                oldUri.getRawUserInfo(),
                oldUri.getHost(),
                oldUri.getPort(),
                oldUri.getRawPath(),
                uri.getEscapedQuery(),
                oldUri.getRawFragment()));
      } catch (Exception e) {
        SoapUI.logError(e);
      }
    } else if (StringUtils.hasContent(path)) {
      try {
        java.net.URI oldUri = httpMethod.getURI();
        String pathToSet =
            StringUtils.hasContent(oldUri.getRawPath()) && !"/".equals(oldUri.getRawPath())
                ? oldUri.getRawPath() + path
                : path;
        java.net.URI newUri =
            URIUtils.createURI(
                oldUri.getScheme(),
                oldUri.getHost(),
                oldUri.getPort(),
                pathToSet,
                oldUri.getQuery(),
                oldUri.getFragment());
        httpMethod.setURI(newUri);
        context.setProperty(
            BaseHttpRequestTransport.REQUEST_URI,
            new URI(
                newUri.toString(), request.getSettings().getBoolean(HttpSettings.ENCODED_URLS)));
      } catch (Exception e) {
        SoapUI.logError(e);
      }
    }

    if (query.length() > 0 && !request.isPostQueryString()) {
      try {
        java.net.URI oldUri = httpMethod.getURI();
        httpMethod.setURI(
            URIUtils.createURI(
                oldUri.getScheme(),
                oldUri.getHost(),
                oldUri.getPort(),
                oldUri.getRawPath(),
                query.toString(),
                oldUri.getFragment()));
      } catch (Exception e) {
        SoapUI.logError(e);
      }
    }

    if (request instanceof RestRequest) {
      String acceptEncoding = ((RestRequest) request).getAccept();
      if (StringUtils.hasContent(acceptEncoding)) {
        httpMethod.setHeader("Accept", acceptEncoding);
      }
    }

    if (formMp != null) {
      // create request message
      try {
        if (request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest) {
          String requestContent =
              PropertyExpander.expandProperties(
                  context, request.getRequestContent(), request.isEntitizeProperties());
          if (StringUtils.hasContent(requestContent)) {
            initRootPart(request, requestContent, formMp);
          }
        }

        for (Attachment attachment : request.getAttachments()) {
          MimeBodyPart part = new PreencodedMimeBodyPart("binary");

          if (attachment instanceof FileAttachment<?>) {
            String name = attachment.getName();
            if (StringUtils.hasContent(attachment.getContentID())
                && !name.equals(attachment.getContentID())) name = attachment.getContentID();

            part.setDisposition(
                "form-data; name=\"" + name + "\"; filename=\"" + attachment.getName() + "\"");
          } else part.setDisposition("form-data; name=\"" + attachment.getName() + "\"");

          part.setDataHandler(new DataHandler(new AttachmentDataSource(attachment)));

          formMp.addBodyPart(part);
        }

        MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION);
        message.setContent(formMp);
        message.saveChanges();
        RestRequestMimeMessageRequestEntity mimeMessageRequestEntity =
            new RestRequestMimeMessageRequestEntity(message, request);
        ((HttpEntityEnclosingRequest) httpMethod).setEntity(mimeMessageRequestEntity);
        httpMethod.setHeader("Content-Type", mimeMessageRequestEntity.getContentType().getValue());
        httpMethod.setHeader("MIME-Version", "1.0");
      } catch (Throwable e) {
        SoapUI.logError(e);
      }
    } else if (request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest) {
      if (StringUtils.hasContent(request.getMediaType()))
        httpMethod.setHeader(
            "Content-Type", getContentTypeHeader(request.getMediaType(), encoding));

      if (request.isPostQueryString()) {
        try {
          ((HttpEntityEnclosingRequest) httpMethod).setEntity(new StringEntity(query.toString()));
        } catch (UnsupportedEncodingException e) {
          SoapUI.logError(e);
        }
      } else {
        String requestContent =
            PropertyExpander.expandProperties(
                context, request.getRequestContent(), request.isEntitizeProperties());
        List<Attachment> attachments = new ArrayList<Attachment>();

        for (Attachment attachment : request.getAttachments()) {
          if (attachment.getContentType().equals(request.getMediaType())) {
            attachments.add(attachment);
          }
        }

        if (StringUtils.hasContent(requestContent) && attachments.isEmpty()) {
          try {
            byte[] content =
                encoding == null ? requestContent.getBytes() : requestContent.getBytes(encoding);
            ((HttpEntityEnclosingRequest) httpMethod).setEntity(new ByteArrayEntity(content));
          } catch (UnsupportedEncodingException e) {
            ((HttpEntityEnclosingRequest) httpMethod)
                .setEntity(new ByteArrayEntity(requestContent.getBytes()));
          }
        } else if (attachments.size() > 0) {
          try {
            MimeMultipart mp = null;

            if (StringUtils.hasContent(requestContent)) {
              mp = new MimeMultipart();
              initRootPart(request, requestContent, mp);
            } else if (attachments.size() == 1) {
              ((HttpEntityEnclosingRequest) httpMethod)
                  .setEntity(new InputStreamEntity(attachments.get(0).getInputStream(), -1));

              httpMethod.setHeader(
                  "Content-Type", getContentTypeHeader(request.getMediaType(), encoding));
            }

            if (((HttpEntityEnclosingRequest) httpMethod).getEntity() == null) {
              if (mp == null) mp = new MimeMultipart();

              // init mimeparts
              AttachmentUtils.addMimeParts(request, attachments, mp, new StringToStringMap());

              // create request message
              MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION);
              message.setContent(mp);
              message.saveChanges();
              RestRequestMimeMessageRequestEntity mimeMessageRequestEntity =
                  new RestRequestMimeMessageRequestEntity(message, request);
              ((HttpEntityEnclosingRequest) httpMethod).setEntity(mimeMessageRequestEntity);
              httpMethod.setHeader(
                  "Content-Type",
                  getContentTypeHeader(
                      mimeMessageRequestEntity.getContentType().getValue(), encoding));
              httpMethod.setHeader("MIME-Version", "1.0");
            }
          } catch (Exception e) {
            SoapUI.logError(e);
          }
        }
      }
    }
  }
コード例 #12
0
ファイル: URI.java プロジェクト: sourcewarehouse/JCGO
 /**
  * Compares the fragment of this URI with that of the supplied URI.
  *
  * @param uri the URI to compare with this one.
  * @return a negative integer, zero or a positive integer depending on whether this uri's fragment
  *     is less than, equal to or greater than the fragment of the uri supplied, respectively.
  */
 private int compareFragments(URI uri) {
   if (rawFragment == null && uri.getRawFragment() != null) return -1;
   else if (rawFragment == null) return 0;
   else return rawFragment.compareTo(uri.getRawFragment());
 }
コード例 #13
0
 /**
  * Returns the raw (encoded) fragment element.
  *
  * @return the raw fragment element.
  */
 public String getRawFragment() {
   return uri.getRawFragment();
 }
コード例 #14
0
  /**
   * Fully relativize the source part URI against the target part URI.
   *
   * @param sourceURI The source part URI.
   * @param targetURI The target part URI.
   * @param msCompatible if true then remove leading slash from the relativized URI. This flag
   *     violates [M1.4]: A part name shall start with a forward slash ('/') character, but allows
   *     generating URIs compatible with MS Office and OpenOffice.
   * @return A fully relativize part name URI ('word/media/image1.gif', '/word/document.xml' =>
   *     'media/image1.gif') else <code>null</code>.
   */
  public static URI relativizeURI(URI sourceURI, URI targetURI, boolean msCompatible) {
    StringBuilder retVal = new StringBuilder();
    String[] segmentsSource = sourceURI.getPath().split("/", -1);
    String[] segmentsTarget = targetURI.getPath().split("/", -1);

    // If the source URI is empty
    if (segmentsSource.length == 0) {
      throw new IllegalArgumentException("Can't relativize an empty source URI !");
    }

    // If target URI is empty
    if (segmentsTarget.length == 0) {
      throw new IllegalArgumentException("Can't relativize an empty target URI !");
    }

    // If the source is the root, then the relativized
    //  form must actually be an absolute URI
    if (sourceURI.toString().equals("/")) {
      String path = targetURI.getPath();
      if (msCompatible && path.length() > 0 && path.charAt(0) == '/') {
        try {
          targetURI = new URI(path.substring(1));
        } catch (Exception e) {
          _logger.log(POILogger.WARN, e);
          return null;
        }
      }
      return targetURI;
    }

    // Relativize the source URI against the target URI.
    // First up, figure out how many steps along we can go
    // and still have them be the same
    int segmentsTheSame = 0;
    for (int i = 0; i < segmentsSource.length && i < segmentsTarget.length; i++) {
      if (segmentsSource[i].equals(segmentsTarget[i])) {
        // Match so far, good
        segmentsTheSame++;
      } else {
        break;
      }
    }

    // If we didn't have a good match or at least except a first empty element
    if ((segmentsTheSame == 0 || segmentsTheSame == 1)
        && segmentsSource[0].equals("")
        && segmentsTarget[0].equals("")) {
      for (int i = 0; i < segmentsSource.length - 2; i++) {
        retVal.append("../");
      }
      for (int i = 0; i < segmentsTarget.length; i++) {
        if (segmentsTarget[i].equals("")) continue;
        retVal.append(segmentsTarget[i]);
        if (i != segmentsTarget.length - 1) retVal.append("/");
      }

      try {
        return new URI(retVal.toString());
      } catch (Exception e) {
        _logger.log(POILogger.WARN, e);
        return null;
      }
    }

    // Special case for where the two are the same
    if (segmentsTheSame == segmentsSource.length && segmentsTheSame == segmentsTarget.length) {
      if (sourceURI.equals(targetURI)) {
        // if source and target are the same they should be resolved to the last segment,
        // Example: if a slide references itself, e.g. the source URI is
        // "/ppt/slides/slide1.xml" and the targetURI is "slide1.xml" then
        // this it should be relativized as "slide1.xml", i.e. the last segment.
        retVal.append(segmentsSource[segmentsSource.length - 1]);
      } else {
        retVal.append("");
      }

    } else {
      // Matched for so long, but no more

      // Do we need to go up a directory or two from
      // the source to get here?
      // (If it's all the way up, then don't bother!)
      if (segmentsTheSame == 1) {
        retVal.append("/");
      } else {
        for (int j = segmentsTheSame; j < segmentsSource.length - 1; j++) {
          retVal.append("../");
        }
      }

      // Now go from here on down
      for (int j = segmentsTheSame; j < segmentsTarget.length; j++) {
        if (retVal.length() > 0 && retVal.charAt(retVal.length() - 1) != '/') {
          retVal.append("/");
        }
        retVal.append(segmentsTarget[j]);
      }
    }

    // if the target had a fragment then append it to the result
    String fragment = targetURI.getRawFragment();
    if (fragment != null) {
      retVal.append("#").append(fragment);
    }

    try {
      return new URI(retVal.toString());
    } catch (Exception e) {
      _logger.log(POILogger.WARN, e);
      return null;
    }
  }
コード例 #15
0
ファイル: HTTPUtil.java プロジェクト: denuno/Lucee4
  public static URI toURI(String strUrl, int port) throws URISyntaxException {

    // print.o((strUrl));
    URI uri = new URI(strUrl);

    String host = uri.getHost();
    String fragment = uri.getRawFragment();
    String path = uri.getRawPath();
    String query = uri.getRawQuery();

    String scheme = uri.getScheme();
    String userInfo = uri.getRawUserInfo();
    if (port <= 0) port = uri.getPort();

    // decode path
    if (!StringUtil.isEmpty(path)) {

      int sqIndex = path.indexOf(';');
      String q = null;
      if (sqIndex != -1) {
        q = path.substring(sqIndex + 1);
        path = path.substring(0, sqIndex);
      }

      StringBuilder res = new StringBuilder();

      StringList list = ListUtil.toListTrim(path, '/');
      String str;

      while (list.hasNext()) {
        str = list.next();
        // str=URLDecoder.decode(str);

        if (StringUtil.isEmpty(str)) continue;
        res.append("/");
        res.append(escapeQSValue(str));
      }
      if (StringUtil.endsWith(path, '/')) res.append('/');
      path = res.toString();

      if (sqIndex != -1) {
        path += decodeQuery(q, ';');
      }
    }

    // decode query
    query = decodeQuery(query, '?');

    // decode ref/anchor
    if (!StringUtil.isEmpty(fragment)) {
      fragment = escapeQSValue(fragment);
    }

    // user/pasword
    if (!StringUtil.isEmpty(userInfo)) {
      int index = userInfo.indexOf(':');
      if (index != -1) {
        userInfo =
            escapeQSValue(userInfo.substring(0, index))
                + ":"
                + escapeQSValue(userInfo.substring(index + 1));
      } else userInfo = escapeQSValue(userInfo);
    }

    /*print.o("- fragment:"+fragment);
    print.o("- host:"+host);
    print.o("- path:"+path);
    print.o("- query:"+query);
    print.o("- scheme:"+scheme);
    print.o("- userInfo:"+userInfo);
    print.o("- port:"+port);
    print.o("- absolute:"+uri.isAbsolute());
    print.o("- opaque:"+uri.isOpaque());*/

    StringBuilder rtn = new StringBuilder();
    if (scheme != null) {
      rtn.append(scheme);
      rtn.append("://");
    }
    if (userInfo != null) {
      rtn.append(userInfo);
      rtn.append("@");
    }
    if (host != null) {
      rtn.append(host);
    }
    if (port > 0) {
      rtn.append(":");
      rtn.append(port);
    }
    if (path != null) {
      rtn.append(path);
    }
    if (query != null) {
      // rtn.append("?");
      rtn.append(query);
    }
    if (fragment != null) {
      rtn.append("#");
      rtn.append(fragment);
    }

    return new URI(rtn.toString());
  }