Java Code Examples for java.net.URI.isAbsolute()

The following are Jave code examples for showing how to use isAbsolute() of the java.net.URI class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: incubator-netbeans   File: WebUrlHyperlinkSupport.java   View Source Code Vote up 6 votes
private boolean checkUrl(int start, int end) {
    String hyperlink = text.subSequence(start, end).toString();
    try {
        URI uri = new URI(hyperlink);
        if (!uri.isAbsolute()) {
            return false;
        }
        String scheme = uri.getScheme();
        if (uri.isOpaque() && !scheme.equals("mailto")) {
            return false;
        }
        if (!scheme.equals("http") && !scheme.equals("https") && !scheme.equals("mailto")) {//NOI18N
            return false;
        }
        uri.toURL();             //just a check
    } catch (Exception ex) {
        return false;
    }
    return true;
}
 
Example 2
Project: mobile-store   File: ManageReposActivity.java   View Source Code Vote up 6 votes
/**
 * Some basic sanitization of URLs, so that two URLs which have the same semantic meaning
 * are represented by the exact same string by F-Droid. This will help to make sure that,
 * e.g. "http://10.0.1.50" and "http://10.0.1.50/" are not two different repositories.
 * <p>
 * Currently it normalizes the path so that "/./" are removed and "test/../" is collapsed.
 * This is done using {@link URI#normalize()}. It also removes multiple consecutive forward
 * slashes in the path and replaces them with one. Finally, it removes trailing slashes.
 */
private String normalizeUrl(String urlString) throws URISyntaxException {
    if (urlString == null) {
        return null;
    }
    URI uri = new URI(urlString);
    if (!uri.isAbsolute()) {
        throw new URISyntaxException(urlString, "Must provide an absolute URI for repositories");
    }

    uri = uri.normalize();
    String path = uri.getPath();
    if (path != null) {
        path = path.replaceAll("//*/", "/"); // Collapse multiple forward slashes into 1.
        if (path.length() > 0 && path.charAt(path.length() - 1) == '/') {
            path = path.substring(0, path.length() - 1);
        }
    }

    return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(),
            path, uri.getQuery(), uri.getFragment()).toString();
}
 
Example 3
Project: incubator-netbeans   File: AutoUpdateCatalogParser.java   View Source Code Vote up 6 votes
private static URL getDistribution (String distribution, URI base) {
    URL retval = null;
    if (distribution != null && distribution.length () > 0) {
        try {
            URI distributionURI = new URI (distribution);
            if (! distributionURI.isAbsolute ()) {
                if (base != null) {
                    distributionURI = base.resolve (distributionURI);
                }
            }
            retval = distributionURI.toURL ();
        } catch (MalformedURLException | URISyntaxException ex) {
            ERR.log (Level.INFO, null, ex);
        }
    }
    return retval;
}
 
Example 4
Project: incubator-netbeans   File: CatalogModelImpl.java   View Source Code Vote up 6 votes
private File retrieveCacheAndLookup(URI locationURI, FileObject sourceFileObject) throws IOException, CatalogModelException{
    File result = null;
    if((locationURI.isAbsolute()) && locationURI.getScheme().toLowerCase().
            startsWith("http") && !CatalogFileWrapperDOMImpl.TEST_ENVIRONMENT){
        // for all http and https absolute URI, just attempt downloading the
        // file using the retriever API and store in the private cache.
        //do not attempt this for a test environment.
        boolean res = false;
        try{
             res = Util.retrieveAndCache(locationURI, 
                    sourceFileObject,!fetchSynchronous, 
                    registerInCatalog);
        }catch (Exception e){//ignore all exceptions
        }
        if(res){
            //now attempt onec more
            result = resolveUsingPublicCatalog(locationURI);
            if(result != null)
                return result;
        }
    }
    return result;
}
 
