Example usage for java.lang Class getResource

List of usage examples for java.lang Class getResource

Introduction

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

Prototype

@CallerSensitive
public URL getResource(String name) 

Source Link

Document

Finds a resource with a given name.

Usage

From source file:com.medallia.spider.api.StRenderer.java

/** @return the path to the .st file of the given name, relative to the package of the given class */
protected String findPathForTemplate(Class<?> c, String name) {
    name = getPageRelativePath() + name;
    String path = name + ".st";
    while (c != null) {
        if (c.getResource(path) != null)
            return c.getPackage().getName().replace('.', '/') + "/" + name;
        c = c.getSuperclass();//from  w  w w  .ja v  a 2  s .co  m
    }
    throw new RuntimeException("Cannot find template " + name);
}

From source file:com.cloud.agent.AgentShell.java

@Override
public void upgradeAgent(final String url) {
    s_logger.info("Updating agent with binary from " + url);
    synchronized (this) {
        final Class<?> c = this.getClass();
        String path = c.getResource(c.getSimpleName() + ".class").toExternalForm();
        final int begin = path.indexOf(File.separator);
        int end = path.lastIndexOf("!");
        end = path.lastIndexOf(File.separator, end);
        path = path.substring(begin, end);

        s_logger.debug("Current binaries reside at " + path);

        File file = null;/*from  w  ww.  j a  v  a2 s  . c o  m*/
        try {
            file = File.createTempFile("agent-", "-" + Long.toString(new Date().getTime()));
            wget(url, file);
        } catch (final IOException e) {
            s_logger.warn("Exception while downloading agent update package, ", e);
            throw new CloudRuntimeException("Unable to update from " + url + ", exception:" + e.getMessage(),
                    e);
        }

        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Unzipping " + file.getAbsolutePath() + " to " + path);
        }

        final Script unzip = new Script("unzip", 120000, s_logger);
        unzip.add("-o", "-q"); // overwrite and quiet
        unzip.add(file.getAbsolutePath());
        unzip.add("-d", path);

        final String result = unzip.execute();
        if (result != null) {
            throw new CloudRuntimeException("Unable to unzip the retrieved file: " + result);
        }

        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Closing the connection to the management server");
        }
    }

    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Exiting to start the new agent.");
    }
    System.exit(ExitStatus.Upgrade.value());
}

From source file:edu.cornell.med.icb.goby.modes.AbstractCommandLineMode.java

/**
 * Load JSAP XML configuration for the current class. With potential
 * modifications to help / defaults stored in the helpValues map.
 *
 * @param helpValues a map of values to replace in the jsap help with other values
 * @return the configured JSAP object//from   www.  jav  a  2  s  .  c  om
 * @throws IOException   error reading or configuring
 * @throws JSAPException error reading or configuring
 */
@SuppressWarnings("unchecked")
public JSAP loadJsapFromResource(final Map<String, String> helpValues) throws IOException, JSAPException {
    final Class thisClass = this.getClass();
    final String className = ClassUtils.getShortCanonicalName(thisClass);
    JSAP jsap;
    try {
        jsap = new JSAP(thisClass.getResource(className + ".jsap"));
        reformatHelp(jsap);

    } catch (NullPointerException e) { // NOPMD
        // No JSAP for "this", no additional args for the specific driver
        jsap = new JSAP();
    }

    // add options from driver to mode specific JSAP:
    final JSAP jsapSource = new JSAP(GenericToolsDriver.class
            .getResource(ClassUtils.getShortCanonicalName(GenericToolsDriver.class) + ".jsap"));
    final Iterator<String> idsIt = jsapSource.getIDMap().idIterator();
    while (idsIt.hasNext()) {
        final String id = idsIt.next();
        // remove parameters if they already exist in the destination.
        // This makes sure we use the source parameters, such as mode, help,
        // which contain variables to be replaced.
        if (jsap.getByID(id) != null) {
            jsap.unregisterParameter(jsap.getByID(id));
        }
        jsap.registerParameter(jsapSource.getByID(id));

    }
    if (helpValues == null) {
        return jsap;
    }
    final IDMap idMap = jsap.getIDMap();
    final Iterator<String> idIterator = idMap.idIterator();

    while (idIterator.hasNext()) {
        final String id = idIterator.next();
        final Parameter param = jsap.getByID(id);
        final String help = param.getHelp();
        final String[] defaults = param.getDefault();
        for (final Map.Entry<String, String> entry : helpValues.entrySet()) {
            // replace values in help
            if (help.contains(entry.getKey())) {
                param.setHelp(StringUtils.replace(help, entry.getKey(), entry.getValue()));
            }
            // replace values in defaults
            if (defaults != null) {
                for (int i = 0; i < defaults.length; i++) {
                    if (defaults[i].contains(entry.getKey())) {
                        defaults[i] = StringUtils.replace(defaults[i], entry.getKey(), entry.getValue());
                    }
                }
            }

        }
    }

    return jsap;
}

