Java Code Examples for java.net.URL#equals()

The following examples show how to use java.net.URL#equals() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Test.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
static void serial() throws IOException, MalformedURLException {

        header("Serialization");

        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        ObjectOutputStream oo = new ObjectOutputStream(bo);
        URL u = new URL("http://java.sun.com/jdk/1.4?release#beta");
        oo.writeObject(u);
        oo.close();

        ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
        ObjectInputStream oi = new ObjectInputStream(bi);
        try {
            Object o = oi.readObject();
            u.equals(o);
        } catch (ClassNotFoundException x) {
            x.printStackTrace();
            throw new RuntimeException(x.toString());
        }

    }
 
Example 2
Source File: JavaSourceTestCase.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void removeResources(List<URL> urls) {
    boolean modified = false;
    main: for (URL url : urls) {
        for (PathResourceImplementation resource : resources) {
            for (URL resourceRoot : resource.getRoots()) {
                if (resourceRoot.equals(url)) {
                    resources.remove(resource);
                    modified = true;
                    break main;
                }
            }
        }
    }
    if (modified) {
        propSupport.firePropertyChange(PROP_RESOURCES, null, null);
    }
}
 
Example 3
Source File: DocumentRootTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
public static int test(URL documentBase, URL codeBase) {
    int error = 0;
    MLetContent mc = new MLetContent(
            documentBase,
            new HashMap<String,String>(),
            new ArrayList<String>(),
            new ArrayList<String>());
    System.out.println("\nACTUAL   DOCUMENT BASE = " + mc.getDocumentBase());
    System.out.println("EXPECTED DOCUMENT BASE = " + documentBase);
    if (!documentBase.equals(mc.getDocumentBase())) {
        System.out.println("ERROR: Wrong document base");
        error++;
    };
    System.out.println("ACTUAL   CODEBASE = " + mc.getCodeBase());
    System.out.println("EXPECTED CODEBASE = " + codeBase);
    if (!codeBase.equals(mc.getCodeBase())) {
        System.out.println("ERROR: Wrong code base");
        error++;
    };
    return error;
}
 
Example 4
Source File: Test.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
static void serial() throws IOException, MalformedURLException {

        header("Serialization");

        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        ObjectOutputStream oo = new ObjectOutputStream(bo);
        URL u = new URL("http://java.sun.com/jdk/1.4?release#beta");
        oo.writeObject(u);
        oo.close();

        ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
        ObjectInputStream oi = new ObjectInputStream(bi);
        try {
            Object o = oi.readObject();
            u.equals(o);
        } catch (ClassNotFoundException x) {
            x.printStackTrace();
            throw new RuntimeException(x.toString());
        }

    }
 
Example 5
Source File: J2SEPlatformSourceJavadocAttacher.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private J2SEPlatformImpl findOwner(final URL root) {
    for (JavaPlatform p : JavaPlatformManager.getDefault().getPlatforms(null, new Specification(J2SEPlatformImpl.PLATFORM_J2SE, null))) {
        if (!(p instanceof J2SEPlatformImpl)) {
            //Cannot handle unknown platform
            continue;
        }
        final J2SEPlatformImpl j2sep = (J2SEPlatformImpl) p;
        if (!j2sep.isValid()) {
            continue;
        }
        for (ClassPath.Entry entry : j2sep.getBootstrapLibraries().entries()) {
            if (root.equals(entry.getURL())) {
                return j2sep;
            }
        }
    }
    return null;
}
 
Example 6
Source File: OpenProjectList.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private int getIndex( Project p ) {
    if (p == null || p.getProjectDirectory() == null) {
        return -1;
    }
    URL pURL = p.getProjectDirectory().toURL();
    
    int i = 0;
    
    for (ProjectReference pRef : recentProjects) {
        URL p2URL = pRef.getURL();
        if ( pURL.equals( p2URL ) ) {
            return i;
        } else {
            i++;
        }
    }
    
    return -1;
}
 
