public NetServerSpecFactoryBean configure(URI uri) {
    setHost(null != uri.getHost() ? uri.getHost() : "0.0.0.0");
    setPort(uri.getPort() > 0 ? uri.getPort() : 3000);
    setFraming(null != uri.getPath() ? uri.getPath().substring(1) : "linefeed");
    this.delegateCodec = StandardCodecs.STRING_CODEC;

    if (null != uri.getQuery()) {
      String[] params = StringUtils.split(uri.getQuery(), "&");
      if (null == params) {
        params = new String[] {uri.getQuery()};
      }
      for (String pair : params) {
        String[] parts = StringUtils.split(pair, "=");
        if (parts.length > 1) {
          if ("codec".equals(parts[0])) {
            setCodec(parts[1]);
          } else if ("dispatcher".equals(parts[0])) {
            setDispatcher(parts[1]);
          } else if ("lengthFieldLength".equals(parts[0])) {
            setLengthFieldLength(Integer.parseInt(parts[1]));
          }
        }
      }
    }
    return this;
  }
  public static String join(String source, String fragment) {
    try {
      boolean isRelative = false;
      if (source.startsWith("/") || source.startsWith(".")) {
        isRelative = true;
      }
      URI uri = new URI(source);

      if (!source.endsWith("/") && (fragment.startsWith("./") && "".equals(uri.getPath()))) {
        uri = new URI(source + "/");
      } else if ("".equals(uri.getPath()) && !fragment.startsWith("/")) {
        uri = new URI(source + "/");
      }
      URI f = new URI(fragment);

      URI resolved = uri.resolve(f);

      URI normalized = resolved.normalize();
      if (Character.isAlphabetic(normalized.toString().charAt(0)) && isRelative) {
        return "./" + normalized.toString();
      }
      return normalized.toString();
    } catch (Exception e) {
      return source;
    }
  }
  public InputStream openResource(URI uri) throws IOException {
    if (uri.isAbsolute() && uri.getScheme().equals("file")) {
      try {
        return uri.toURL().openStream();
      } catch (Exception except) {
        log.error("openResource: unable to open file URL " + uri + "; " + except.toString());
        return null;
      }
    }

    // Note that if we get an absolute URI, the relativize operation will simply
    // return the absolute URI.
    URI relative = baseUri.relativize(uri);

    if (relative.isAbsolute() && relative.getScheme().equals("http")) {
      try {
        return relative.toURL().openStream();
      } catch (Exception except) {
        log.error("openResource: unable to open http URL " + uri + "; " + except.toString());
        return null;
      }
    }

    if (relative.isAbsolute() && !relative.getScheme().equals("urn")) {
      log.error("openResource: invalid scheme (should be urn:)  " + uri);
      return null;
    }

    File f = new File(baseUri.getPath(), relative.getPath());
    if (!f.exists()) {
      log.error("openResource: file not found " + f);
      return null;
    }
    return new FileInputStream(f);
  }
Esempio n. 4
0
  /**
   * Returns the diagram that has been loaded from this root. If diagram is not already loaded,
   * returns null.
   */
  public SVGDiagram getDiagram(URI xmlBase, boolean loadIfAbsent) {
    if (xmlBase == null) {
      return null;
    }

    SVGDiagram dia = (SVGDiagram) loadedDocs.get(xmlBase);
    if (dia != null || !loadIfAbsent) {
      return dia;
    }

    // Load missing diagram
    try {
      URL url;
      if ("jar".equals(xmlBase.getScheme())
          && xmlBase.getPath() != null
          && !xmlBase.getPath().contains("!/")) {
        // Workaround for resources stored in jars loaded by Webstart.
        // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6753651
        url = SVGUniverse.class.getResource("xmlBase.getPath()");
      } else {
        url = xmlBase.toURL();
      }

      loadSVG(url, false);
      dia = (SVGDiagram) loadedDocs.get(xmlBase);
      return dia;
    } catch (Exception e) {
      Logger.getLogger(SVGConst.SVG_LOGGER).log(Level.WARNING, "Could not parse", e);
    }

    return null;
  }