Example 5
Project: nativehtml   File: Document.java   View Source Code Vote up 6 votes
public URI resolveUrl(String url) {
 if (this.url.isOpaque()) {
        try {
            URI uri = new URI(url);
            if (uri.isAbsolute()) {
                return uri;
            }
            String s = this.url.toString();
            int cut;
            if (url.startsWith("#")) {
                cut = s.indexOf('#');
                if (cut == -1) {
                    cut = s.length();
                }
            } else {
                cut = s.lastIndexOf('/') + 1;
            }
            return new URI(s.substring(0, cut) + url);
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }
    return this.url.resolve(url);
}
 
Example 6
Project: hype   File: Submitter.java   View Source Code Vote up 5 votes
private URI getStagingURI(String stagingLocation) {
  checkNotNull(stagingLocation);
  URI uri = URI.create(stagingLocation);
  if (!uri.isAbsolute()) {
    return URI.create("file://" + uri.toString());
  } else {
    return uri;
  }
}
 
Example 7
Project: HL4A   File: ModuleSourceProviderBase.java   View Source Code Vote up 5 votes
private ModuleSource loadFromPathArray(String moduleId,
        Scriptable paths, Object validator) throws IOException
{
    final long llength = ScriptRuntime.toUint32(
            ScriptableObject.getProperty(paths, "length"));
    // Yeah, I'll ignore entries beyond Integer.MAX_VALUE; so sue me.
    int ilength = llength > Integer.MAX_VALUE ? Integer.MAX_VALUE :
        (int)llength;

    for(int i = 0; i < ilength; ++i) {
        final String path = ensureTrailingSlash(
                ScriptableObject.getTypedProperty(paths, i, String.class));
        try {
            URI uri =  new URI(path);
            if (!uri.isAbsolute()) {
                uri = new File(path).toURI().resolve("");
            }
            final ModuleSource moduleSource = loadFromUri(
                    uri.resolve(moduleId), uri, validator);
            if(moduleSource != null) {
                return moduleSource;
            }
        }
        catch(URISyntaxException e) {
            throw new MalformedURLException(e.getMessage());
        }
    }
    return null;
}
 
Example 8
Project: incubator-netbeans   File: SelectRootsPanel.java   View Source Code Vote up 5 votes
@Override
public Component getListCellRendererComponent(
        final JList<?> list,
        Object value,
        final int index,
        final boolean isSelected,
        final boolean cellHasFocus) {
    if (value instanceof URI) {
        final URI uri = (URI) value;
        if (uri.isAbsolute()) {
            try {
                URL url = uri.toURL();
                String offset = null;
                if ("jar".equals(url.getProtocol())) {  //NOI18N
                    final String surl = url.toExternalForm();
                    int offsetPos = surl.lastIndexOf("!/"); //NOI18N
                    if (offsetPos > 0 && offsetPos < surl.length()-3) {
                        offset = surl.substring(offsetPos+2);
                    }
                    url = FileUtil.getArchiveFile(url);
                }
                if ("file".equals(url.getProtocol())) { //NOI18N
                    final File file = Utilities.toFile(url.toURI());
                    value = offset == null ?
                        file.getAbsolutePath() :
                        NbBundle.getMessage(
                            SelectRootsPanel.class,
                            "PATTERN_RELPATH_IN_FILE",
                            offset,
                            file.getAbsolutePath());
                }
            } catch (MalformedURLException | URISyntaxException ex) {
                //pass - value unchanged
            }
        }
    }
    return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
}
 
Example 9
Project: javaide   File: JavacFileManager.java   View Source Code Vote up 5 votes
/**
 * Enforces the specification of a "relative" URI as used in
 * {@linkplain #getFileForInput(Location, String, URI)
 * getFileForInput}.  This method must follow the rules defined in
 * that method, do not make any changes without consulting the
 * specification.
 */
protected static boolean isRelativeUri(URI uri) {
    if (uri.isAbsolute())
        return false;
    String path = uri.normalize().getPath();
    if (path.length() == 0 /* isEmpty() is mustang API */)
        return false;
    if (!path.equals(uri.getPath())) // implicitly checks for embedded . and ..
        return false;
    if (path.startsWith("/") || path.startsWith("./") || path.startsWith("../"))
        return false;
    return true;
}
 
Example 10
Project: incubator-netbeans   File: LibrariesSupport.java   View Source Code Vote up 5 votes
/**
 * Properly converts possibly relative URI to file path.
 * @param uri URI convert; can be relative URI; cannot be null
 * @return file path
 * @since org.netbeans.modules.project.libraries/1 1.18
 */
public static String convertURIToFilePath(URI uri) {
    if (uri.isAbsolute()) {
        return BaseUtilities.toFile(uri).getPath();
    } else {
        String path = uri.getPath();
        if (path.length() > 0 && path.charAt(path.length()-1) == '/') {   //NOI18N
            path = path.substring(0, path.length()-1);
        }
        return path.replace('/', File.separatorChar);   //NOI18N
    }
}
 
Example 11
Project: incubator-netbeans   File: NbMavenProjectImpl.java   View Source Code Vote up 5 votes
public URI[] getResources(boolean test) {
        List<URI> toRet = new ArrayList<URI>();
        URI projectroot = getProjectDirectory().toURI();
        Set<URI> sourceRoots = null;
        List<Resource> res = test ? getOriginalMavenProject().getTestResources() : getOriginalMavenProject().getResources();
        LBL : for (Resource elem : res) {
            String dir = elem.getDirectory();
            if (dir == null) {
                continue; // #191742
            }
            URI uri = FileUtilities.getDirURI(getProjectDirectory(), dir);
            if (elem.getTargetPath() != null || !elem.getExcludes().isEmpty() || !elem.getIncludes().isEmpty()) {
                URI rel = projectroot.relativize(uri);
                if (rel.isAbsolute()) { //outside of project directory
                    continue;// #195928, #231517
                }
                if (sourceRoots == null) {
                    sourceRoots = new HashSet<URI>();
                    sourceRoots.addAll(Arrays.asList(getSourceRoots(true)));
                    sourceRoots.addAll(Arrays.asList(getSourceRoots(false)));
                    //should we also consider generated sources? most like not necessary
                }
                for (URI sr : sourceRoots) {
                    if (!uri.relativize(sr).isAbsolute()) {
                        continue LBL;// #195928, #231517
                    }
                }
                //hope for the best now
            }
//            if (new File(uri).exists()) {
            toRet.add(uri);
//            }
        }
        return toRet.toArray(new URI[toRet.size()]);
    }
 
Example 12
Project: incubator-netbeans   File: ReferenceHelper.java   View Source Code Vote up 5 votes
private RawReference(String foreignProjectName, String artifactType, URI scriptLocation, String newScriptLocation, String targetName, String cleanTargetName, String artifactID, Properties props) throws IllegalArgumentException {
    this.foreignProjectName = foreignProjectName;
    this.artifactType = artifactType;
    if (scriptLocation != null && scriptLocation.isAbsolute()) {
        throw new IllegalArgumentException("Cannot use an absolute URI " + scriptLocation + " for script location"); // NOI18N
    }
    this.scriptLocation = scriptLocation;
    this.newScriptLocation = newScriptLocation;
    this.targetName = targetName;
    this.cleanTargetName = cleanTargetName;
    this.artifactID = artifactID;
    this.props = props;
}
 
Example 13
Project: incubator-netbeans   File: URLResourceRetriever.java   View Source Code Vote up 5 votes
public boolean accept(String baseAddr, String currentAddr) throws URISyntaxException {
    URI currURI = new URI(currentAddr);
    if( (currURI.isAbsolute()) && (currURI.getScheme().equalsIgnoreCase(URI_SCHEME)))
        return true;
    if(baseAddr != null){
        if(!currURI.isAbsolute()){
            URI baseURI = new URI(baseAddr);
            if(baseURI.getScheme().equalsIgnoreCase(URI_SCHEME))
                return true;
        }
    }
    return false;
}
 
Example 14
Project: openjdk-jdk10   File: JavacFileManager.java   View Source Code Vote up 5 votes
/**
 * Enforces the specification of a "relative" name as used in
 * {@linkplain #getFileForInput(Location,String,String)
 * getFileForInput}.  This method must follow the rules defined in
 * that method, do not make any changes without consulting the
 * specification.
 */
protected static boolean isRelativeUri(URI uri) {
    if (uri.isAbsolute())
        return false;
    String path = uri.normalize().getPath();
    if (path.length() == 0 /* isEmpty() is mustang API */)
        return false;
    if (!path.equals(uri.getPath())) // implicitly checks for embedded . and ..
        return false;
    if (path.startsWith("/") || path.startsWith("./") || path.startsWith("../"))
        return false;
    return true;
}
 
Example 15
Project: whackpad   File: ModuleSourceProviderBase.java   View Source Code Vote up 5 votes
private ModuleSource loadFromPathArray(String moduleId,
        Scriptable paths, Object validator) throws IOException
{
    final long llength = ScriptRuntime.toUint32(
            ScriptableObject.getProperty(paths, "length"));
    // Yeah, I'll ignore entries beyond Integer.MAX_VALUE; so sue me.
    int ilength = llength > Integer.MAX_VALUE ? Integer.MAX_VALUE : 
        (int)llength;

    for(int i = 0; i < ilength; ++i) {
        final String path = ensureTrailingSlash(
                ScriptableObject.getTypedProperty(paths, i, String.class));
        try {
            URI uri =  new URI(path);
            if (!uri.isAbsolute()) {
                uri = new File(path).toURI().resolve("");
            }
            final ModuleSource moduleSource = loadFromUri(
                    uri.resolve(moduleId), uri, validator);
            if(moduleSource != null) {
                return moduleSource;
            }
        }
        catch(URISyntaxException e) {
            throw new MalformedURLException(e.getMessage());
        }
    }
    return null;
}
 
Example 16
Project: incubator-netbeans   File: SecureURLResourceRetriever.java   View Source Code Vote up 5 votes
public boolean accept(String baseAddr, String currentAddr) throws URISyntaxException {
    URI currURI = new URI(currentAddr);
    if( (currURI.isAbsolute()) && (currURI.getScheme().equalsIgnoreCase(URI_SCHEME)))
        return true;
    if(baseAddr != null){
        URI baseURI = new URI(baseAddr);
        if(baseURI.getScheme().equalsIgnoreCase(URI_SCHEME))
            return true;
    }
    return false;
}
 
Example 17
Project: BUbiNG   File: Agent.java   View Source Code Vote up 4 votes
@Override
public BubingJob fromString(final String s) {
	final URI url = BURL.parse(s);
	if (url != null && url.isAbsolute()) return new BubingJob(ByteArrayList.wrap(BURL.toByteArray(url)));
	throw new IllegalArgumentException();
}
 
Example 18
Project: syndesis   File: RelativeUriValidator.java   View Source Code Vote up 4 votes
@Override
public boolean isValid(final URI value, final ConstraintValidatorContext context) {
    return value != null && !value.isAbsolute();
}
 
Example 19
Project: OpenJSharp   File: File.java   View Source Code Vote up 3 votes
/**
 * Creates a new <tt>File</tt> instance by converting the given
 * <tt>file:</tt> URI into an abstract pathname.
 *
 * <p> The exact form of a <tt>file:</tt> URI is system-dependent, hence
 * the transformation performed by this constructor is also
 * system-dependent.
 *
 * <p> For a given abstract pathname <i>f</i> it is guaranteed that
 *
 * <blockquote><tt>
 * new File(</tt><i>&nbsp;f</i><tt>.{@link #toURI() toURI}()).equals(</tt><i>&nbsp;f</i><tt>.{@link #getAbsoluteFile() getAbsoluteFile}())
 * </tt></blockquote>
 *
 * so long as the original abstract pathname, the URI, and the new abstract
 * pathname are all created in (possibly different invocations of) the same
 * Java virtual machine.  This relationship typically does not hold,
 * however, when a <tt>file:</tt> URI that is created in a virtual machine
 * on one operating system is converted into an abstract pathname in a
 * virtual machine on a different operating system.
 *
 * @param  uri
 *         An absolute, hierarchical URI with a scheme equal to
 *         <tt>"file"</tt>, a non-empty path component, and undefined
 *         authority, query, and fragment components
 *
 * @throws  NullPointerException
 *          If <tt>uri</tt> is <tt>null</tt>
 *
 * @throws  IllegalArgumentException
 *          If the preconditions on the parameter do not hold
 *
 * @see #toURI()
 * @see java.net.URI
 * @since 1.4
 */
public File(URI uri) {

    // Check our many preconditions
    if (!uri.isAbsolute())
        throw new IllegalArgumentException("URI is not absolute");
    if (uri.isOpaque())
        throw new IllegalArgumentException("URI is not hierarchical");
    String scheme = uri.getScheme();
    if ((scheme == null) || !scheme.equalsIgnoreCase("file"))
        throw new IllegalArgumentException("URI scheme is not \"file\"");
    if (uri.getAuthority() != null)
        throw new IllegalArgumentException("URI has an authority component");
    if (uri.getFragment() != null)
        throw new IllegalArgumentException("URI has a fragment component");
    if (uri.getQuery() != null)
        throw new IllegalArgumentException("URI has a query component");
    String p = uri.getPath();
    if (p.equals(""))
        throw new IllegalArgumentException("URI path component is empty");

    // Okay, now initialize
    p = fs.fromURIPath(p);
    if (File.separatorChar != '/')
        p = p.replace('/', File.separatorChar);
    this.path = fs.normalize(p);
    this.prefixLength = fs.prefixLength(this.path);
}
 
Example 20
Project: truevfs   File: UriCat.java   View Source Code Vote up 2 votes
/**
 * Copies the contents of the parameter resource to the standard output.
 * <p>
 * The set of archive file extensions detected by this method is determined
 * by the current archive detector
 * {@code TConfig.current().getArchiveDetector()}
 * and the respective file system driver providers on the class path.
 *
 * @param  resource the URI string of the resource to copy.
 *         The URI must be file-based, i.e. the top level file system
 *         scheme must be {@code file}.
 * @throws IOException if accessing the resource results in an I/O error.
 * @throws URISyntaxException if {@code resource} does not
 *         conform to the syntax constraints for {@link URI}s.
 */
static void uriCat(String resource) throws IOException, URISyntaxException {
    URI uri = new URI(resource);
    TFile file = uri.isAbsolute() ? new TFile(uri) : new TFile(resource);
    file.output(System.out);
}