Example usage for org.springframework.core.io ClassPathResource exists

List of usage examples for org.springframework.core.io ClassPathResource exists

Introduction

In this page you can find the example usage for org.springframework.core.io ClassPathResource exists.

Prototype

@Override
public boolean exists() 

Source Link

Document

This implementation checks for the resolution of a resource URL.

Usage

From source file:io.s4.MainApp.java

public static void main(String args[]) throws Exception {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("corehome").hasArg().withDescription("core home").create("c"));

    options.addOption(/*w ww .j  av a  2  s . c o  m*/
            OptionBuilder.withArgName("appshome").hasArg().withDescription("applications home").create("a"));

    options.addOption(OptionBuilder.withArgName("s4clock").hasArg().withDescription("s4 clock").create("d"));

    options.addOption(OptionBuilder.withArgName("seedtime").hasArg()
            .withDescription("event clock initialization time").create("s"));

    options.addOption(
            OptionBuilder.withArgName("extshome").hasArg().withDescription("extensions home").create("e"));

    options.addOption(
            OptionBuilder.withArgName("instanceid").hasArg().withDescription("instance id").create("i"));

    options.addOption(
            OptionBuilder.withArgName("configtype").hasArg().withDescription("configuration type").create("t"));

    CommandLineParser parser = new GnuParser();
    CommandLine commandLine = null;
    String clockType = "wall";

    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException pe) {
        System.err.println(pe.getLocalizedMessage());
        System.exit(1);
    }

    int instanceId = -1;
    if (commandLine.hasOption("i")) {
        String instanceIdStr = commandLine.getOptionValue("i");
        try {
            instanceId = Integer.parseInt(instanceIdStr);
        } catch (NumberFormatException nfe) {
            System.err.println("Bad instance id: %s" + instanceIdStr);
            System.exit(1);
        }
    }

    if (commandLine.hasOption("c")) {
        coreHome = commandLine.getOptionValue("c");
    }

    if (commandLine.hasOption("a")) {
        appsHome = commandLine.getOptionValue("a");
    }

    if (commandLine.hasOption("d")) {
        clockType = commandLine.getOptionValue("d");
    }

    if (commandLine.hasOption("e")) {
        extsHome = commandLine.getOptionValue("e");
    }

    String configType = "typical";
    if (commandLine.hasOption("t")) {
        configType = commandLine.getOptionValue("t");
    }

    long seedTime = 0;
    if (commandLine.hasOption("s")) {
        seedTime = Long.parseLong(commandLine.getOptionValue("s"));
    }

    File coreHomeFile = new File(coreHome);
    if (!coreHomeFile.isDirectory()) {
        System.err.println("Bad core home: " + coreHome);
        System.exit(1);
    }

    File appsHomeFile = new File(appsHome);
    if (!appsHomeFile.isDirectory()) {
        System.err.println("Bad applications home: " + appsHome);
        System.exit(1);
    }

    if (instanceId > -1) {
        System.setProperty("instanceId", "" + instanceId);
    } else {
        System.setProperty("instanceId", "" + S4Util.getPID());
    }

    List loArgs = commandLine.getArgList();

    if (loArgs.size() < 1) {
        // System.err.println("No bean configuration file specified");
        // System.exit(1);
    }

    // String s4ConfigXml = (String) loArgs.get(0);
    // System.out.println("s4ConfigXml is " + s4ConfigXml);

    ClassPathResource propResource = new ClassPathResource("s4-core.properties");
    Properties prop = new Properties();
    if (propResource.exists()) {
        prop.load(propResource.getInputStream());
    } else {
        System.err.println("Unable to find s4-core.properties. It must be available in classpath");
        System.exit(1);
    }

    ApplicationContext coreContext = null;
    String configBase = coreHome + File.separatorChar + "conf" + File.separatorChar + configType;
    String configPath = "";
    List<String> coreConfigUrls = new ArrayList<String>();
    File configFile = null;

    // load clock configuration
    configPath = configBase + File.separatorChar + clockType + "-clock.xml";
    coreConfigUrls.add(configPath);

    // load core config xml
    configPath = configBase + File.separatorChar + "s4-core-conf.xml";
    configFile = new File(configPath);
    if (!configFile.exists()) {
        System.err.printf("S4 core config file %s does not exist\n", configPath);
        System.exit(1);
    }

    coreConfigUrls.add(configPath);
    String[] coreConfigFiles = new String[coreConfigUrls.size()];
    coreConfigUrls.toArray(coreConfigFiles);

    String[] coreConfigFileUrls = new String[coreConfigFiles.length];
    for (int i = 0; i < coreConfigFiles.length; i++) {
        coreConfigFileUrls[i] = "file:" + coreConfigFiles[i];
    }

    coreContext = new FileSystemXmlApplicationContext(coreConfigFileUrls, coreContext);
    ApplicationContext context = coreContext;

    Clock s4Clock = (Clock) context.getBean("clock");
    if (s4Clock instanceof EventClock && seedTime > 0) {
        EventClock s4EventClock = (EventClock) s4Clock;
        s4EventClock.updateTime(seedTime);
        System.out.println("Intializing event clock time with seed time " + s4EventClock.getCurrentTime());
    }

    PEContainer peContainer = (PEContainer) context.getBean("peContainer");

    Watcher w = (Watcher) context.getBean("watcher");
    w.setConfigFilename(configPath);

    // load extension modules
    String[] configFileNames = getModuleConfigFiles(extsHome, prop);
    if (configFileNames.length > 0) {
        String[] configFileUrls = new String[configFileNames.length];
        for (int i = 0; i < configFileNames.length; i++) {
            configFileUrls[i] = "file:" + configFileNames[i];
        }
        context = new FileSystemXmlApplicationContext(configFileUrls, context);
    }

    // load application modules
    configFileNames = getModuleConfigFiles(appsHome, prop);
    if (configFileNames.length > 0) {
        String[] configFileUrls = new String[configFileNames.length];
        for (int i = 0; i < configFileNames.length; i++) {
            configFileUrls[i] = "file:" + configFileNames[i];
        }
        context = new FileSystemXmlApplicationContext(configFileUrls, context);
        // attach any beans that implement ProcessingElement to the PE
        // Container
        String[] processingElementBeanNames = context.getBeanNamesForType(ProcessingElement.class);
        for (String processingElementBeanName : processingElementBeanNames) {
            Object bean = context.getBean(processingElementBeanName);
            try {
                Method getS4ClockMethod = bean.getClass().getMethod("getS4Clock");

                if (getS4ClockMethod.getReturnType().equals(Clock.class)) {
                    if (getS4ClockMethod.invoke(bean) == null) {
                        Method setS4ClockMethod = bean.getClass().getMethod("setS4Clock", Clock.class);
                        setS4ClockMethod.invoke(bean, coreContext.getBean("clock"));
                    }
                }
            } catch (NoSuchMethodException mnfe) {
                // acceptable
            }
            System.out.println("Adding processing element with bean name " + processingElementBeanName + ", id "
                    + ((ProcessingElement) bean).getId());
            peContainer.addProcessor((ProcessingElement) bean, processingElementBeanName);
        }
    }
}