From source file:at.gv.egovernment.moa.id.configuration.config.ConfigurationProvider.java

private String parseVersionFromManifest() {

    try {//from w w  w.j  ava 2s .  co  m
        Class clazz = ConfigurationProvider.class;
        String className = clazz.getSimpleName() + ".class";
        String classPath = clazz.getResource(className).toString();

        if (classPath.startsWith("jar")) {
            log.info("MOA-ID-Configuration Version can NOT parsed from Manifest. Set blank Version");
            return Constants.DEFAULT_VERSION;

        }

        String manifestPath = classPath.substring(0,
                classPath.lastIndexOf("WEB-INF/classes/") + "WEB-INF/classes/".length())
                + "../../META-INF/MANIFEST.MF";

        Manifest manifest = new Manifest(new URL(manifestPath).openStream());
        ;

        Attributes attributes = manifest.getMainAttributes();
        String version = attributes.getValue("version");

        if (MiscUtil.isNotEmpty(version))
            return version;

        else {
            log.info("MOA-ID-Configuration Version not found in Manifest. Set blank Version");
            return Constants.DEFAULT_VERSION;

        }

    } catch (Throwable e) {
        log.info("MOA-ID Version can NOT parsed from Manifest. Set blank Version");

        return Constants.DEFAULT_VERSION;
    }

}

From source file:net.sf.jabref.gui.help.HelpContent.java

public void setPage(String filename, Class<?> resourceOwner) {

    // Check for anchor
    int indexOf = filename.indexOf('#');
    String file;/*from  w w w.j  a  v a 2  s  . c  o  m*/
    String anchorName = null;

    if (indexOf != -1) {
        file = filename.substring(0, indexOf);
        anchorName = filename.substring(indexOf + 1);
    } else {
        file = filename;
    }

    String middle = prefs.get(JabRefPreferences.LANGUAGE) + '/';

    URL old = getPage();

    // First check in specified language
    URL resource = resourceOwner.getResource(GUIGlobals.helpPre + middle + file);

    // If not available fallback to english
    if (resource == null) {
        resource = resourceOwner.getResource(GUIGlobals.helpPre + "en/" + file);
        LOGGER.info("No localization available for file '" + file + "'. Falling back to English.");
    }

    // If still not available print a warning
    if (resource == null) {
        // TODO show warning to user
        LOGGER.error("Could not find html-help for file '" + file + "'.");
        return;
    }

    setPageOnly(resource, anchorName);

    forw.removeAllElements();
    if (old != null) {
        history.push(old);
    }

}

From source file:com.medallia.spider.SpiderServlet.java

/** @return the path to the StringTemplate with the given name */
protected String findPathForTemplate(String name) {
    name = "st/" + name;
    String path = name + ".st";
    Class<?> c = getServletClass();
    while (c != null) {
        if (c.getResource(path) != null)
            return c.getPackage().getName().replace('.', '/') + "/" + name;

        if (c == SpiderServlet.class)
            break;

        c = c.getSuperclass();/*from  w  ww  .  j  av  a  2  s .  c  o m*/
    }
    throw new RuntimeException("Cannot find template " + name);
}

From source file:org.kurento.test.grid.GridHandler.java