Esempio n. 5
0
 /** Illegal characters unescaped in the string, for glob processing, etc. */
 @Override
 public String toString() {
   StringBuffer sb = new StringBuffer();
   if (mUri.getScheme() != null) {
     sb.append(mUri.getScheme());
     sb.append(":");
   }
   if (mUri.getAuthority() != null) {
     sb.append("//");
     sb.append(mUri.getAuthority());
   }
   if (mUri.getPath() != null) {
     String path = mUri.getPath();
     if (path.indexOf('/') == 0
         && hasWindowsDrive(path, true)
         && // has windows drive
         mUri.getScheme() == null
         && // but no scheme
         mUri.getAuthority() == null) { // or authority
       path = path.substring(1); // remove slash before drive
     }
     sb.append(path);
   }
   return sb.toString();
 }
Esempio n. 6
0
  /**
   * Creates a new FTPFile instance by converting the given file: URI into an abstract pathname.
   *
   * <p>FTP URI protocol:<br>
   * ftp:// [ userName [ : password ] @ ] host [ : port ][ / path ]
   *
   * <p>example:<br>
   * ftp://[email protected]:21/pub/testfile.txt
   *
   * @param uri An absolute, hierarchical URI using a supported scheme.
   * @throws NullPointerException if <code>uri</code> is <code>null</code>.
   * @throws IllegalArgumentException If the preconditions on the parameter do not hold.
   */
  public FTPFile(URI uri) throws IOException, URISyntaxException {
    super(uri);

    if (uri.getScheme().equals("ftp")) {
      String userinfo = uri.getUserInfo();
      if (userinfo != null) {
        int index = userinfo.indexOf(":");
        if (index >= 0) {
          setFileSystem(
              new FTPFileSystem(
                  new FTPAccount(
                      uri.getHost(),
                      uri.getPort(),
                      userinfo.substring(0, index - 1),
                      userinfo.substring(index + 1),
                      uri.getPath())));
        } else {
          setFileSystem(
              new FTPFileSystem(
                  new FTPAccount(uri.getHost(), uri.getPort(), userinfo, "", uri.getPath())));
        }
      } else {
        fileSystem =
            new FTPFileSystem(
                new FTPAccount(uri.getHost(), uri.getPort(), null, "", uri.getPath()));
      }

      setFileName(uri.getPath());
      ftpClient = ((FTPFileSystem) fileSystem).getFTPClient();
    } else {
      throw new URISyntaxException(uri.toString(), "Wrong URI scheme");
    }
  }
Esempio n. 7
0
 /**
  * Return a File for a URI from a .jos/.joz file.
  *
  * <p>Returns null if the URI points to a file inside the zip archive. In this case, inZipPath
  * will be set to the corresponding path.
  */
 public File getFile(String uriStr) throws IOException {
   inZipPath = null;
   try {
     URI uri = new URI(uriStr);
     if ("file".equals(uri.getScheme()))
       // absolute path
       return new File(uri);
     else if (uri.getScheme() == null) {
       // Check if this is an absolute path without 'file:' scheme part.
       // At this point, (as an exception) platform dependent path separator will be recognized.
       // (This form is discouraged, only for users that like to copy and paste a path manually.)
       File file = new File(uriStr);
       if (file.isAbsolute()) return file;
       else {
         // for relative paths, only forward slashes are permitted
         if (isZip()) {
           if (uri.getPath().startsWith("../")) {
             // relative to session file - "../" step out of the archive
             String relPath = uri.getPath().substring(3);
             return new File(sessionFileURI.resolve(relPath));
           } else {
             // file inside zip archive
             inZipPath = uriStr;
             return null;
           }
         } else return new File(sessionFileURI.resolve(uri));
       }
     } else
       throw new IOException(
           tr("Unsupported scheme ''{0}'' in URI ''{1}''.", uri.getScheme(), uriStr));
   } catch (URISyntaxException e) {
     throw new IOException(e);
   }
 }