From source file:org.apache.s4.MainApp.java

public static void main(String args[]) throws Exception {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("corehome").hasArg().withDescription("core home").create("c"));

    options.addOption(/*from ww w  .ja  v  a 2  s .  c o  m*/
            OptionBuilder.withArgName("appshome").hasArg().withDescription("applications home").create("a"));

    options.addOption(OptionBuilder.withArgName("s4clock").hasArg().withDescription("s4 clock").create("d"));

    options.addOption(OptionBuilder.withArgName("seedtime").hasArg()
            .withDescription("event clock initialization time").create("s"));

    options.addOption(
            OptionBuilder.withArgName("extshome").hasArg().withDescription("extensions home").create("e"));

    options.addOption(
            OptionBuilder.withArgName("instanceid").hasArg().withDescription("instance id").create("i"));

    options.addOption(
            OptionBuilder.withArgName("configtype").hasArg().withDescription("configuration type").create("t"));

    CommandLineParser parser = new GnuParser();
    CommandLine commandLine = null;
    String clockType = "wall";

    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException pe) {
        System.err.println(pe.getLocalizedMessage());
        System.exit(1);
    }

    int instanceId = -1;
    if (commandLine.hasOption("i")) {
        String instanceIdStr = commandLine.getOptionValue("i");
        try {
            instanceId = Integer.parseInt(instanceIdStr);
        } catch (NumberFormatException nfe) {
            System.err.println("Bad instance id: %s" + instanceIdStr);
            System.exit(1);
        }
    }

    if (commandLine.hasOption("c")) {
        coreHome = commandLine.getOptionValue("c");
    }

    if (commandLine.hasOption("a")) {
        appsHome = commandLine.getOptionValue("a");
    }

    if (commandLine.hasOption("d")) {
        clockType = commandLine.getOptionValue("d");
    }

    if (commandLine.hasOption("e")) {
        extsHome = commandLine.getOptionValue("e");
    }

    String configType = "typical";
    if (commandLine.hasOption("t")) {
        configType = commandLine.getOptionValue("t");
    }

    long seedTime = 0;
    if (commandLine.hasOption("s")) {
        seedTime = Long.parseLong(commandLine.getOptionValue("s"));
    }

    File coreHomeFile = new File(coreHome);
    if (!coreHomeFile.isDirectory()) {
        System.err.println("Bad core home: " + coreHome);
        System.exit(1);
    }

    File appsHomeFile = new File(appsHome);
    if (!appsHomeFile.isDirectory()) {
        System.err.println("Bad applications home: " + appsHome);
        System.exit(1);
    }

    if (instanceId > -1) {
        System.setProperty("instanceId", "" + instanceId);
    } else {
        System.setProperty("instanceId", "" + S4Util.getPID());
    }

    List loArgs = commandLine.getArgList();

    if (loArgs.size() < 1) {
        // System.err.println("No bean configuration file specified");
        // System.exit(1);
    }

    // String s4ConfigXml = (String) loArgs.get(0);
    // System.out.println("s4ConfigXml is " + s4ConfigXml);

    ClassPathResource propResource = new ClassPathResource("s4-core.properties");
    Properties prop = new Properties();
    if (propResource.exists()) {
        prop.load(propResource.getInputStream());
    } else {
        System.err.println("Unable to find s4-core.properties. It must be available in classpath");
        System.exit(1);
    }

    ApplicationContext coreContext = null;
    String configBase = coreHome + File.separatorChar + "conf" + File.separatorChar + configType;
    String configPath = "";
    List<String> coreConfigUrls = new ArrayList<String>();
    File configFile = null;

    // load clock configuration
    configPath = configBase + File.separatorChar + clockType + "-clock.xml";
    coreConfigUrls.add(configPath);

    // load core config xml
    configPath = configBase + File.separatorChar + "s4-core-conf.xml";
    configFile = new File(configPath);
    if (!configFile.exists()) {
        System.err.printf("S4 core config file %s does not exist\n", configPath);
        System.exit(1);
    }

    coreConfigUrls.add(configPath);
    String[] coreConfigFiles = new String[coreConfigUrls.size()];
    coreConfigUrls.toArray(coreConfigFiles);

    String[] coreConfigFileUrls = new String[coreConfigFiles.length];
    for (int i = 0; i < coreConfigFiles.length; i++) {
        coreConfigFileUrls[i] = "file:" + coreConfigFiles[i];
    }

    coreContext = new FileSystemXmlApplicationContext(coreConfigFileUrls, coreContext);
    ApplicationContext context = coreContext;

    Clock clock = (Clock) context.getBean("clock");
    if (clock instanceof EventClock && seedTime > 0) {
        EventClock s4EventClock = (EventClock) clock;
        s4EventClock.updateTime(seedTime);
        System.out.println("Intializing event clock time with seed time " + s4EventClock.getCurrentTime());
    }

    PEContainer peContainer = (PEContainer) context.getBean("peContainer");

    Watcher w = (Watcher) context.getBean("watcher");
    w.setConfigFilename(configPath);

    // load extension modules
    String[] configFileNames = getModuleConfigFiles(extsHome, prop);
    if (configFileNames.length > 0) {
        String[] configFileUrls = new String[configFileNames.length];
        for (int i = 0; i < configFileNames.length; i++) {
            configFileUrls[i] = "file:" + configFileNames[i];
        }
        context = new FileSystemXmlApplicationContext(configFileUrls, context);
    }

    // load application modules
    configFileNames = getModuleConfigFiles(appsHome, prop);
    if (configFileNames.length > 0) {
        String[] configFileUrls = new String[configFileNames.length];
        for (int i = 0; i < configFileNames.length; i++) {
            configFileUrls[i] = "file:" + configFileNames[i];
        }
        context = new FileSystemXmlApplicationContext(configFileUrls, context);
        // attach any beans that implement ProcessingElement to the PE
        // Container
        String[] processingElementBeanNames = context.getBeanNamesForType(AbstractPE.class);
        for (String processingElementBeanName : processingElementBeanNames) {
            AbstractPE bean = (AbstractPE) context.getBean(processingElementBeanName);
            bean.setClock(clock);
            try {
                bean.setSafeKeeper((SafeKeeper) context.getBean("safeKeeper"));
            } catch (NoSuchBeanDefinitionException ignored) {
                // no safe keeper = no checkpointing / recovery
            }
            // if the application did not specify an id, use the Spring bean name
            if (bean.getId() == null) {
                bean.setId(processingElementBeanName);
            }
            System.out.println("Adding processing element with bean name " + processingElementBeanName + ", id "
                    + ((AbstractPE) bean).getId());
            peContainer.addProcessor((AbstractPE) bean);
        }
    }
}