Example 7
Source File: URLClassLoaderFirst.java    From tomee with Apache License 2.0 6 votes vote down vote up
public static boolean shouldSkipSlf4j(final ClassLoader loader, final String name) {
    if (name == null || !name.startsWith("org.slf4j.")) {
        return false;
    }

    try { // using getResource here just returns randomly the container one so we need getResources
        final Enumeration<URL> resources = loader.getResources(SLF4J_BINDER_CLASS);
        while (resources.hasMoreElements()) {
            final URL resource = resources.nextElement();
            if (!resource.equals(SLF4J_CONTAINER)) {
                // applicative slf4j
                return false;
            }
        }
    } catch (final Throwable e) {
        // no-op
    }

    return true;
}
 
Example 8
Source File: DocumentRootTest.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
public static int test(URL documentBase, URL codeBase) {
    int error = 0;
    MLetContent mc = new MLetContent(
            documentBase,
            new HashMap<String,String>(),
            new ArrayList<String>(),
            new ArrayList<String>());
    System.out.println("\nACTUAL   DOCUMENT BASE = " + mc.getDocumentBase());
    System.out.println("EXPECTED DOCUMENT BASE = " + documentBase);
    if (!documentBase.equals(mc.getDocumentBase())) {
        System.out.println("ERROR: Wrong document base");
        error++;
    };
    System.out.println("ACTUAL   CODEBASE = " + mc.getCodeBase());
    System.out.println("EXPECTED CODEBASE = " + codeBase);
    if (!codeBase.equals(mc.getCodeBase())) {
        System.out.println("ERROR: Wrong code base");
        error++;
    };
    return error;
}
 
Example 9
Source File: EmbeddedFelixFramework.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/** Wraps the bundle if successful or already installed, wraps TRUE if it's the system entry,
 * wraps null if the bundle is already installed from somewhere else;
 * in all these cases <i>masking</i> an explanatory error if already installed or it's the system entry.
 * <p>
 * Returns an instance wrapping null and <i>throwing</i> an error if the bundle could not be installed.
 */
private static ReferenceWithError<?> installExtensionBundle(BundleContext bundleContext, URL manifestUrl, Map<String, Bundle> installedBundles, String frameworkVersionedId) {
    //ignore http://felix.extensions:9/ system entry
    if("felix.extensions".equals(manifestUrl.getHost()))
        return ReferenceWithError.newInstanceMaskingError(null, new IllegalArgumentException("Skipping install of internal extension bundle from "+manifestUrl));

    try {
        Manifest manifest = readManifest(manifestUrl);
        if (!isValidBundle(manifest))
            return ReferenceWithError.newInstanceMaskingError(null, new IllegalArgumentException("Resource at "+manifestUrl+" is not an OSGi bundle: no valid manifest"));

        String versionedId = OsgiUtils.getVersionedId(manifest);
        URL bundleUrl = OsgiUtils.getContainerUrl(manifestUrl, MANIFEST_PATH);

        Bundle existingBundle = installedBundles.get(versionedId);
        if (existingBundle != null) {
            if (!bundleUrl.equals(existingBundle.getLocation()) &&
                    //the framework bundle is always pre-installed, don't display duplicate info
                    !versionedId.equals(frameworkVersionedId)) {
                return ReferenceWithError.newInstanceMaskingError(null, new IllegalArgumentException("Bundle "+versionedId+" (from manifest " + manifestUrl + ") is already installed, from " + existingBundle.getLocation()));
            }
            return ReferenceWithError.newInstanceMaskingError(existingBundle, new IllegalArgumentException("Bundle "+versionedId+" from manifest " + manifestUrl + " is already installed"));
        }

        byte[] jar = buildExtensionBundle(manifest);
        LOG.debug("Installing boot bundle " + bundleUrl);
        //mark the bundle as extension so we can detect it later using the "system:" protocol
        //(since we cannot access BundleImpl.isExtension)
        Bundle newBundle = bundleContext.installBundle(EXTENSION_PROTOCOL + ":" + bundleUrl.toString(), new ByteArrayInputStream(jar));
        installedBundles.put(versionedId, newBundle);
        return ReferenceWithError.newInstanceWithoutError(newBundle);
    } catch (Exception e) {
        Exceptions.propagateIfFatal(e);
        return ReferenceWithError.newInstanceThrowingError(null,
            new IllegalStateException("Problem installing extension bundle " + manifestUrl + ": "+e, e));
    }
}
 
