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

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

Introduction

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

Prototype

public ClassPathResource(String path) 

Source Link

Document

Create a new ClassPathResource for ClassLoader usage.

Usage

From source file:com.divinesoft.boynas.Boynas.java

public static void main(String args[]) {
    //TODO: Move Options to a different method
    Options options = new Options();

    //Create options
    Option list = OptionBuilder.withDescription("List all config entries in database").create("list");

    Option clean = OptionBuilder.withDescription("Remove all config entries in database").create("clean");

    Option importCSV = OptionBuilder.withArgName("file").hasArg()
            .withDescription("Import config entries from a CSV file").create("importCSV");

    Option exportXML = OptionBuilder.withDescription("Export all config entries to XML CFG files")
            .create("exportXML");

    Option exportTemplate = OptionBuilder.withArgName("templates folder").hasArgs()
            .withDescription("Export all config entries from a set of template files").create("exportTemplate");

    Option version = OptionBuilder.withDescription("Print the version number").create("version");

    Option quickGen = OptionBuilder.withArgName("import file,templates folder")
            .withDescription("Use a one-shot template based config generator").hasArgs(2)
            .withValueSeparator(' ').create("quickExport");

    //Add options
    options.addOption(list);/*from   w ww.j  a v  a 2s . co m*/
    options.addOption(clean);
    options.addOption(importCSV);
    options.addOption(exportXML);
    options.addOption(exportTemplate);
    options.addOption(quickGen);
    options.addOption(version);

    CommandLineParser parser = new GnuParser();

    //The main Boynas object
    Boynas boynas;

    //Start dealing with application context
    XmlBeanFactory appContext = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));

    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("list")) {
            boynas = (Boynas) appContext.getBean("boynasList");
            boynas.getAllConfigEntries();
        } else if (cmd.hasOption("clean")) {
            boynas = (Boynas) appContext.getBean("boynasList");
            boynas.clean();
        } else if (cmd.hasOption("importCSV")) {
            Boynas.filePath = cmd.getOptionValue("importCSV");
            boynas = (Boynas) appContext.getBean("bynImportCSV");
            boynas.importCSV();
        } else if (cmd.hasOption("exportXML")) {
            boynas = (Boynas) appContext.getBean("bynExportXML");
            boynas.exportXML();
        } else if (cmd.hasOption("version")) {
            boynas = (Boynas) appContext.getBean("boynasList");
            boynas.printVersion();
        } else if (cmd.hasOption("exportTemplate")) {
            Boynas.templatePath = cmd.getOptionValue("exportTemplate");
            boynas = (Boynas) appContext.getBean("bynExportTemplate");
            boynas.exportTemplate();
        } else if (cmd.hasOption("quickExport")) {
            String[] paths = cmd.getOptionValues("quickExport");

            if (paths.length < 2) {
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp("boynas", options);
            }

            Boynas.filePath = paths[0];
            Boynas.templatePath = paths[1];
            boynas = (Boynas) appContext.getBean("bynQuickExport");
            boynas.quickExport();
        }

        else {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("boynas", options);
        }

    } catch (ParseException e) {
        System.err.println("Parsing failed. Reason: " + e.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("boynas", options);
    }
}

From source file:au.com.jwatmuff.eventmanager.Main.java

/**
 * Main method.// w ww  .  java2  s.c  o m
 */