From source file:com.fengduo.bee.commons.filter.xss.XssClean.java

public static Policy getPolicy() throws PolicyException, ServiceException {
    if (policy == null) {
        ClassPathResource classPathResource = new ClassPathResource("/antisamy/spark-antisamy.xml");
        if (classPathResource == null || !classPathResource.exists()) {
            throw new ServiceException("spark-antisamy.xml is not exists!");
        }/*from  w w w  . j a  v  a 2 s. c  om*/
        InputStream policyFile = XssClean.class.getResourceAsStream("/antisamy/spark-antisamy.xml");
        if (policyFile == null) {
            throw new ServiceException("spark-antisamy.xml is not exists!");
        }
        policy = Policy.getInstance(policyFile);
    }
    return policy;
}

From source file:com.ankang.report.config.ReportConfig.java

public static void loadReportConfig(String classPath) {

    if ((null == classPath || REPORT.equals(classPath)) && !isLoad) {

        classPath = REPORT;//from w  w  w  . j a  v a  2s.c  o m
        isLoad = Boolean.TRUE;
    }
    logger.info("load properties " + classPath);

    ClassPathResource cp = new ClassPathResource(classPath);

    try {
        if (cp.exists()) {
            ps.load(cp.getInputStream());
            convertMap((Map) ps);
            ps.clear();
        }
    } catch (IOException e) {
        throw new ReportException("File read exception file.[%s]", classPath);
    }

}