Example 10
Source File: PatchAnalyzer.java    From steady with Apache License 2.0 5 votes vote down vote up
/**
 * Switches to a new VCS. Upon success, previous analysis results are lost.
 *
 * @param _url a {@link java.lang.String} object.
 * @throws java.net.MalformedURLException if the given URL is invalid (previous results are kept)
 * @throws com.sap.psr.vulas.vcs.NoRepoClientException if no VCS client can be created for the given URL (previous results are kept)
 */
public void setRepoURL(String _url) throws MalformedURLException, NoRepoClientException {
	final URL u = new URL(_url);
	if(!u.equals(this.url)) {
		final IVCSClient c = PatchAnalyzer.createVCSClient(u);
		// Previous state will be dropped (only if above instantiation worked)
		this.vcs = c;
		this.url = u;
		this.changes.clear();
		this.sourceConstructs = null;
		this.sourceRev = null;
	}
}
 
Example 11
Source File: RepositoryUpdaterTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public URL getIndexURL(URL root) {
    URL index = null;
    lck.lock();
    try {
        if (root.equals(expectedURL)) {
            index = indexURL;
            expectedURL = null;
            cnd.signal();
        }
    } finally {
        lck.unlock();
    }
    return index;
}
 
Example 12
Source File: NbinstURLMapperTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testURLNoInetAccess() throws MalformedURLException, IOException {
    URL url1 = new URL ("nbinst://test-module/modules/test.txt");   // NOI18N
    URL url2 = new URL ("nbinst://foo-module/modules/test.txt");    // NOI18N
    SecurityManager defaultManager = System.getSecurityManager();
    
    System.setSecurityManager(new InetSecurityManager());
    try {
        // make sure we do not try to resolve host name
        url1.hashCode();
        url1.equals(url2);
        testURLConnection();
    } finally {
        System.setSecurityManager(defaultManager);
    }
}
 
Example 13
Source File: PathRegistryTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void removeResource (FileObject fo) throws IOException {
    URL url = fo.getURL();
    for (Iterator<PathResourceImplementation> it = res.iterator(); it.hasNext(); ) {
        PathResourceImplementation r = it.next();
        if (url.equals(r.getRoots()[0])) {
            it.remove();
            this.support.firePropertyChange(PROP_RESOURCES,null,null);
        }
    }
}
 
Example 14
Source File: URLTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testHashCodeAndEqualsDoesNotPerformNetworkIo() throws Exception {
    final BlockGuard.Policy oldPolicy = BlockGuard.getThreadPolicy();
    BlockGuard.setThreadPolicy(new BlockGuard.Policy() {
        @Override
        public void onWriteToDisk() {
            fail("Blockguard.Policy.onWriteToDisk");
        }

        @Override
        public void onReadFromDisk() {
            fail("Blockguard.Policy.onReadFromDisk");
        }

        @Override
        public void onNetwork() {
            fail("Blockguard.Policy.onNetwork");
        }

        @Override
        public int getPolicyMask() {
            return 0;
        }
    });

    try {
        URL url = new URL("http://www.google.com/");
        URL url2 = new URL("http://www.nest.com/");

        url.equals(url2);
        url2.hashCode();
    } finally {
        BlockGuard.setThreadPolicy(oldPolicy);
    }
}
 