Esempio n. 8
0
  public static void main(String args[]) throws URISyntaxException, MalformedURLException {

    URL url = null;
    URL url1 = null;

    try {
      url = new URL(unencoded);
      url1 = new URL(encoded);
    } catch (Exception e) {
      System.out.println("Unexpected exception :" + e);
      System.exit(-1);
    }

    if (url.sameFile(url1)) {
      throw new RuntimeException("URL does not understand escaping");
    }

    /* check decoding of a URL */

    URI uri = url1.toURI();
    if (!uri.getPath().equals(path)) {
      throw new RuntimeException("Got: " + uri.getPath() + " expected: " + path);
    }

    /* check encoding of a URL */

    URI uri1 = new URI(scheme, auth, path);
    url = uri.toURL();
    if (!url.toString().equals(encoded)) {
      throw new RuntimeException("Got: " + url.toString() + " expected: " + encoded);
    }
  }
Esempio n. 9
0
    protected AhcWebSocketWrappedOutputStream(
        Message message,
        boolean possibleRetransmit,
        boolean isChunking,
        int chunkThreshold,
        String conduitName,
        URI url) {
      super(message, possibleRetransmit, isChunking, chunkThreshold, conduitName, url);

      entity = message.get(AhcWebSocketConduitRequest.class);
      // REVISIT how we prepare the request
      String requri = (String) message.getContextualProperty("org.apache.cxf.request.uri");
      if (requri != null) {
        // jaxrs speicfies a sub-path using prop org.apache.cxf.request.uri
        if (requri.startsWith("ws")) {
          entity.setPath(requri.substring(requri.indexOf('/', 3 + requri.indexOf(':'))));
        } else {
          entity.setPath(url.getPath() + requri);
        }
      } else {
        // jaxws
        entity.setPath(url.getPath());
      }
      entity.setId(UUID.randomUUID().toString());
      uncorrelatedRequests.put(entity.getId(), new RequestResponse(entity));
    }
Esempio n. 10
0
  public boolean isDirectory(URI uri) {
    try {
      if (uri.getPath() != null && uri.getPath().endsWith(".jar!")) {
        // if the uri is the root of a jar, and it ends with a !, it should be considered a
        // directory
        return true;
      }
      String jar = getJar(uri);
      String path = getPath(uri);

      if (!path.endsWith("/")) {
        path = path + "/";
      }

      JarFile jarFile = new JarFile(jar);
      try {
        JarEntry jarEntry = jarFile.getJarEntry(path);
        if (jarEntry != null && jarEntry.isDirectory()) {
          return true;
        }
        // maybe the path is not in the jar as a seperate entry, but there are files in the path
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
          if (entries.nextElement().getName().startsWith(path)) {
            return true;
          }
        }
        return false;
      } finally {
        jarFile.close();
      }
    } catch (IOException e) {
      return false;
    }
  }
 public String getNormalizedServerUri() throws URISyntaxException {
   URI uri = new URI(originalServerUri);
   if (uri.getAuthority() == null) uri = new URI("ws://" + originalServerUri);
   if (uri.getPort() == -1)
     if ("ws".equals(uri.getScheme().toLowerCase(Locale.ENGLISH)))
       uri =
           new URI(
               "ws",
               uri.getUserInfo(),
               uri.getHost(),
               PluginConfig.DEFAULT_TCP_PORT,
               uri.getPath(),
               uri.getQuery(),
               uri.getFragment());
     else if ("wss".equals(uri.getScheme().toLowerCase(Locale.ENGLISH)))
       uri =
           new URI(
               "wss",
               uri.getUserInfo(),
               uri.getHost(),
               PluginConfig.DEFAULT_SSL_PORT,
               uri.getPath(),
               uri.getQuery(),
               uri.getFragment());
   return uri.toString();
 }
Esempio n. 12
0
 public String toString() {
   // we can't use uri.toString(), which escapes everything, because we want
   // illegal characters unescaped in the string, for glob processing, etc.
   StringBuilder buffer = new StringBuilder();
   if (uri.getScheme() != null) {
     buffer.append(uri.getScheme());
     buffer.append(":");
   }
   if (uri.getAuthority() != null) {
     buffer.append("//");
     buffer.append(uri.getAuthority());
   }
   if (uri.getPath() != null) {
     String path = uri.getPath();
     if (path.indexOf('/') == 0
         && hasWindowsDrive(path, true)
         && // has windows drive
         uri.getScheme() == null
         && // but no scheme
         uri.getAuthority() == null) // or authority
     path = path.substring(1); // remove slash before drive
     buffer.append(path);
   }
   if (uri.getFragment() != null) {
     buffer.append("#");
     buffer.append(uri.getFragment());
   }
   return buffer.toString();
 }