From source file:py.una.pol.karaku.test.util.TestUtils.java

/**
 * Retorna un recurso, que se supone esta en la misma ubicacin que la
 * clase./*from w  w w .j a v  a2s .  c om*/
 * 
 * @param source
 *            Clase de dondese invoca
 * @param fileName
 *            nombre del archivo
 * @return ClassPath vlido
 * @throws KarakuRuntimeException
 *             si no se encuentra el archivo
 */
public static ClassPathResource getSiblingResource(Class<?> source, String resourceName) {

    ClassPathResource cpr = new ClassPathResource(resourceName);
    if (cpr.exists()) {
        return cpr;
    }

    String realPath = source.getPackage().getName().replaceAll("\\.", "/");
    realPath += "/" + resourceName;
    cpr = new ClassPathResource(realPath);

    if (!cpr.exists()) {
        throw new KarakuRuntimeException("File with name " + resourceName
                + " can not be found. Paths tried: Absolute:" + resourceName + "; Relative: " + realPath);
    }
    return cpr;
}

From source file:com.github.vanroy.springdata.jest.MappingBuilder.java

private static void mapEntity(XContentBuilder xContentBuilder, Class clazz, boolean isRootObject,
        String idFieldName, String nestedObjectFieldName, boolean nestedOrObjectField, FieldType fieldType,
        Field fieldAnnotation) throws IOException {

    java.lang.reflect.Field[] fields = retrieveFields(clazz);

    if (!isRootObject && (isAnyPropertyAnnotatedAsField(fields) || nestedOrObjectField)) {
        String type = FieldType.Object.toString().toLowerCase();
        if (nestedOrObjectField) {
            type = fieldType.toString().toLowerCase();
        }//w w  w . j  a  v  a  2 s.c  om
        XContentBuilder t = xContentBuilder.startObject(nestedObjectFieldName).field(FIELD_TYPE, type);

        if (nestedOrObjectField && FieldType.Nested == fieldType && fieldAnnotation.includeInParent()) {
            t.field("include_in_parent", fieldAnnotation.includeInParent());
        }
        t.startObject(FIELD_PROPERTIES);
    }

    for (java.lang.reflect.Field field : fields) {

        if (field.isAnnotationPresent(Transient.class) || isInIgnoreFields(field)) {
            continue;
        }

        if (field.isAnnotationPresent(Mapping.class)) {
            String mappingPath = field.getAnnotation(Mapping.class).mappingPath();
            if (isNotBlank(mappingPath)) {
                ClassPathResource mappings = new ClassPathResource(mappingPath);
                if (mappings.exists()) {
                    xContentBuilder.rawField(field.getName(), mappings.getInputStream());
                    continue;
                }
            }
        }

        boolean isGeoPointField = isGeoPointField(field);
        boolean isCompletionField = isCompletionField(field);

        Field singleField = field.getAnnotation(Field.class);
        if (!isGeoPointField && !isCompletionField && isEntity(field) && isAnnotated(field)) {
            if (singleField == null) {
                continue;
            }
            boolean nestedOrObject = isNestedOrObjectField(field);
            mapEntity(xContentBuilder, getFieldType(field), false, EMPTY, field.getName(), nestedOrObject,
                    singleField.type(), field.getAnnotation(Field.class));
            if (nestedOrObject) {
                continue;
            }
        }

        MultiField multiField = field.getAnnotation(MultiField.class);

        if (isGeoPointField) {
            applyGeoPointFieldMapping(xContentBuilder, field);
        }

        if (isCompletionField) {
            CompletionField completionField = field.getAnnotation(CompletionField.class);
            applyCompletionFieldMapping(xContentBuilder, field, completionField);
        }

        if (isRootObject && singleField != null && isIdField(field, idFieldName)) {
            applyDefaultIdFieldMapping(xContentBuilder, field);
        } else if (multiField != null) {
            addMultiFieldMapping(xContentBuilder, field, multiField, isNestedOrObjectField(field));
        } else if (singleField != null) {
            addSingleFieldMapping(xContentBuilder, field, singleField, isNestedOrObjectField(field));
        }
    }

    if (!isRootObject && isAnyPropertyAnnotatedAsField(fields) || nestedOrObjectField) {
        xContentBuilder.endObject().endObject();
    }
}

