Example usage for java.net URL equals

List of usage examples for java.net URL equals

Introduction

In this page you can find the example usage for java.net URL equals.

Prototype

public boolean equals(Object obj) 

Source Link

Document

Compares this URL for equality with another object.

If the given object is not a URL then this method immediately returns false .

Two URL objects are equal if they have the same protocol, reference equivalent hosts, have the same port number on the host, and the same file and fragment of the file.

Two hosts are considered equivalent if both host names can be resolved into the same IP addresses; else if either host name can't be resolved, the host names must be equal without regard to case; or both host names equal to null.

Since hosts comparison requires name resolution, this operation is a blocking operation.

Usage

From source file:URLEquality.java

public static void main(String args[]) {

    try {// ww  w .  ja v a  2  s. com
        URL sunsite = new URL("http://www.java2s.com");
        URL helios = new URL("http://www.demo2s.com");
        if (sunsite.equals(helios)) {
            System.out.println(sunsite + " is the same as " + helios);
        } else {
            System.out.println(sunsite + " is not the same as " + helios);
        }
    } catch (MalformedURLException e) {
        System.err.println(e);
    }

}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    URL relativeURL, baseURL;
    baseURL = new URL("http://www.yourserver.com/");
    relativeURL = new URL(baseURL, "./a.htm");
    System.out.println(relativeURL.equals(baseURL));

}

From source file:org.osaf.cosmo.dav.caldav.report.MultigetReport.java

private static boolean isDescendentOrEqual(URL collection, URL test) {
    if (collection.equals(test))
        return true;
    return test.getPath().startsWith(collection.getPath());
}

From source file:javarestart.WebClassLoaderRegistry.java

public static WebClassLoader resolveClassLoader(URL url) {
    if (url.getPath().endsWith("/..")) {
        return null;
    }//from w  w  w.  ja  va  2s . c  o m
    WebClassLoader cl = null;
    URL baseURL = normalizeURL(url);
    try {
        URL rootURL = new URL(baseURL, "/");
        while (((cl = associatedClassloaders.get(baseURL)) == null) && !baseURL.equals(rootURL)) {
            baseURL = new URL(baseURL, "..");
        }
    } catch (MalformedURLException e) {
    }

    if (cl == null) {
        try {
            JSONObject desc = Utils.getJSON(new URL(url.getProtocol(), url.getHost(), url.getPort(),
                    url.getPath() + "?getAppDescriptor"));
            if (desc != null) {
                cl = new WebClassLoader(url, desc);
            }
        } catch (Exception e) {
        }
    }
    associatedClassloaders.put(normalizeURL(url), cl);
    if (cl != null) {
        URL clURL = normalizeURL(cl.getBaseURL());
        associatedClassloaders.put(clURL, cl);
        classloaders.put(clURL, cl);
    }
    return cl;
}

From source file:org.mycore.common.xml.MCREntityResolver.java

private static boolean isAbsoluteURL(String url) {
    try {// w  w  w .  ja va2s .c  o m
        URL baseHttp = new URL("http://www.mycore.org");
        URL baseFile = new URL("file:///");
        URL relativeHttp = new URL(baseHttp, url);
        URL relativeFile = new URL(baseFile, url);
        return relativeFile.equals(relativeHttp);
    } catch (MalformedURLException e) {
        return false;
    }
}

From source file:org.apache.axiom.util.stax.dialect.StAXDialectDetector.java

private static Class loadClass(ClassLoader classLoader, URL rootUrl, String name) {
    try {/*from ww w.  ja v  a2s . c om*/
        if (classLoader == null) {
            classLoader = ClassLoader.getSystemClassLoader();
        }
        Class cls = classLoader.loadClass(name);
        // Cross check if the class was loaded from the same location (JAR)
        return rootUrl.equals(getRootUrlForClass(cls)) ? cls : null;
    } catch (ClassNotFoundException ex) {
        return null;
    }
}

From source file:sx.blah.discord.modules.ModuleLoader.java

/**
 * Loads a jar file and automatically adds any modules.
 * To avoid high overhead recursion, specify the attribute "Discord4J-ModuleClass" in your jar manifest.
 * Multiple classes should be separated by a semicolon ";".
 *
 * @param file The jar file to load.//from   ww  w  . j  av  a2  s.  c  om
 */