Example 15
Source File: MultiResolutionImageTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
static void testImageNameTo2xParsing() throws Exception {

        for (String[] testNames : TEST_FILE_NAMES) {
            String testName = testNames[0];
            String goldenName = testNames[1];
            String resultName = getTestScaledImageName(testName);

            if (!isValidPath(testName) && resultName == null) {
                continue;
            }

            if (goldenName.equals(resultName)) {
                continue;
            }

            throw new RuntimeException("Test name " + testName
                + ", result name: " + resultName);
        }

        for (URL[] testURLs : TEST_URLS) {
            URL testURL = testURLs[0];
            URL goldenURL = testURLs[1];
            URL resultURL = getTestScaledImageURL(testURL);

            if (!isValidPath(testURL.getPath()) && resultURL == null) {
                continue;
            }

            if (goldenURL.equals(resultURL)) {
                continue;
            }

            throw new RuntimeException("Test url: " + testURL
                + ", result url: " + resultURL);
        }

    }
 
Example 16
Source File: MultiResolutionImageTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
static void testImageNameTo2xParsing() throws Exception {

        for (String[] testNames : TEST_FILE_NAMES) {
            String testName = testNames[0];
            String goldenName = testNames[1];
            String resultName = getTestScaledImageName(testName);

            if (!isValidPath(testName) && resultName == null) {
                continue;
            }

            if (goldenName.equals(resultName)) {
                continue;
            }

            throw new RuntimeException("Test name " + testName
                + ", result name: " + resultName);
        }

        for (URL[] testURLs : TEST_URLS) {
            URL testURL = testURLs[0];
            URL goldenURL = testURLs[1];
            URL resultURL = getTestScaledImageURL(testURL);

            if (!isValidPath(testURL.getPath()) && resultURL == null) {
                continue;
            }

            if (goldenURL.equals(resultURL)) {
                continue;
            }

            throw new RuntimeException("Test url: " + testURL
                + ", result url: " + resultURL);
        }

    }
 
Example 17
Source File: HelpManager.java    From ghidra with Apache License 2.0 5 votes vote down vote up
private void displayHelpUrl(Object help, URL helpUrl) {
	if (helpUrl == null) {
		Msg.debug(this, "Unable to find help for object: " + help);
	}

	helpUrl = validateUrl(helpUrl);

	if (hasBeenDisplayed && helpUrl.equals(mainHB.getCurrentURL())) {
		reloadPage(helpUrl);
		return;
	}

	mainHB.setCurrentURL(validateUrl(helpUrl));
}
 