private File getJarPath(Class<?> aclass) {
    URL url;/*from w  w  w .  jav  a 2s  .c o  m*/
    try {
        url = aclass.getProtectionDomain().getCodeSource().getLocation();
    } catch (SecurityException ex) {
        url = aclass.getResource(aclass.getSimpleName() + ".class");
    }
    try {
        return new File(url.toURI());
    } catch (URISyntaxException ex) {
        return new File(url.getPath());
    }
}

From source file:net.sf.jabref.help.HelpContent.java

public void setPage(String filename, Class resourceOwner) {

    // Check for anchor
    int indexOf = filename.indexOf('#');
    String file;// w ww .j  av  a 2  s. c  o m
    String reference;

    if (indexOf != -1) {
        file = filename.substring(0, indexOf);
        reference = filename.substring(indexOf + 1);
    } else {
        file = filename;
        reference = "";
    }

    String middle = prefs.get("language") + "/";
    if (middle.equals("en/"))
        middle = ""; // english in base help dir.

    URL old = getPage();
    try {
        // First check in specified language
        URL resource = resourceOwner.getResource(GUIGlobals.helpPre + middle + file);

        // If not available fallback to english
        if (resource == null) {
            resource = resourceOwner.getResource(GUIGlobals.helpPre + file);
        }

        // If still not available print a warning
        if (resource == null) {
            // TODO show warning to user
            log.error("Could not find html-help for file '" + file + "'.");
            return;
        }
        setPageOnly(new URL(resource.toString() + "#" + reference));

    } catch (IOException ex) {
        ex.printStackTrace();
    }

    forw.removeAllElements();
    if (old != null)
        history.push(old);

}

From source file:com.jk.framework.util.FakeRunnable.java

/**
 * Gets the application path.//from   w w  w  .  j  a  v a  2 s .com
 *
 * @return the application path
 */
public static String getApplicationPath() {
    /**
     * @todo this is used to get the current class path including the
     *       package structure , it should
     */
    final Class<Integer> c = Integer.class;
    final String className = c.getName();
    final String resourceName = "/" + className.replace('.', '/') + ".class";
    final URL location = c.getResource(resourceName);
    final File file = new File(location.getFile());
    return file.getAbsolutePath();
}

From source file:com.vmware.qe.framework.datadriven.impl.supplier.CSVDataSupplier.java

public HierarchicalConfiguration getData(final String className, HierarchicalConfiguration context) {
    HierarchicalConfiguration testData = null;
    try {/*from   ww  w  . j a va 2s .  c o m*/
        Class<?> clazz = Class.forName(className);
        String dataFilePath = null;
        URL dataFileURL = null;
        String dataFileName = context.getString("supplier.dataFile", null);
        log.debug("Checking the data file in argument...");
        if (dataFileName == null || dataFileName.equals("")) {
            log.debug("Data file not given in argument..Using DataFileFinder..");
            dataFilePath = DDUtils.findDataFile(className, ".csv", context);
        } else {
            log.debug("Got data file in argument");
            dataFilePath = dataFileName;
        }
        log.debug("Data file path: " + dataFilePath);
        if (dataFilePath == null) {
            return null;// No data found, hence it's a normal test case.
        }
        dataFileURL = clazz.getResource(dataFilePath);
        CsvMapReader reader = new CsvMapReader(new InputStreamReader(dataFileURL.openStream()),
                CsvPreference.STANDARD_PREFERENCE);
        String list[] = reader.getHeader(true);
        Map<String, String> map = null;
        testData = new HierarchicalConfiguration();
        int i = 0;
        while ((map = reader.read(list)) != null) {
            String testId = null;
            HierarchicalConfiguration newData = new HierarchicalConfiguration();
            Set<Map.Entry<String, String>> entrySet = map.entrySet();
            for (Map.Entry<String, String> entry : entrySet) {
                if (entry.getKey().equals("test-id")) {
                    newData.addProperty("[@test-id]", entry.getValue());
                    testId = entry.getValue();
                    continue;
                }
                newData.addProperty(entry.getKey(), entry.getValue());
            }
            testData.addNodes("data(" + i + ")", newData.getRootNode().getChildren());
            if (testId != null) {
                testData.addProperty("data(" + i + ")[@test-id]", testId);
            }
            i++;
        }
        reader.close();
    } catch (Exception ex) {
        throw new DDException("Error in loading data file", ex);
    }
    return testData;
}