Esempio n. 13
0
  @Override
  protected ChannelFuture writeRequest(@Nullable ByteBuf request) {
    DefaultFullHttpRequest httpRequest;

    if (request == Unpooled.EMPTY_BUFFER || request == null || request.readableBytes() == 0) {
      httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri.getPath());
      // httpRequest.headers().add(HttpHeaders.CONTENT_LENGTH, "0");
    } else {
      httpRequest =
          new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uri.getPath(), request);
      //      httpRequest.headers().add(HttpHeaders.CONTENT_LENGTH, request.readableBytes());
    }

    if (headerDictionary != null) {
      for (Map.Entry<String, String> entry : headerDictionary.entrySet()) {
        httpRequest.headers().add(entry.getKey(), entry.getValue());
      }
    }

    httpRequest.headers().set(HttpHeaders.CONNECTION, CLOSE);
    //    httpRequest.headers().set(HttpHeaders.ACCEPT_ENCODING, GZIP);

    // TODO(JR): Remove logger before deployment
    // log.debug("\nHTTP Request from XIO:\n" + httpRequest);

    return underlyingNettyChannel.writeAndFlush(httpRequest);
  }
  private List<HttpCookie> getValidCookies(URI uri) {
    List<HttpCookie> targetCookies = new ArrayList<HttpCookie>();
    // If the stored URI does not have a path then it must match any URI in
    // the same domain
    for (URI storedUri : allCookies.keySet()) {
      // Check ith the domains match according to RFC 6265
      if (checkDomainsMatch(storedUri.getHost(), uri.getHost())) {
        // Check if the paths match according to RFC 6265
        if (checkPathsMatch(storedUri.getPath(), uri.getPath())) {
          targetCookies.addAll(allCookies.get(storedUri));
        }
      }
    }

    // Check it there are expired cookies and remove them
    if (!targetCookies.isEmpty()) {
      List<HttpCookie> cookiesToRemoveFromPersistence = new ArrayList<HttpCookie>();
      for (Iterator<HttpCookie> it = targetCookies.iterator(); it.hasNext(); ) {
        HttpCookie currentCookie = it.next();
        if (currentCookie.hasExpired()) {
          cookiesToRemoveFromPersistence.add(currentCookie);
          it.remove();
        }
      }

      if (!cookiesToRemoveFromPersistence.isEmpty()) {
        removeFromPersistence(uri, cookiesToRemoveFromPersistence);
      }
    }
    return targetCookies;
  }
Esempio n. 15
0
  /**
   * Resolve a child path against a parent path.
   *
   * @param parent the parent path
   * @param child the child path
   */
  public Path(Path parent, Path child) {
    // Add a slash to parent's path so resolution is compatible with URI's
    URI parentUri = parent.uri;
    final String parentPath = parentUri.getPath();
    if (!(parentPath.equals("/") || parentPath.equals(""))) {
      try {
        parentUri =
            new URI(
                parentUri.getScheme(),
                parentUri.getAuthority(),
                parentUri.getPath() + "/",
                null,
                null);
      } catch (URISyntaxException e) {
        throw new IllegalArgumentException(e);
      }
    }

    if (child.uri.getPath().startsWith(Path.SEPARATOR)) {
      child =
          new Path(
              child.uri.getScheme(), child.uri.getAuthority(), child.uri.getPath().substring(1));
    }

    final URI resolved = parentUri.resolve(child.uri);
    initialize(resolved.getScheme(), resolved.getAuthority(), normalizePath(resolved.getPath()));
  }
Esempio n. 16
0
 public static boolean isUsableURI(URI uri) {
   try {
     java.net.URL u = new URL(uri.toString());
   } catch (MalformedURLException e) {
     return false;
   }
   return !(uri.getPath() == null || uri.getPath().length() == 0);
 }