Example 18
Source File: BuildArtifactMapperImpl.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private Boolean performSync(@NonNull final Context ctx) throws IOException {
    final URL sourceRoot = ctx.getSourceRoot();
    final URL targetFolderURL = ctx.getTargetURL();
    final boolean copyResources = ctx.isCopyResources();
    final boolean keepResourceUpToDate = ctx.isKeepResourcesUpToDate();
    final Object context = ctx.getOwner();

    if (targetFolderURL == null) {
        return null;
    }

    final File targetFolder = FileUtil.archiveOrDirForURL(targetFolderURL);

    if (targetFolder == null) {
        return null;
    }

    try {
        SourceUtils.waitScanFinished();
    } catch (InterruptedException e) {
        //Not Important
        LOG.log(Level.FINE, null, e);
        return null;
    }

    if (JavaIndex.ensureAttributeValue(sourceRoot, DIRTY_ROOT, null)) {
        IndexingManager.getDefault().refreshIndexAndWait(sourceRoot, null);
    }

    if (JavaIndex.getAttribute(sourceRoot, DIRTY_ROOT, null) != null) {
        return false;
    }

    FileObject[][] sources = new FileObject[1][];

    if (!protectAgainstErrors(targetFolderURL, sources, context)) {
        return false;
    }
                
    File tagFile = new File(targetFolder, TAG_FILE_NAME);
    File tagUpdateResourcesFile = new File(targetFolder, TAG_UPDATE_RESOURCES);
    final boolean forceResourceCopy = copyResources && keepResourceUpToDate && !tagUpdateResourcesFile.exists();
    final boolean cosActive = tagFile.exists();
    if (cosActive && !forceResourceCopy) {
        return true;
    }

    if (!cosActive) {
        delete(targetFolder, false/*#161085: cleanCompletely*/);
    }

    if (!targetFolder.exists() && !targetFolder.mkdirs()) {
        throw new IOException("Cannot create destination folder: " + targetFolder.getAbsolutePath());
    }

    sources(targetFolderURL, sources);

    for (int i = sources[0].length - 1; i>=0; i--) {
        final FileObject sr = sources[0][i];
        if (!cosActive) {
            URL srURL = sr.toURL();
            File index = JavaIndex.getClassFolder(srURL, true);

            if (index == null) {
                //#181992: (not nice) ignore the annotation processing target directory:
                if (srURL.equals(AnnotationProcessingQuery.getAnnotationProcessingOptions(sr).sourceOutputDirectory())) {
                    continue;
                }

                return null;
            }

            copyRecursively(index, targetFolder);
        }

        if (copyResources) {
            Set<String> javaMimeTypes = COSSynchronizingIndexer.gatherJavaMimeTypes();
            String[]    javaMimeTypesArr = javaMimeTypes.toArray(new String[0]);

            copyRecursively(sr, targetFolder, javaMimeTypes, javaMimeTypesArr);
        }
    }

    if (!cosActive) {
        new FileOutputStream(tagFile).close();
    }

    if (keepResourceUpToDate)
        new FileOutputStream(tagUpdateResourcesFile).close();

    return true;
}
 
Example 19
Source File: IOUtils.java    From ccu-historian with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Creates a relative url by stripping the common parts of the the url.
 *
 * @param url the to be stripped url
 * @param baseURL the base url, to which the <code>url</code> is relative 
 *                to.
 * @return the relative url, or the url unchanged, if there is no relation
 * beween both URLs.
 */
public String createRelativeURL(final URL url, final URL baseURL) {
    if (url == null) {
        throw new NullPointerException("content url must not be null.");
    }
    if (baseURL == null) {
        throw new NullPointerException("baseURL must not be null.");
    }
    if (isFileStyleProtocol(url) && isSameService(url, baseURL)) {

        // If the URL contains a query, ignore that URL; do not
        // attemp to modify it...
        final List urlName = parseName(getPath(url));
        final List baseName = parseName(getPath(baseURL));
        final String query = getQuery(url);

        if (!isPath(baseURL)) {
            baseName.remove(baseName.size() - 1);
        }

        // if both urls are identical, then return the plain file name... 
        if (url.equals(baseURL)) {
            return (String) urlName.get(urlName.size() - 1);
        }

        int commonIndex = startsWithUntil(urlName, baseName);
        if (commonIndex == 0) {
            return url.toExternalForm();
        }

        if (commonIndex == urlName.size()) {
            // correct the base index if there is some weird mapping 
            // detected,
            // fi. the file url is fully included in the base url:
            //
            // base: /file/test/funnybase
            // file: /file/test
            //
            // this could be a valid configuration whereever virtual 
            // mappings are allowed.
            commonIndex -= 1;
        }

        final ArrayList retval = new ArrayList();
        if (baseName.size() >= urlName.size()) {
            final int levels = baseName.size() - commonIndex;
            for (int i = 0; i < levels; i++) {
                retval.add("..");
            }
        }

        retval.addAll(urlName.subList(commonIndex, urlName.size()));
        return formatName(retval, query);
    }
    return url.toExternalForm();
}
 
Example 20
Source File: Package.java    From jdk-1.7-annotated with Apache License 2.0 2 votes vote down vote up
/**
 * Returns true if this package is sealed with respect to the specified
 * code source url.
 *
 * @param url the code source url
 * @return true if this package is sealed with respect to url
 */
public boolean isSealed(URL url) {
    return url.equals(sealBase);
}