Example usage for java.lang ClassLoader getResource

List of usage examples for java.lang ClassLoader getResource

Introduction

In this page you can find the example usage for java.lang ClassLoader getResource.

Prototype

public URL getResource(String name) 

Source Link

Document

Finds the resource with the given name.

Usage

From source file:com.eryansky.common.utils.io.FileUtil.java

@SuppressWarnings("rawtypes")
public static String getAppPath(Class cls) {
    // ??//from w  w w .  j  av a2s . c om
    if (cls == null)
        throw new java.lang.IllegalArgumentException("???");
    ClassLoader loader = cls.getClassLoader();
    // ????
    String clsName = cls.getName() + ".class";
    // ?
    Package pack = cls.getPackage();
    String path = "";
    // ?????
    if (pack != null) {
        String packName = pack.getName();
        // ??JavaJDK
        if (packName.startsWith("java.") || packName.startsWith("javax."))
            throw new java.lang.IllegalArgumentException("????");
        // ??????
        clsName = clsName.substring(packName.length() + 1);
        // ?????????
        if (packName.indexOf(".") < 0)
            path = packName + "/";
        else {// ???????
            int start = 0, end = 0;
            end = packName.indexOf(".");
            while (end != -1) {
                path = path + packName.substring(start, end) + "/";
                start = end + 1;
                end = packName.indexOf(".", start);
            }
            path = path + packName.substring(start) + "/";
        }
    }
    // ClassLoadergetResource????
    java.net.URL url = loader.getResource(path + clsName);
    // URL??
    String realPath = url.getPath();
    // ?????"file:"
    int pos = realPath.indexOf("file:");
    if (pos > -1)
        realPath = realPath.substring(pos + 5);
    // ????
    pos = realPath.indexOf(path + clsName);
    realPath = realPath.substring(0, pos - 1);
    // JARJAR??
    if (realPath.endsWith("!"))
        realPath = realPath.substring(0, realPath.lastIndexOf("/"));
    /*------------------------------------------------------------ 
     ClassLoadergetResourceutf-8?? 
      ??? 
      URLDecoderdecode? 
      ? 
    -------------------------------------------------------------*/
    try {
        realPath = java.net.URLDecoder.decode(realPath, "utf-8");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    System.out.println("realPath----->" + realPath);
    return realPath;
}

From source file:com.eryansky.common.utils.io.FileUtils.java

@SuppressWarnings("rawtypes")
public static String getAppPath(Class cls) {
    // ??/*from ww w.j av  a  2  s  .  c  om*/
    if (cls == null)
        throw new IllegalArgumentException("???");
    ClassLoader loader = cls.getClassLoader();
    // ????
    String clsName = cls.getName() + ".class";
    // ?
    Package pack = cls.getPackage();
    String path = "";
    // ?????
    if (pack != null) {
        String packName = pack.getName();
        // ??JavaJDK
        if (packName.startsWith("java.") || packName.startsWith("javax."))
            throw new IllegalArgumentException("????");
        // ??????
        clsName = clsName.substring(packName.length() + 1);
        // ?????????
        if (packName.indexOf(".") < 0)
            path = packName + "/";
        else {// ???????
            int start = 0, end = 0;
            end = packName.indexOf(".");
            while (end != -1) {
                path = path + packName.substring(start, end) + "/";
                start = end + 1;
                end = packName.indexOf(".", start);
            }
            path = path + packName.substring(start) + "/";
        }
    }
    // ClassLoadergetResource????
    java.net.URL url = loader.getResource(path + clsName);
    // URL??
    String realPath = url.getPath();
    // ?????"file:"
    int pos = realPath.indexOf("file:");
    if (pos > -1)
        realPath = realPath.substring(pos + 5);
    // ????
    pos = realPath.indexOf(path + clsName);
    realPath = realPath.substring(0, pos - 1);
    // JARJAR??
    if (realPath.endsWith("!"))
        realPath = realPath.substring(0, realPath.lastIndexOf("/"));
    /*------------------------------------------------------------ 
     ClassLoadergetResourceutf-8?? 
      ??? 
      URLDecoderdecode? 
      ? 
    -------------------------------------------------------------*/
    try {
        realPath = java.net.URLDecoder.decode(realPath, "utf-8");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    System.out.println("realPath----->" + realPath);
    return realPath;
}

From source file:com.xpn.xwiki.internal.template.InternalTemplateManager.java

private Template getClassloaderTemplate(ClassLoader classloader, String suffixPath, String templateName) {
    String templatePath = suffixPath + templateName;

    URL url = classloader.getResource(templatePath);

    return url != null ? new DefaultTemplate(new ClassloaderResource(url, templateName)) : null;
}

From source file:com.joyent.manta.client.crypto.AbstractMantaEncryptedObjectInputStreamTest.java

AbstractMantaEncryptedObjectInputStreamTest() {
    final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    this.testURL = classLoader.getResource("test-data/chaucer.txt");

    try {/*from   ww  w.jav  a2s  . c  om*/
        testFile = Paths.get(testURL.toURI());
    } catch (URISyntaxException e) {
        throw new AssertionError(e);
    }

    this.plaintextSize = (int) testFile.toFile().length();

    try (InputStream in = this.testURL.openStream()) {
        this.plaintextBytes = IOUtils.readFully(in, plaintextSize);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:fxts.stations.ui.help.ContentTree.java

/**
 * Parses xml file to load contents./*from w  w  w  .  j  av a2 s.c  om*/
 *
 * @param aUrl url to xml-file
 *
 * @return the root of contents tree
 */
private DefaultMutableTreeNode parseXML(String aUrl) {
    ClassLoader classLoader;
    InputStream istream;
    URL url;
    XmlParser parser;

    //clears vector of contents
    mContents.clear();
    //clears hashtables
    mId2UrlMap.clear();
    mUrl2IdMap.clear();
    parser = new XmlParser();
    classLoader = getClass().getClassLoader();
    url = classLoader.getResource(aUrl);
    if (url == null) {
        mLogger.error("Xml-file by url = \"" + aUrl + "\" not found!");
        return null;
    }
    try {
        istream = url.openStream();
        parser.parse(new InputStreamReader(istream));
        mHelpPrefix = parser.getNodeUrlPrefix();
    } catch (Exception e) {
        mLogger.error("Not parsed xml-file with contents by url = " + aUrl);
        e.printStackTrace();
        return null;
    }
    return parser.getRootNode();
}

From source file:net.jetrix.config.ServerConfig.java

/**
 * Locate the specified resource by searching in the classpath and in
 * the current directory./*from   www. j  a  v  a  2s. co m*/
 *
 * @param name the name of the resource
 * @return the URL of the resource, or null if it cannot be found
 * @since 0.2
 */
private URL findResource(String name) throws MalformedURLException {
    ClassLoader loader = ServerConfig.class.getClassLoader();
    URL url = loader.getResource(name);

    if (url == null) {
        File file = new File(name);
        url = file.toURI().toURL();
    }

    return url;
}

From source file:io.siddhi.extension.io.file.FileSourceLineModeTestCase.java

@BeforeClass
public void init() {
    ClassLoader classLoader = FileSourceLineModeTestCase.class.getClassLoader();
    String rootPath = classLoader.getResource("files").getFile();
    sourceRoot = new File(rootPath + "/repo");
    dirUri = rootPath + "/new";
    newRoot = new File(dirUri);
    moveAfterProcessDir = rootPath + "/moved_files";
}

From source file:com.aurel.track.dbase.InitDatabase.java

/**
 * This method loads form templates from resources/FormTemplates
 * into the database./*w  ww.j  a va  2s.c o  m*/
 * @throws ServletException
 */
public static void loadFormTemplates() {

    List<String> templates = new ArrayList<String>(5);

    templates.add("DefaultForms.xml");

    List<ImportResult> importResultList;
    ImportResult importResult;
    int code;
    for (String template : templates) {
        try {
            LOGGER.info("Synchronizing form template " + template);
            URL propURL = ApplicationBean.getInstance().getServletContext()
                    .getResource(initDataDir + "/Forms/" + template);
            if (propURL == null) {
                ClassLoader cl = InitDatabase.class.getClassLoader();
                propURL = cl.getResource(initDataDir + "/Forms/" + template);
            }
            InputStream in = propURL.openStream();
            EntityImporter entityImporter = new EntityImporter();
            ImportContext importContext = new ImportContext();
            importContext.setEntityType("TScreenBean");
            importContext.setOverrideExisting(true);
            importContext.setClearChildren(true);
            importContext.setOverrideOnlyNotModifiedByUser(true);

            importResultList = entityImporter.importFile(in, importContext);

            in.close();
            if (importResultList != null && !importResultList.isEmpty()) {
                importResult = importResultList.get(0);
                code = importResult.getCode();
                if (importResult.isError()) {
                    LOGGER.warn("Error importing template:" + template + ":" + importResult.getErrorMessage()
                            + ". Error code=" + importResult.getCode());
                } else {
                    switch (code) {
                    case ImportResult.SUCCESS_NEW_ENTITY: {
                        LOGGER.info("Form template " + template + " added.");
                        break;
                    }
                    case ImportResult.SUCCESS_OVERRIDE: {
                        LOGGER.info("Form template " + template + " overridden.");
                        break;
                    }
                    case ImportResult.SUCCESS_TAKE_EXISTING: {
                        LOGGER.info(
                                "Form template " + template + " not updated. Take existing version from DB");
                        break;
                    }
                    }
                }
            } else {
                LOGGER.warn("No template found in file: " + template);
            }
        } catch (Exception e) {
            LOGGER.error("Can't read form template " + template + ": " + e.getMessage());
            LOGGER.debug(STACKTRACE, e);
        }
    } // We have loaded the forms
    //TODO The screen to action assignments should be moved out of the SQL as well
    insertPostLoadData(postloadSql);
}

From source file:com.aurel.track.dbase.InitDatabase.java

private static void addResourceToDatabase(Locale loc, String locCode, Boolean useProjects) {
    String pfix = "_" + locCode;
    String lang = loc.getDisplayName();
    if (locCode == null || "".equals(locCode.trim())) {
        pfix = "";
        lang = "Standard";
    }/*  w w w. java  2 s  .  c o  m*/
    try {
        LOGGER.info("Synchronizing resources for " + lang);
        URL propURL = ApplicationBean.getInstance().getServletContext().getResource(
                "/WEB-INF/classes/resources/UserInterface/ApplicationResources" + pfix + propertiesStr);
        InputStream in = propURL.openStream();
        LocalizeBL.saveResources(in, locCode, false, LocalizeBL.RESOURCE_CATEGORIES.UI_TEXT, false);
    } catch (Exception e) {
        LOGGER.warn("Can't read ApplicationResources.properties from context for " + lang);
        LOGGER.debug(e);
        try {
            LOGGER.info("Trying to use class loader to synchronize resources for " + lang);
            ClassLoader cl = InitDatabase.class.getClassLoader();
            URL propURL = cl.getResource("resources/UserInterface/ApplicationResources" + pfix + propertiesStr);
            InputStream in = propURL.openStream();
            LocalizeBL.saveResources(in, locCode, false, LocalizeBL.RESOURCE_CATEGORIES.UI_TEXT, false);
        } catch (Exception ee) {
            LOGGER.error("No chance to get ApplicationResources.properties for " + lang);
            LOGGER.debug(STACKTRACE, ee);
        }
    }
    try {
        URL propURL = ApplicationBean.getInstance().getServletContext()
                .getResource("/WEB-INF/classes/resources/UserInterface/BoxResources" + pfix + propertiesStr);
        InputStream in = propURL.openStream();
        LocalizeBL.saveResources(in, locCode, false, LocalizeBL.RESOURCE_CATEGORIES.DB_ENTITY, true);
    } catch (Exception e) {
        LOGGER.warn("Can't read BoxResources.properties from context for " + lang);
        try {
            LOGGER.info("Trying to use class loader to synchronize resources for " + lang, e);
            ClassLoader cl = InitDatabase.class.getClassLoader();
            URL propURL = cl.getResource("resources/UserInterface/BoxResources" + pfix + propertiesStr);
            InputStream in = propURL.openStream();
            LocalizeBL.saveResources(in, locCode, false, LocalizeBL.RESOURCE_CATEGORIES.DB_ENTITY, true);
        } catch (Exception ee) {
            LOGGER.error("No chance to read BoxResources.properties for " + lang);
            LOGGER.debug(STACKTRACE, ee);
        }
    }
    // Now overwrite the "spaces" with "projects" if this is an upgraded installation
    if (useProjects) {
        try {
            URL propURL = ApplicationBean.getInstance().getServletContext().getResource(
                    "/WEB-INF/classes/resources/UserInterfaceProj/ApplicationResources" + pfix + propertiesStr);
            InputStream in = propURL.openStream();
            LocalizeBL.saveResources(in, locCode, false, LocalizeBL.RESOURCE_CATEGORIES.UI_TEXT, false);
        } catch (Exception e) {
            LOGGER.warn("Can't read UserInterfaceProj/ApplicationResources.properties for " + lang);
            try {
                ClassLoader cl = InitDatabase.class.getClassLoader();
                URL propURL = cl.getResource("/WEB-INF/classes/resources/UserInterfaceProj/ApplicationResources"
                        + pfix + propertiesStr);
                InputStream in = propURL.openStream();
                LocalizeBL.saveResources(in, locCode, false, LocalizeBL.RESOURCE_CATEGORIES.UI_TEXT, false);
            } catch (Exception ee) {
                LOGGER.error("Can't read UserInterfaceProj/ApplicationResources.properties for " + lang);
                LOGGER.debug(STACKTRACE, ee);
            }
        }
    }
}

From source file:com.aurel.track.dbase.InitDatabase.java

/**
 * This method loads mail templates from resources/MailTemplates
 * into the database.//from   w  w  w  . j av a2  s. co  m
 * @throws ServletException
 */
private static void loadMailTemplates() {
    List<LabelValueBean> templates = new ArrayList<LabelValueBean>(7);
    templates.add(
            new LabelValueBean("ItemCreated.xml", Integer.toString(IEventSubscriber.EVENT_POST_ISSUE_CREATE)));
    templates.add(new LabelValueBean("ItemCreatedByEmail.xml",
            Integer.toString(IEventSubscriber.EVENT_POST_ISSUE_CREATE_BY_EMAIL)));
    templates.add(
            new LabelValueBean("ItemChanged.xml", Integer.toString(IEventSubscriber.EVENT_POST_ISSUE_UPDATE)));
    templates.add(new LabelValueBean("BudgetChanged.xml",
            Integer.toString(IEventSubscriber.EVENT_POST_ISSUE_UPDATEPLANNEDVALUE)));
    templates.add(
            new LabelValueBean("Welcome.xml", Integer.toString(IEventSubscriber.EVENT_POST_USER_REGISTERED)));
    templates.add(new LabelValueBean("WelcomeSelf.xml",
            Integer.toString(IEventSubscriber.EVENT_POST_USER_SELF_REGISTERED)));
    templates.add(new LabelValueBean("ForgotPassword.xml",
            Integer.toString(IEventSubscriber.EVENT_POST_USER_FORGOTPASSWORD)));
    templates.add(
            new LabelValueBean("Reminder.xml", Integer.toString(IEventSubscriber.EVENT_POST_USER_REMINDER)));
    templates.add(new LabelValueBean("ClientCreatedByEmail.xml",
            Integer.toString(IEventSubscriber.EVENT_POST_USER_CREATED_BY_EMAIL)));

    List<ImportResult> importResultList;
    ImportResult importResult;
    int code;
    for (LabelValueBean template : templates) {
        try {
            LOGGER.info("Synchronizing mail template " + template.getLabel());
            URL propURL = ApplicationBean.getInstance().getServletContext()
                    .getResource("/WEB-INF/classes/resources/MailTemplates/" + template.getLabel());
            if (propURL == null) {
                ClassLoader cl = InitDatabase.class.getClassLoader();
                propURL = cl.getResource("resources/MailTemplates/" + template.getLabel());
            }
            InputStream in = propURL.openStream();
            ImportContext importContext = new ImportContext();
            importContext.setOverrideExisting(true);
            importContext.setOverrideOnlyNotModifiedByUser(true);
            importContext.setClearChildren(false);
            importResultList = MailTemplateBL.importFile(in, importContext);
            in.close();
            if (importResultList != null && !importResultList.isEmpty()) {
                importResult = importResultList.get(0);
                code = importResult.getCode();
                if (importResult.isError()) {
                    LOGGER.warn("Error importing template:" + template.getLabel() + ":"
                            + importResult.getErrorMessage() + ". Error code=" + importResult.getCode());
                } else {
                    switch (code) {
                    case ImportResult.SUCCESS_NEW_ENTITY: {
                        createMailTemplateConfigEntry(new Integer(template.getValue()),
                                importResult.getNewObjectID());
                        LOGGER.info("Mail template " + template.getLabel() + " added.");
                        break;
                    }
                    case ImportResult.SUCCESS_OVERRIDE: {
                        LOGGER.info("Mail template " + template.getLabel() + " overridden.");
                        break;
                    }
                    case ImportResult.SUCCESS_TAKE_EXISTING: {
                        LOGGER.info("Mail template " + template.getLabel()
                                + " not updated. Take existing version from DB");
                        break;
                    }
                    }
                }
            } else {
                LOGGER.warn("No template found in file: " + template.getLabel());
            }
        } catch (Exception e) {
            LOGGER.error("Can't read mail template " + template.getLabel() + ": " + e.getMessage());
            LOGGER.debug(STACKTRACE, e);
        }
    }
}