public static synchronized void loadExternalModules(File file) { // A bit hacky, but oracle be dumb and encapsulates URLClassLoader#addUrl()
    if (file.isFile() && file.getName().endsWith(".jar")) { // Can't be a directory and must be a jar
        try (JarFile jar = new JarFile(file)) {
            Manifest man = jar.getManifest();
            String moduleAttrib = man == null ? null
                    : man.getMainAttributes().getValue("Discord4J-ModuleClass");
            String[] moduleClasses = new String[0];
            if (moduleAttrib != null) {
                moduleClasses = moduleAttrib.split(";");
            }
            // Executes would should be URLCLassLoader.addUrl(file.toURI().toURL());
            URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader();
            URL url = file.toURI().toURL();
            for (URL it : Arrays.asList(loader.getURLs())) { // Ensures duplicate libraries aren't loaded
                if (it.equals(url)) {
                    return;
                }
            }
            Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
            method.setAccessible(true);
            method.invoke(loader, url);
            if (moduleClasses.length == 0) { // If the Module Developer has not specified the Implementing Class, revert to recursive search
                // Scans the jar file for classes which have IModule as a super class
                List<String> classes = new ArrayList<>();
                jar.stream()
                        .filter(jarEntry -> !jarEntry.isDirectory() && jarEntry.getName().endsWith(".class"))
                        .map(path -> path.getName().replace('/', '.').substring(0,
                                path.getName().length() - ".class".length()))
                        .forEach(classes::add);
                for (String clazz : classes) {
                    try {
                        Class classInstance = loadClass(clazz);
                        if (IModule.class.isAssignableFrom(classInstance)
                                && !classInstance.equals(IModule.class)) {
                            addModuleClass(classInstance);
                        }
                    } catch (NoClassDefFoundError ignored) {
                        /* This can happen. Looking recursively looking through the classpath is hackish... */ }
                }
            } else {
                for (String moduleClass : moduleClasses) {
                    Discord4J.LOGGER.info(LogMarkers.MODULES, "Loading Class from Manifest Attribute: {}",
                            moduleClass);
                    Class classInstance = loadClass(moduleClass);
                    if (IModule.class.isAssignableFrom(classInstance))
                        addModuleClass(classInstance);
                }
            }
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | IOException
                | ClassNotFoundException e) {
            Discord4J.LOGGER.error(LogMarkers.MODULES, "Unable to load module " + file.getName() + "!", e);
        }
    }
}

From source file:io.github.lal872k.monotifier.MyBackPack.java