From source file:edu.northwestern.bioinformatics.studycalendar.restlets.ClasspathResourceRepresentation.java

@Override
public InputStream getStream() throws IOException {
    ClassPathResource res = new ClassPathResource(resourceName);
    if (!res.exists()) {
        throw new FileNotFoundException("Could not find " + resourceName);
    }//from ww  w .  j a v a  2s  .  c  om
    return res.getInputStream();
}

From source file:nl.knaw.dans.common.lang.spring.UsernamePropertyPlaceholderConfigurer.java

public UsernamePropertyPlaceholderConfigurer() throws IOException {
    String filename = RESOURCE_PATH + System.getProperty("user.name") + ".properties";
    ClassPathResource resource = new ClassPathResource(filename);
    if (!resource.exists()) {
        resource = new ClassPathResource(DEFAULT_APP_PROPERTIES);
    }/*from ww  w.  j  av  a 2s  . c om*/
    setLocation(resource);
    logger.info("Found application properties at " + resource.getFile().getAbsolutePath());
}

From source file:org.nd4j.linalg.jcublas.kernel.KernelFunctionLoaderTests.java

@Test
public void testLoader() throws Exception {
    Nd4j.dtype = DataBuffer.DOUBLE;

    KernelFunctionLoader loader = KernelFunctionLoader.getInstance();
    loader.load();/*  w  ww . j a va 2  s .c  om*/
    ClassPathResource res = new ClassPathResource("/cudafunctions.properties");
    if (!res.exists())
        throw new IllegalStateException("Please put a cudafunctions.properties in your class path");
    Properties props = new Properties();
    props.load(res.getInputStream());
    loader.unload();

}

From source file:com.iflytek.edu.cloud.frame.web.listener.LogBackLoadConfigureListener.java

@Override
public void contextInitialized(ServletContextEvent sce) {
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();

    try {/*from  w  w  w.j a v a2  s.  co m*/
        JoranConfigurator configurator = new JoranConfigurator();
        configurator.setContext(context);
        context.reset();
        ClassPathResource resource = new ClassPathResource("logback-default.xml");
        if (!resource.exists()) {
            String profile = EnvUtil.getProfile();
            resource = new ClassPathResource("META-INF/logback/logback-" + profile + ".xml");
        }

        configurator.doConfigure(resource.getInputStream());
        logger.info("logback?" + resource.getURL().getPath());
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    StatusPrinter.printInCaseOfErrorsOrWarnings(context);
}