Esempio n. 17
0
 private static InputStream readFromHDFS(
     FileSystem fs, String name, URI uri, ApplicationSpec appSpec, ApplicationId appId)
     throws Exception {
   // will throw exception if the file name is without extension
   String extension = uri.getPath().substring(uri.getPath().lastIndexOf(".") + 1);
   String pathSuffix = appSpec.getAppName() + "/" + appId.getId() + "/" + name + "." + extension;
   Path dst = new Path(fs.getHomeDirectory(), pathSuffix);
   return fs.open(dst).getWrappedStream();
 }
 /**
  * Combine two URIs.
  *
  * @param prefix the prefix URI
  * @param suffix the suffix URI
  * @return the combined URI
  */
 public static URI combine(URI prefix, URI suffix) {
   URI retUri = null;
   try {
     retUri = new URI(combine(prefix.getPath(), suffix.getPath()));
   } catch (URISyntaxException e) {
     throw new IllegalArgumentException("Prefix and suffix can't be combine !");
   }
   return retUri;
 }
 /**
  * Return a proper URL with lowercase scheme, lowercase domain, stripped hash - used to compare
  * against other previously seen URLs
  *
  * @param href A relative or absolute URL
  * @param context Null or an absolute URL to use when href is relative
  * @return
  */
 public static URL getCanonicalURL(String href, String context) {
   try {
     URI normalized;
     if (context != null) {
       normalized = new URI(context);
       if (normalized.getPath().equals("")) context += "/";
       normalized = new URI(context).resolve(href);
     } else {
       normalized = new URI(href);
     }
     normalized = normalized.normalize();
     return new URI(
             normalized.getScheme().toLowerCase(),
             normalized.getUserInfo(),
             normalized.getHost(),
             normalized.getPort(),
             normalized.getPath().equals("") ? "/" : normalized.getPath(),
             normalized.getQuery(),
             null)
         .toURL();
   } catch (URISyntaxException e) {
     LogFactory.getLog(URLCanonicalizer.class)
         .error("Unable to canonicalize href: " + href + ", context" + context, e);
     return null;
   } catch (MalformedURLException e) {
     LogFactory.getLog(URLCanonicalizer.class)
         .error("Unable to canonicalize href: " + href + ", context" + context, e);
     return null;
   } catch (IllegalArgumentException e) {
     LogFactory.getLog(URLCanonicalizer.class)
         .error("Unable to canonicalize href: " + href + ", context" + context, e);
     return null;
   }
   /*if (href.contains("#")) {
             href = href.substring(0, href.indexOf("#"));
         }
   href = href.replace(" ", "%20");
         try {
         	URL canonicalURL;
         	if (context == null) {
         		canonicalURL = new URL(href);
         	} else {
         		canonicalURL = new URL(new URL(context), href);
         	}
         	String path = canonicalURL.getPath();
         	if (path.startsWith("/../")) {
         		path = path.substring(3);
         		canonicalURL = new URL(canonicalURL.getProtocol(), canonicalURL.getHost(), canonicalURL.getPort(), path);
         	} else if (path.contains("..")) {
         		System.out.println("Found path with ..: " + path + " " + href + " " + context);
         	}
         	return canonicalURL;
         } catch (MalformedURLException ex) {
             return null;
         }*/
 }
Esempio n. 20
0
  public static Constants.Format extractFormat(URI uri) {
    String path = uri.getPath() == null ? uri.toString() : uri.getPath().toLowerCase();
    Constants.Format format = Constants.Format.json;

    if (path.endsWith(".xml")) format = Constants.Format.xml;
    else if (path.endsWith(".json")) format = Constants.Format.json;
    else if (path.contains(".xml/")) format = Constants.Format.xml;

    return format;
  }
 /**
  * Returns the route URI for the current request
  *
  * @param request HttpRequest which contains the request URI of the current session
  * @return Returns the route
  * @throws URISyntaxException
  */
 public TrackingType setTrackingType(HttpRequest request) throws URISyntaxException {
   URI uri = new URI(request.getUri());
   if (uri.getPath().startsWith("/trackingPoint")) {
     return TrackingType.TRACKING_POINT;
   } else if (uri.getPath().startsWith("/startTracking")) {
     return TrackingType.START_TRACKING;
   } else if (uri.getPath().startsWith("/stopTracking")) {
     return TrackingType.STOP_TRACKING;
   } else {
     return TrackingType.UNKNOWN;
   }
 }