public static MO[] loadMOs(User user, Engine engine) throws IOException {
    System.out.println("Retrieving MO's for user " + user.getID() + " (" + user.getName() + ").");
    // make web client
    final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_45);

    LogFactory.getFactory().setAttribute("org.apache.commons.logging.Log",
            "org.apache.commons.logging.impl.NoOpLog");

    java.util.logging.Logger.getLogger("com.gargoylesoftware.htmlunit").setLevel(Level.OFF);
    java.util.logging.Logger.getLogger("org.apache.commons.httpclient").setLevel(Level.OFF);

    //webClient.setCssEnabled(false);
    // http://stackoverflow.com/questions/3600557/turning-htmlunit-warnings-off

    webClient.setIncorrectnessListener(new IncorrectnessListener() {

        @Override/*ww  w.j av  a 2 s. c  om*/
        public void notify(String arg0, Object arg1) {
            // TODO Auto-generated method stub

        }
    });
    webClient.setCssErrorHandler(new ErrorHandler() {

        @Override
        public void warning(CSSParseException exception) throws CSSException {
            // TODO Auto-generated method stub

        }

        @Override
        public void fatalError(CSSParseException exception) throws CSSException {
            // TODO Auto-generated method stub

        }

        @Override
        public void error(CSSParseException exception) throws CSSException {
            // TODO Auto-generated method stub

        }
    });
    webClient.setJavaScriptErrorListener(new JavaScriptErrorListener() {

        @Override
        public void scriptException(InteractivePage ip, ScriptException se) {
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void timeoutError(InteractivePage ip, long l, long l1) {
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void malformedScriptURL(InteractivePage ip, String string, MalformedURLException murle) {
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void loadScriptError(InteractivePage ip, URL url, Exception excptn) {
            //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    });
    webClient.setHTMLParserListener(new HTMLParserListener() {

        @Override
        public void error(String string, URL url, String string1, int i, int i1, String string2) {
            //
        }

        @Override
        public void warning(String string, URL url, String string1, int i, int i1, String string2) {
            //
        }
    });

    //webClient.setThrowExceptionOnFailingStatusCode(false);
    //webClient.setThrowExceptionOnScriptError(false);

    //http://stackoverflow.com/questions/19551043/process-ajax-request-in-htmlunit/26268815#26268815
    webClient.getOptions().setJavaScriptEnabled(true);
    webClient.getOptions().setThrowExceptionOnScriptError(false);
    webClient.getOptions().setCssEnabled(false);
    webClient.setAjaxController(new NicelyResynchronizingAjaxController());

    // get the page
    HtmlPage page = webClient.getPage(
            "https://peddie.seniormbp.com/SeniorApps/studentParent/attendSummary.faces?selectedMenuId=true");

    // get login form
    final HtmlForm login_form = page.getFormByName("form");

    final HtmlTextInput username = login_form.getInputByName("form:userId");
    final HtmlPasswordInput password = login_form.getInputByName("form:userPassword");

    final HtmlButtonInput login_submit = login_form.getInputByName("form:signIn");

    username.setValueAttribute(user.getMyBackPackUsername());
    password.setValueAttribute(user.getDecryptedMyBackPackPassword());

    URL oldURL = page.getUrl();

    // Now submit the form by clicking the button and get back the new page.
    page = login_submit.click();

    if (oldURL.equals(page.getUrl())) {
        System.err
                .println("Password or username was invalid for " + user.getName() + "(" + user.getID() + ").");
        return new MO[0];
    }

    // click on details

    final HtmlForm switchView_form = page.getFormByName("j_id_jsp_1447653194_2");

    final HtmlSubmitInput switchView_submit = switchView_form
            .getInputByName("j_id_jsp_1447653194_2:j_id_jsp_1447653194_12");

    page = switchView_submit.click();

    // now on right page

    ArrayList<MO> mos = new ArrayList();

    // find all rows
    List<DomElement> odds = (List<DomElement>) page
            .getByXPath("//tr[@class='dataCellOdd' or @class='dataCellEven']");

    String date = "";
    String section = "";
    boolean passedSection = false;

    for (DomElement el : odds) {
        for (DomElement ele : el.getChildElements()) {
            // date is only on with rowspan
            if (ele.hasAttribute("rowspan")) {
                date = ele.getTextContent();
            }
            // section and type contain that attr
            if (ele.getAttribute("class").equals("attendTypeColumnData2")) {
                // section comes first
                if (!passedSection) {
                    section = ele.getTextContent();
                    passedSection = true;
                } else {
                    mos.add(new MO(section, date, ele.getTextContent()));
                    passedSection = false;
                }
            }
        }
    }

    engine.getHistory().addAction(new Action("Accessed MyBackPack", "Accessed the MyBackPack of "
            + user.getName() + " (" + user.getID() + ")(" + user.getEmail() + ") to update the mo count."));

    return mos.toArray(new MO[0]);

}

From source file:org.jactr.eclipse.core.ast.Support.java

/**
 * return true if the node has the same base url as base
 * /*  w w w  .  j a v  a  2 s  .  c o m*/
 * @param node
 * @param base
 * @return
 */
static private boolean isLocal(CommonTree node, URL base) {
    if (base == null)
        return true;
    if (node instanceof DetailedCommonTree) {
        URL source = ((DetailedCommonTree) node).getSource();
        if (source == null)
            return true;
        return base.equals(source);
    }
    return false;
}

From source file:org.apache.openejb.util.classloader.URLClassLoaderFirst.java

public static boolean shouldSkipSlf4j(final ClassLoader loader, final String name) {
    if (name == null || !name.startsWith("org.slf4j.")) {
        return false;
    }//from   ww  w .j a  v a 2 s  .com

    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;
}