public static void main(String args[]) {
    LogUtils.setupUncaughtExceptionHandler();

    /* Set timeout for RMI connections - TODO: move to external file */
    System.setProperty("sun.rmi.transport.tcp.handshakeTimeout", "2000");
    updateRmiHostName();

    /*
     * Set up menu bar for Mac
     */
    System.setProperty("apple.laf.useScreenMenuBar", "true");
    System.setProperty("com.apple.mrj.application.apple.menu.about.name", "Event Manager");

    /*
     * Set look and feel to 'system' style
     */
    try {
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {
        log.info("Failed to set system look and feel");
    }

    /*
     * Set workingDir to a writable folder for storing competitions, settings etc.
     */
    String applicationData = System.getenv("APPDATA");
    if (applicationData != null) {
        workingDir = new File(applicationData, "EventManager");
        if (workingDir.exists() || workingDir.mkdirs()) {
            // redirect logging to writable folder
            LogUtils.reconfigureFileAppenders("log4j.properties", workingDir);
        } else {
            workingDir = new File(".");
        }
    }

    // log version for debugging
    log.info("Running version: " + VISIBLE_VERSION + " (Internal: " + VERSION + ")");

    /*
     * Copy license if necessary
     */
    File license1 = new File("license.lic");
    File license2 = new File(workingDir, "license.lic");
    if (license1.exists() && !license2.exists()) {
        try {
            FileUtils.copyFile(license1, license2);
        } catch (IOException e) {
            log.warn("Failed to copy license from " + license1 + " to " + license2, e);
        }
    }
    if (license1.exists() && license2.exists()) {
        if (license1.lastModified() > license2.lastModified()) {
            try {
                FileUtils.copyFile(license1, license2);
            } catch (IOException e) {
                log.warn("Failed to copy license from " + license1 + " to " + license2, e);
            }
        }
    }

    /*
     * Check if run lock exists, if so ask user if it is ok to continue
     */
    if (!obtainRunLock(false)) {
        int response = JOptionPane.showConfirmDialog(null,
                "Unable to obtain run-lock.\nPlease ensure that no other instances of EventManager are running before continuing.\nDo you wish to continue?",
                "Run-lock detected", JOptionPane.YES_NO_OPTION);
        if (response == JOptionPane.YES_OPTION)
            obtainRunLock(true);
        else
            System.exit(0);
    }

    try {
        LoadWindow loadWindow = new LoadWindow();
        loadWindow.setVisible(true);

        loadWindow.addMessage("Reading settings..");

        /*
         * Read properties from file
         */
        final Properties props = new Properties();
        try {
            Properties defaultProps = PropertiesLoaderUtils
                    .loadProperties(new ClassPathResource("eventmanager.properties"));
            props.putAll(defaultProps);
        } catch (IOException ex) {
            log.error(ex);
        }

        props.putAll(System.getProperties());

        File databaseStore = new File(workingDir, "comps");
        int rmiPort = Integer.parseInt(props.getProperty("eventmanager.rmi.port"));

        loadWindow.addMessage("Loading Peer Manager..");
        log.info("Loading Peer Manager");

        ManualDiscoveryService manualDiscoveryService = new ManualDiscoveryService();
        JmDNSRMIPeerManager peerManager = new JmDNSRMIPeerManager(rmiPort, new File(workingDir, "peerid.dat"));
        peerManager.addDiscoveryService(manualDiscoveryService);

        monitorNetworkInterfaceChanges(peerManager);

        loadWindow.addMessage("Loading Database Manager..");
        log.info("Loading Database Manager");

        DatabaseManager databaseManager = new SQLiteDatabaseManager(databaseStore, peerManager);
        LicenseManager licenseManager = new LicenseManager(workingDir);

        loadWindow.addMessage("Loading Load Competition Dialog..");
        log.info("Loading Load Competition Dialog");

        LoadCompetitionWindow loadCompetitionWindow = new LoadCompetitionWindow(databaseManager, licenseManager,
                peerManager);
        loadCompetitionWindow.setTitle(WINDOW_TITLE);

        loadWindow.dispose();
        log.info("Starting Load Competition Dialog");

        while (true) {
            // reset permission checker to use our license
            licenseManager.updatePermissionChecker();

            GUIUtils.runModalJFrame(loadCompetitionWindow);

            if (loadCompetitionWindow.getSuccess()) {
                DatabaseInfo info = loadCompetitionWindow.getSelectedDatabaseInfo();

                if (!databaseManager.checkLock(info.id)) {
                    String message = "EventManager did not shut down correctly the last time this competition was open. To avoid potential data corruption, you are advised to take the following steps:\n"
                            + "1) Do NOT open this competition\n" + "2) Create a backup of this competition\n"
                            + "3) Delete the competition from this computer\n"
                            + "4) If possible, reload this competition from another computer on the network\n"
                            + "5) Alternatively, you may manually load the backup onto all computers on the network, ensuring the 'Preserve competition ID' option is checked.";
                    String title = "WARNING: Potential Data Corruption Detected";

                    int status = JOptionPane.showOptionDialog(null, message, title, JOptionPane.YES_NO_OPTION,
                            JOptionPane.ERROR_MESSAGE, null,
                            new Object[] { "Cancel (recommended)", "Open anyway" }, "Cancel (recommended)");

                    if (status == 0)
                        continue; // return to load competition window
                }

                SynchronizingWindow syncWindow = new SynchronizingWindow();
                syncWindow.setVisible(true);
                long t = System.nanoTime();
                DistributedDatabase database = databaseManager.activateDatabase(info.id, info.passwordHash);
                long dt = System.nanoTime() - t;
                log.debug(String.format("Initial sync in %dms",
                        TimeUnit.MILLISECONDS.convert(dt, TimeUnit.NANOSECONDS)));
                syncWindow.dispose();

                if (loadCompetitionWindow.isNewDatabase()) {
                    GregorianCalendar calendar = new GregorianCalendar();
                    Date today = calendar.getTime();
                    calendar.set(Calendar.MONTH, Calendar.DECEMBER);
                    calendar.set(Calendar.DAY_OF_MONTH, 31);
                    Date endOfYear = new java.sql.Date(calendar.getTimeInMillis());

                    CompetitionInfo ci = new CompetitionInfo();
                    ci.setName(info.name);
                    ci.setStartDate(today);
                    ci.setEndDate(today);
                    ci.setAgeThresholdDate(endOfYear);
                    //ci.setPasswordHash(info.passwordHash);
                    License license = licenseManager.getLicense();
                    if (license != null) {
                        ci.setLicenseName(license.getName());
                        ci.setLicenseType(license.getType().toString());
                        ci.setLicenseContact(license.getContactPhoneNumber());
                    }
                    database.add(ci);
                }

                // Set PermissionChecker to use database's license type
                String competitionLicenseType = database.get(CompetitionInfo.class, null).getLicenseType();
                PermissionChecker.setLicenseType(LicenseType.valueOf(competitionLicenseType));

                TransactionNotifier notifier = new TransactionNotifier();
                database.setListener(notifier);

                MainWindow mainWindow = new MainWindow();
                mainWindow.setDatabase(database);
                mainWindow.setNotifier(notifier);
                mainWindow.setPeerManager(peerManager);
                mainWindow.setLicenseManager(licenseManager);
                mainWindow.setManualDiscoveryService(manualDiscoveryService);
                mainWindow.setTitle(WINDOW_TITLE);
                mainWindow.afterPropertiesSet();

                TestUtil.setActivatedDatabase(database);

                // show main window (modally)
                GUIUtils.runModalJFrame(mainWindow);

                // shutdown procedures

                // System.exit();

                database.shutdown();
                databaseManager.deactivateDatabase(1500);

                if (mainWindow.getDeleteOnExit()) {
                    for (File file : info.localDirectory.listFiles())
                        if (!file.isDirectory())
                            file.delete();
                    info.localDirectory.deleteOnExit();
                }
            } else {
                // This can cause an RuntimeException - Peer is disconnected
                peerManager.stop();
                System.exit(0);
            }
        }
    } catch (Throwable e) {
        log.error("Error in main function", e);
        String message = e.getMessage();
        if (message == null)
            message = "";
        if (message.length() > 100)
            message = message.substring(0, 97) + "...";
        GUIUtils.displayError(null,
                "An unexpected error has occured.\n\n" + e.getClass().getSimpleName() + "\n" + message);
        System.exit(0);
    }
}

From source file:com.univocity.app.utils.FileFinder.java

public static File findFile(String path) {
    Resource resource = new ClassPathResource(path);
    File file;/*from w w w .ja v a 2  s.c  om*/
    try {
        file = resource.getFile();
    } catch (IOException e) {
        file = new File(path);
        if (!file.exists()) {
            //we are not including the resources into the jars
            //this is needed to find the resources when executing from the IDE & test cases.
            file = new File("src/main/resources/" + path);
        }
    }

    if (file == null || !file.exists()) {
        throw new IllegalArgumentException("Unable to find file specified by path: " + path);
    }

    return file;
}

From source file:gov.nih.nci.lv.auth.ObjectFactory.java

/**
 *
 * @param name name/*from  w ww .  j  av a  2 s .com*/
 * @return Object
 */
public static Object getObject(String name) {
    if (fact == null) {
        ClassPathResource res = new ClassPathResource("applicationContext.xml");
        fact = new XmlBeanFactory(res);
    }
    return fact.getBean(name);
}

From source file:net.lalotech.spring.mvc.config.PropertiesConfiguration.java

static @Bean public PropertySourcesPlaceholderConfigurer myPropertySourcesPlaceholderConfigurer() {
    PropertySourcesPlaceholderConfigurer p = new PropertySourcesPlaceholderConfigurer();
    Resource[] resourceLocations = new Resource[] { new ClassPathResource("app.properties") };
    p.setLocations(resourceLocations);/*  www  .ja  v a2 s.com*/
    return p;
}

From source file:com.example.JobUtil.java

public static Resource getResource(final String resourcePath) {

    if (resourcePath == null) {
        return null;
    }//from w w w.  ja va2s . co  m

    Resource resource = null;

    String profile = System.getProperty("spring.profiles.active");
    if (!StringUtils.hasText(profile) || ("loc").equals(profile)) {
        resource = new ClassPathResource(resourcePath);
        return resource;
    }

    try {
        resource = new UrlResource(resourcePath);
    } catch (Exception e) {
        log.error("resource error : {}", e.toString());
        return null;
    }

    return resource;
}

From source file:Main.java

/**
 * Return he dom root element of an xml file
 * @param filePathInClassPath  the file path relative to the classpath
 * @return  the root element// w ww. j a  va2  s  .  co m
 * @throws ParserConfigurationException
 * @throws IOException
 * @throws SAXException
 */
public static Element getRootElementFromFileInClasspath(String filePathInClassPath)
        throws ParserConfigurationException, IOException, SAXException {
    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

    // root elements
    Document doc = docBuilder.parse(new ClassPathResource(filePathInClassPath).getInputStream());
    return doc.getDocumentElement();
}

From source file:config.ResourceUtils.java

/**
 * Gets a resource by its relative path. If the resource is not found on the
 * file system, the classpath is searched. If nothing is found, null is
 * returned.//from www.j a  v  a2 s.  c  om
 *
 * @param fileName the name of the resource
 * @return the found resource
 */
public static Resource getResourceByRelativePath(String fileName) {
    Resource resource = new FileSystemResource(RESOURCES_FOLDER + File.separator + fileName);
    if (!resource.exists()) {
        //try to find it on the classpath
        resource = new ClassPathResource(fileName);
        if (!resource.exists()) {
            // making sure to run on Netbeans..
            resource = new FileSystemResource("src" + File.separator + "main" + File.separator
                    + RESOURCES_FOLDER + File.separator + fileName);
            if (!resource.exists()) {
                resource = null;
            }
        }
    }
    return resource;
}

From source file:de.randi2.ui.integration.AbstractUITest.java

@BeforeClass
public static void loadTestProperties() {
    try {//from  w  w w. j  av a 2s  . c o m
        testData.load((new ClassPathResource("testData.properties").getInputStream()));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:biz.c24.io.spring.integration.test.TestUtils.java

public static ComplexDataObject loadObject() throws Exception {

    ClassPathResource resource = new ClassPathResource("valid-1.txt");

    TextualSource textualSource = new TextualSource(resource.getInputStream());

    ComplexDataObject object = textualSource.readObject(InputDocumentRootElement.getInstance());

    return object;
}