Esempio n. 22
0
 /**
  * Reformat the S3URL to locate a directory resource, i.e. contains an octet encoded trailing "/"
  */
 private static URI encodeAsDirectory(URI uri) {
   if (null == uri) throw new NullPointerException();
   // add a trailing, octet encoded "/" to the path and rebuild the URL
   try {
     if (null != uri.getPath()) {
       if (uri.getPath().endsWith(SEPERATOR)) return uri;
       else return new URI(uri.getScheme(), uri.getAuthority(), uri.getPath() + SEPERATOR, null);
     } else return new URI(uri.getScheme(), uri.getAuthority(), SEPERATOR, null);
   } catch (URISyntaxException e) {
     throw new IllegalArgumentException("can't encode a s3 object with directory path", e);
   }
 }
Esempio n. 23
0
 /**
  * Makes sure, that URI points to directory by adding slash to it. Useful in relativizing URIs.
  */
 public static URI addSlash(URI u) throws HiveException {
   if (u.getPath().endsWith("/")) {
     return u;
   } else {
     try {
       return new URI(
           u.getScheme(), u.getAuthority(), u.getPath() + "/", u.getQuery(), u.getFragment());
     } catch (URISyntaxException e) {
       throw new HiveException("Couldn't append slash to a URI", e);
     }
   }
 }
Esempio n. 24
0
  public void testToUri() {
    if (!SystemInfo.isWindows) {
      assertEquals("file:///asd", VfsUtil.toUri(new File("/asd")).toASCIIString());
      assertEquals("file:///asd%20/sd", VfsUtil.toUri(new File("/asd /sd")).toASCIIString());
    }

    URI uri = VfsUtil.toUri("file:///asd");
    assertNotNull(uri);
    assertEquals("file", uri.getScheme());
    assertEquals("/asd", uri.getPath());

    uri = VfsUtil.toUri("file:///asd/ ads/ad#test");
    assertNotNull(uri);
    assertEquals("file", uri.getScheme());
    assertEquals("/asd/ ads/ad", uri.getPath());
    assertEquals("test", uri.getFragment());

    uri = VfsUtil.toUri("file:///asd/ ads/ad#");
    assertNotNull(uri);
    assertEquals("file:///asd/%20ads/ad#", uri.toString());

    uri = VfsUtil.toUri("mailto:[email protected]");
    assertNotNull(uri);
    assertEquals("*****@*****.**", uri.getSchemeSpecificPart());

    if (SystemInfo.isWindows) {
      uri = VfsUtil.toUri("file://C:/p");
      assertNotNull(uri);
      assertEquals("file", uri.getScheme());
      assertEquals("/C:/p", uri.getPath());
    }

    uri = VfsUtil.toUri("file:///Users/S pace");
    assertNotNull(uri);
    assertEquals("file", uri.getScheme());
    assertEquals("/Users/S pace", uri.getPath());
    assertEquals("/Users/S%20pace", uri.getRawPath());
    assertEquals("file:///Users/S%20pace", uri.toString());

    uri = VfsUtil.toUri("http://developer.android.com/guide/developing/tools/avd.html");
    assertNotNull(uri);
    assertEquals("http", uri.getScheme());
    assertEquals("/guide/developing/tools/avd.html", uri.getRawPath());
    assertEquals("http://developer.android.com/guide/developing/tools/avd.html", uri.toString());

    uri = VfsUtil.toUri("http://developer.android.com/guide/developing/tools/avd.html?f=23r2ewd");
    assertNotNull(uri);
    assertEquals("http", uri.getScheme());
    assertEquals("/guide/developing/tools/avd.html", uri.getRawPath());
    assertEquals(
        "http://developer.android.com/guide/developing/tools/avd.html?f=23r2ewd", uri.toString());
    assertEquals("f=23r2ewd", uri.getQuery());
  }
 private URI toIpUri(Endpoint endpoint, URI uri) throws URISyntaxException {
   final URI endpointUri = endpoint.getUri();
   final String fullpath = endpointUri.getPath() + uri.getPath();
   return new URI(
       endpointUri.getScheme(),
       endpointUri.getUserInfo(),
       endpoint.getIp().getHostAddress(),
       endpointUri.getPort(),
       fullpath,
       uri.getQuery(),
       null);
 }
Esempio n. 26
0
 protected void initUrls() throws Exception {
   ClassLoader classLoader = NXRuntimeTestCase.class.getClassLoader();
   urls = introspectClasspath(classLoader);
   // special cases such as Surefire with useManifestOnlyJar or Jacoco
   // Look for nuxeo-runtime
   boolean found = false;
   JarFile surefirebooterJar = null;
   for (URL url : urls) {
     URI uri = url.toURI();
     if (uri.getPath().matches(".*/nuxeo-runtime-[^/]*\\.jar")) {
       found = true;
       break;
     } else if (uri.getScheme().equals("file") && uri.getPath().contains("surefirebooter")) {
       surefirebooterJar = new JarFile(new File(uri));
     }
   }
   if (!found && surefirebooterJar != null) {
     try {
       String cp =
           surefirebooterJar
               .getManifest()
               .getMainAttributes()
               .getValue(Attributes.Name.CLASS_PATH);
       if (cp != null) {
         String[] cpe = cp.split(" ");
         URL[] newUrls = new URL[cpe.length];
         for (int i = 0; i < cpe.length; i++) {
           // Don't need to add 'file:' with maven surefire
           // >= 2.4.2
           String newUrl = cpe[i].startsWith("file:") ? cpe[i] : "file:" + cpe[i];
           newUrls[i] = new URL(newUrl);
         }
         urls = newUrls;
       }
     } catch (Exception e) {
       // skip
     } finally {
       surefirebooterJar.close();
     }
   }
   if (log.isDebugEnabled()) {
     StringBuilder sb = new StringBuilder();
     sb.append("URLs on the classpath: ");
     for (URL url : urls) {
       sb.append(url.toString());
       sb.append('\n');
     }
     log.debug(sb.toString());
   }
   readUris = new HashSet<>();
   bundles = new HashMap<>();
 }
Esempio n. 27
0
File: IO.java Progetto: nremond/boon
 public static Path uriToPath(URI uri) {
   Path thePath = null;
   if (Sys.isWindows()) {
     String newPath = uri.getPath();
     if (newPath.startsWith("/C:")) {
       newPath = slc(newPath, 3);
     }
     thePath = FileSystems.getDefault().getPath(newPath);
   } else {
     thePath = FileSystems.getDefault().getPath(uri.getPath());
   }
   return thePath;
 }
 public void setApiEndpoint(URI apiEndpoint) {
   if (apiEndpoint != null && apiEndpoint.getPath() != null && !apiEndpoint.getPath().isEmpty()) {
     throw new IllegalArgumentException("apiEndpoint should not contain a path");
   }
   if (apiEndpoint != null
       && (apiEndpoint.getUserInfo() != null
           || apiEndpoint.getQuery() != null
           || apiEndpoint.getFragment() != null)) {
     throw new IllegalArgumentException(
         "apiEndpoint should not contain user info, query or fragment");
   }
   this.apiEndpoint = apiEndpoint;
 }
Esempio n. 29
0
  private URL resolveClassPathResourceName(String httpPath) {

    try {
      URI uri = new URI(httpPath);
      if (uri.getPath() == null) {
        throw new IllegalArgumentException("Wrong path in uri: " + httpPath);
      }
      return classLoader.getResource(uri.getPath().substring(1));

    } catch (URISyntaxException use) {
      throw new IllegalArgumentException("Unable to parse uri: " + httpPath);
    }
  }
Esempio n. 30
0
  /* (non-Javadoc)
   * @see org.eclipse.cdt.managedbuilder.builddescription.IBuildResource#getLocation()
   */
  public IPath getLocation() {
    if (fFullWorkspacePath == null) {
      return new Path(fLocationURI.getPath());
    }

    IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember(fFullWorkspacePath);
    if (resource == null) {
      return new Path(fLocationURI.getPath());
    }

    if (resource.getLocation() != null) return resource.getLocation();
    else return new Path(fLocationURI.getPath());
  }