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

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

Introduction

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

Prototype

@Override
public File getFile() throws IOException 

Source Link

Document

This implementation returns a File reference for the underlying class path resource, provided that it refers to a file in the file system.

Usage

From source file:info.jtrac.config.JtracConfigurer.java

private void configureJtrac() throws Exception {

    String jtracHome = null;//from   w w w  .j av a 2  s .co m
    ClassPathResource jtracInitResource = new ClassPathResource("jtrac-init.properties");
    // jtrac-init.properties assumed to exist
    Properties props = loadProps(jtracInitResource.getFile());
    logger.info("found 'jtrac-init.properties' on classpath, processing...");
    jtracHome = props.getProperty("jtrac.home");
    if (jtracHome != null) {
        logger.info("'jtrac.home' property initialized from 'jtrac-init.properties' as '" + jtracHome + "'");
    }
    //======================================================================
    FilenameFilter ff = new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.startsWith("messages_") && name.endsWith(".properties");
        }
    };
    File[] messagePropsFiles = jtracInitResource.getFile().getParentFile().listFiles(ff);
    String locales = "en";
    for (File f : messagePropsFiles) {
        int endIndex = f.getName().indexOf('.');
        String localeCode = f.getName().substring(9, endIndex);
        locales += "," + localeCode;
    }
    logger.info("locales available configured are '" + locales + "'");
    props.setProperty("jtrac.locales", locales);
    //======================================================================
    if (jtracHome == null) {
        logger.info(
                "valid 'jtrac.home' property not available in 'jtrac-init.properties', trying system properties.");
        jtracHome = System.getProperty("jtrac.home");
        if (jtracHome != null) {
            logger.info("'jtrac.home' property initialized from system properties as '" + jtracHome + "'");
        }
    }
    if (jtracHome == null) {
        logger.info(
                "valid 'jtrac.home' property not available in system properties, trying servlet init paramters.");
        jtracHome = servletContext.getInitParameter("jtrac.home");
        if (jtracHome != null) {
            logger.info("Servlet init parameter 'jtrac.home' exists: '" + jtracHome + "'");
        }
    }
    if (jtracHome == null) {
        jtracHome = System.getProperty("user.home") + "/.jtrac";
        logger.warn("Servlet init paramter  'jtrac.home' does not exist.  Will use 'user.home' directory '"
                + jtracHome + "'");
    }
    //======================================================================
    File homeFile = new File(jtracHome);
    if (!homeFile.exists()) {
        homeFile.mkdir();
        logger.info("directory does not exist, created '" + homeFile.getPath() + "'");
        if (!homeFile.exists()) {
            String message = "invalid path '" + homeFile.getAbsolutePath()
                    + "', try creating this directory first.  Aborting.";
            logger.error(message);
            throw new Exception(message);
        }
    } else {
        logger.info("directory already exists: '" + homeFile.getPath() + "'");
    }
    props.setProperty("jtrac.home", homeFile.getAbsolutePath());
    //======================================================================
    File attachmentsFile = new File(jtracHome + "/attachments");
    if (!attachmentsFile.exists()) {
        attachmentsFile.mkdir();
        logger.info("directory does not exist, created '" + attachmentsFile.getPath() + "'");
    } else {
        logger.info("directory already exists: '" + attachmentsFile.getPath() + "'");
    }
    File indexesFile = new File(jtracHome + "/indexes");
    if (!indexesFile.exists()) {
        indexesFile.mkdir();
        logger.info("directory does not exist, created '" + indexesFile.getPath() + "'");
    } else {
        logger.info("directory already exists: '" + indexesFile.getPath() + "'");
    }
    //======================================================================
    File propsFile = new File(homeFile.getPath() + "/jtrac.properties");
    if (!propsFile.exists()) {
        propsFile.createNewFile();
        logger.info("properties file does not exist, created '" + propsFile.getPath() + "'");
        OutputStream os = new FileOutputStream(propsFile);
        Writer out = new PrintWriter(os);
        try {
            out.write("database.driver=org.hsqldb.jdbcDriver\n");
            out.write("database.url=jdbc:hsqldb:file:${jtrac.home}/db/jtrac\n");
            out.write("database.username=sa\n");
            out.write("database.password=\n");
            out.write("hibernate.dialect=org.hibernate.dialect.HSQLDialect\n");
            out.write("hibernate.show_sql=false\n");
        } finally {
            out.close();
            os.close();
        }
        logger.info("HSQLDB will be used.  Finished creating '" + propsFile.getPath() + "'");
    } else {
        logger.info("'jtrac.properties' file exists: '" + propsFile.getPath() + "'");
    }
    //======================================================================
    String version = "0.0.0";
    String timestamp = "0000";
    ClassPathResource versionResource = new ClassPathResource("jtrac-version.properties");
    if (versionResource.exists()) {
        logger.info("found 'jtrac-version.properties' on classpath, processing...");
        Properties versionProps = loadProps(versionResource.getFile());
        version = versionProps.getProperty("version");
        timestamp = versionProps.getProperty("timestamp");
    } else {
        logger.info("did not find 'jtrac-version.properties' on classpath");
    }
    logger.info("jtrac.version = '" + version + "'");
    logger.info("jtrac.timestamp = '" + timestamp + "'");
    props.setProperty("jtrac.version", version);
    props.setProperty("jtrac.timestamp", timestamp);
    props.setProperty("database.validationQuery", "SELECT 1");
    props.setProperty("ldap.url", "");
    props.setProperty("ldap.activeDirectoryDomain", "");
    props.setProperty("ldap.searchBase", "");
    props.setProperty("database.datasource.jndiname", "");
    // set default properties that can be overridden by user if required
    setProperties(props);
    // finally set the property that spring is expecting, manually
    FileSystemResource fsr = new FileSystemResource(propsFile);
    setLocation(fsr);
}

From source file:oz.hadoop.yarn.api.core.LocalApplicationLaunchTests.java

@Test(timeout = 2000)
public void validateContainerLaunchWithInfiniteCommandForcedShutdown() throws Exception {
    ClassPathResource resource = new ClassPathResource("infinite", this.getClass());
    final YarnApplication<Void> yarnApplication = YarnAssembly
            .forApplicationContainer(resource.getFile().getAbsolutePath()).containerCount(3).memory(512)
            .withApplicationMaster().maxAttempts(2).priority(2).build("sample-yarn-application");

    assertEquals(0, yarnApplication.liveContainers());
    assertFalse(yarnApplication.isRunning());

    ExecutorService executor = Executors.newCachedThreadPool();
    executor.execute(new Runnable() {
        @Override//from w  w  w. ja v a  2 s. c o m
        public void run() {
            yarnApplication.launch();
        }
    });
    while (yarnApplication.liveContainers() != 3) {
        LockSupport.parkNanos(1000);
    }
    assertTrue(yarnApplication.isRunning());
    yarnApplication.terminate();
    assertEquals(0, yarnApplication.liveContainers());
}

From source file:org.joy.config.Configuration.java

public Configuration(String classPath) {
    ClassPathResource resource = new ClassPathResource(this.CONFIGURATION_FILE);

    try {//from   ww w . j a va  2s. co  m
        this.configurationFile = classPath + CONFIGURATION_FILE;
        this.configurationFile = resource.getFile().getAbsolutePath();
    } catch (IOException e) {
        throw new Wrong(e);
    }
}

From source file:org.springsource.restbucks.PaymentProcessIntegrationTest.java

/**
 * Creates a new {@link Order} by looking up the orders link from the source and posting the content of
 * {@code orders.json} to it. Verifies we get receive a {@code 201 Created} and a {@code Location} header. Follows the
 * location header to retrieve the {@link Order} just created.
 * //w ww . j a  va2s.  c om
 * @param source
 * @return
 * @throws Exception
 */
private MockHttpServletResponse createNewOrder(MockHttpServletResponse source) throws Exception {

    String content = source.getContentAsString();
    Link ordersLink = links.findLinkWithRel(ORDERS_REL, content);

    ClassPathResource resource = new ClassPathResource("order.json");
    byte[] data = Files.readAllBytes(resource.getFile().toPath());

    MockHttpServletResponse result = mvc
            .perform(post(ordersLink.getHref()).contentType(MediaType.APPLICATION_JSON).content(data)). //
            andExpect(status().isCreated()). //
            andExpect(header().string("Location", is(notNullValue()))). //
            andReturn().getResponse();

    return mvc.perform(get(result.getHeader("Location"))).andReturn().getResponse();
}

From source file:com.wavemaker.tools.javaservice.JavaServiceDefinition2Test.java

private ServiceDefinition getServiceDefFromJar(String jarFileName) throws Exception {

    List<File> classRoots = new ArrayList<File>();
    List<File> jarDirs = new ArrayList<File>();

    File jarDir = IOUtils.createTempDirectory();
    File srcJarFile = new ClassPathResource(
            this.getClass().getPackage().getName().replace(".", "/") + "/" + jarFileName).getFile();
    File jarFile = new File(jarDir, jarFileName);
    FileUtils.copyFile(srcJarFile, jarFile);
    jarDirs.add(jarDir);/*from w w  w  .  j a  va2s .  c  om*/

    ClassPathResource runtimeServiceResource = new ClassPathResource(
            "com/wavemaker/runtime/service/LiveDataService.class");
    if (ResourceUtils.isJarURL(runtimeServiceResource.getURL())) {
        URL jarUrl = ResourceUtils.extractJarFileURL(runtimeServiceResource.getURL());
        jarDirs.add(ResourceUtils.getFile(jarUrl).getParentFile());
    } else {
        File runtimeServiceClassFile = runtimeServiceResource.getFile();
        File runtimeClassRoot = runtimeServiceClassFile.getParentFile().getParentFile().getParentFile()
                .getParentFile().getParentFile();
        classRoots.add(runtimeClassRoot);
    }

    ServiceDefinition ret = new JavaServiceDefinition("Foo", "serviceId", classRoots, jarDirs,
            new ArrayList<String>());

    jarFile.delete();
    jarDir.delete();

    return ret;
}

From source file:no.dusken.momus.controller.DevController.java

@RequestMapping("/gdoc")
public @ResponseBody String gdocTest() {

    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    HttpTransport httpTransport = null;//from ww  w . j  av  a2s .  com
    try {
        httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    } catch (GeneralSecurityException | IOException e) {
        e.printStackTrace();
    }
    try {

        if (credential == null) {

            String email = "68986569027-ecn9md3ej7krhquhvamf7phfovro8aru@developer.gserviceaccount.com";

            ClassPathResource classPathResource = new ClassPathResource("googlekey.p12");
            File file = classPathResource.getFile();

            Collection<String> scopes = new ArrayList<>();
            scopes.add("https://www.googleapis.com/auth/drive");

            logger.info("making credentials");

            credential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory)
                    .setServiceAccountId(email)
                    //                    .setServiceAccountPrivateKey
                    .setServiceAccountPrivateKeyFromP12File(file).setServiceAccountScopes(scopes).build();

            logger.info("made credentials");
        }

        if (drive == null) {

            drive = new Drive.Builder(httpTransport, jsonFactory, credential)
                    .setApplicationName("momustest-molten-aurora-752").build();

            logger.info("made drive");
        }

        long start = System.currentTimeMillis();

        // list all files
        Drive.Files.List request = drive.files().list();
        FileList fileList = request.execute();

        List<com.google.api.services.drive.model.File> items = fileList.getItems();
        for (com.google.api.services.drive.model.File item : items) {
            logger.info("file: {}", item);
            //                Map<String, String> exportLinks = item.getExportLinks();//.get("text/html");
            //                String s = exportLinks.get("text/plain"); // will crash for stuff not having this
            //                logger.debug("test");
        }

        About execute = drive.about().get().execute();

        // insert file
        //            com.google.api.services.drive.model.File insertFile = new com.google.api.services.drive.model.File();
        //            insertFile.setTitle("mats2.odt");
        //            insertFile.setMimeType("application/vnd.google-apps.document");
        //            com.google.api.services.drive.model.File uploaded = drive.files().insert(insertFile).execute();
        //            logger.info("uploaded file id({}): {}", uploaded.getId(), uploaded);
        //
        //            Permission permission = new Permission();
        //            permission.setRole("writer");
        //            permission.setType("anyone");
        //            permission.setValue("default");
        //            permission.setWithLink(true);
        //
        //            drive.permissions().insert(uploaded.getId(), permission).execute();

        long end = System.currentTimeMillis();
        long timeUsed = end - start;
        logger.debug("Time spent: {}ms", timeUsed);

    } catch (GeneralSecurityException | IOException e) {
        logger.debug("Ex: ", e);
    }

    return "gdoc ok";
}

From source file:com.wavemaker.tools.javaservice.JavaServiceDefinition2Test.java

private ServiceDefinition getServiceDef(String className, List<File> serviceLibDirs) throws Exception {

    List<File> classRoots = new ArrayList<File>();
    serviceLibDirs = serviceLibDirs == null ? new ArrayList<File>() : serviceLibDirs;

    File classFile = new ClassPathResource(className.replace('.', '/') + ".class").getFile();
    File classRoot = classFile.getParentFile().getParentFile().getParentFile().getParentFile().getParentFile();
    classRoots.add(classRoot);/*  w  w  w .  j  av  a2 s . c  om*/

    File queryInfoClassFile = new ClassPathResource(
            JavaService_BeanClass.class.getName().replace('.', '/') + ".class").getFile();
    File queryInfoClassRoot = queryInfoClassFile.getParentFile().getParentFile().getParentFile().getParentFile()
            .getParentFile();
    classRoots.add(queryInfoClassRoot);

    ClassPathResource runtimeServiceResource = new ClassPathResource(
            LiveDataService.class.getName().replace(".", "/") + ".class");
    if (ResourceUtils.isJarURL(runtimeServiceResource.getURL())) {
        URL jarUrl = ResourceUtils.extractJarFileURL(runtimeServiceResource.getURL());
        serviceLibDirs.add(ResourceUtils.getFile(jarUrl).getParentFile());
    } else {
        File runtimeServiceClassFile = runtimeServiceResource.getFile();
        File runtimeClassRoot = runtimeServiceClassFile.getParentFile().getParentFile().getParentFile()
                .getParentFile().getParentFile();
        classRoots.add(runtimeClassRoot);
    }

    ClassPathResource typeDefinitionResource = new ClassPathResource(
            TypeDefinition.class.getName().replace(".", "/") + ".class");
    if (ResourceUtils.isJarURL(typeDefinitionResource.getURL())) {
        URL jarUrl = ResourceUtils.extractJarFileURL(typeDefinitionResource.getURL());
        serviceLibDirs.add(ResourceUtils.getFile(jarUrl).getParentFile());
    } else {
        File typeDefinitionClassFile = typeDefinitionResource.getFile();
        File typeDefinitionClassRoot = typeDefinitionClassFile.getParentFile().getParentFile().getParentFile()
                .getParentFile().getParentFile();
        classRoots.add(typeDefinitionClassRoot);
    }

    return new JavaServiceDefinition(className, "serviceId", classRoots, serviceLibDirs,
            new ArrayList<String>());
}

From source file:com.ephesoft.dcma.workflows.service.impl.DeploymentServiceImpl.java

@Override
@PostConstruct//from   ww w  .  j ava 2 s  . co  m
public void deployAll() {
    if (deployAllWorkflow) {
        LOGGER.info("workflow.deploy property is set to true, All process definitions will be deployed");
        try {
            File newWorkflowFolder = new File(newWorkflowsBasePath);
            LOGGER.info("Base path for newly created workflows: ", newWorkflowsBasePath);
            deployProcessDefinitionFromSubdirectory(newWorkflowFolder, PLUGINS_CONSTANT);
            for (String processDefinition : workflowsDefinitionList) {
                LOGGER.info("Deploying default process definition at: ", processDefinition);
                DeploymentBuilder deployment = repositoryService.createDeployment();
                deployment.addClasspathResource(new ClassPathResource(processDefinition).getPath());
                deployment.deploy();
            }
            deployProcessDefinitionFromSubdirectory(newWorkflowFolder, MODULES_CONSTANT);
            deployProcessDefinitionFromSubdirectory(newWorkflowFolder, WORKFLOWS_CONSTANT);
            ClassPathResource workflowsClassPathResource = new ClassPathResource(META_INF_DCMA_WORKFLOWS);
            File workflowDirectory = workflowsClassPathResource.getFile();
            upgradeExistingBatchClasses();
            updatePropertyFile(workflowDirectory.getAbsolutePath());
            upgradeExistingBatchClasses();
        } catch (IOException exception) {
            LOGGER.error(exception, "IOException occurred: ", exception.getMessage());
            throw new DCMABusinessException("An error occured while trying to deploy process definition",
                    exception);
        }
    } else {
        LOGGER.info("workflow.deploy property is set to false, Process definitions will not be deployed");
    }
}

From source file:de.ingrid.ibus.comm.registry.Registry.java

/**
 * Creates a registry with a given lifetime for IPlugs, a given auto activation value for new IPlugs and a IPlug
 * factory.//from w w w  .  j a v a2s . com
 *
 * @param lifeTimeOfPlugs     Life time of IPlugs. If the last life sign of a IPlug is longer than this value the IPlug is removed.
 * @param iplugAutoActivation The auto activation feature. If this is true all new IPlugs are activated by default otherwise not.
 * @param factory             The factory that creates IPlugs.
 */
public Registry(long lifeTimeOfPlugs, boolean iplugAutoActivation, IPlugProxyFactory factory) {

    ClassPathResource ibusSettings = new ClassPathResource("/activatedIplugs.properties");

    try {
        if (ibusSettings.exists()) {
            this.fFile = ibusSettings.getFile();
        } else {
            File dir = new File("conf");
            if (!dir.exists()) {
                dir.mkdir();
            }
            this.fFile = new File(dir, "activatedIplugs.properties");
            if (!this.fFile.exists()) {
                this.fFile.createNewFile();
            }

        }
    } catch (Exception e) {
        if (fLogger.isErrorEnabled()) {
            fLogger.error("Cannot open the file for saving the activation state of the iplugs.", e);
        }
    }

    loadProperties();
    this.fLifeTime = lifeTimeOfPlugs;
    this.fIplugAutoActivation = iplugAutoActivation;
    this.fProxyFactory = factory;

    // start iplug timeout scanner
    PooledThreadExecutor.getInstance().execute(new RegistryIPlugTimeoutScanner());
}

From source file:com.ephesoft.dcma.workflow.service.common.DeploymentServiceImpl.java

/**
 * This method is used to deploy all batch classes.
 *///from  ww  w.  j ava 2 s. c o  m
@Override
@PostConstruct
public void deployAll() {

    if (!workflowDeploy) {
        return;
    }

    ClassPathResource workflowsClassPathResource = new ClassPathResource(
            WorkFlowConstants.META_INF_DCMA_WORKFLOWS);
    File workflowDirectory = null;
    File newWorkflowFolder = null;
    try {
        // Deploy new plugins here
        workflowDirectory = workflowsClassPathResource.getFile();
        newWorkflowFolder = new File(newWorkflowsBasePath);
        String subDirectoryName = WorkFlowConstants.PLUGINS_CONSTANT;
        LOGGER.info("Deploying new plugins.");
        deployFilesFromWorkflowSubdirectory(newWorkflowFolder, subDirectoryName);
        // workflowDirectory.
        for (String processDefinition : workflowsDefinitionList) {
            NewDeployment deployment = repositoryService.createDeployment();
            deployment.addResourceFromUrl(new ClassPathResource(processDefinition).getURL());

            deployment.deploy();
        }
        // Deploy new Modules followed by new workflows here

        subDirectoryName = WorkFlowConstants.MODULES_CONSTANT;
        LOGGER.info("Deploying new batch class modules.");
        deployFilesFromWorkflowSubdirectory(newWorkflowFolder, subDirectoryName);

        subDirectoryName = WorkFlowConstants.WORKFLOWS_CONSTANT;
        LOGGER.info("Deploying new batch classes.");
        deployFilesFromWorkflowSubdirectory(newWorkflowFolder, subDirectoryName);

    } catch (IOException e) {
        LOGGER.error("IOException occurred: " + ExceptionUtils.getFullStackTrace(e), e);
        throw new DCMABusinessException("An error occured while trying to deploy a process definition", e);
    }

    try {
        File propertyFile = new File(workflowDirectory.getAbsolutePath() + File.separator
                + WorkFlowConstants.DCMA_WORKFLOWS_PROPERTIES);
        Map<String, String> propertyMap = new HashMap<String, String>();
        propertyMap.put(WorkFlowConstants.WORKFLOW_DEPLOY, Boolean.toString(false));

        String comments = "Workflow deploy property changed.";

        FileUtils.updateProperty(propertyFile, propertyMap, comments);

    } catch (IOException e) {
        LOGGER.error("IOException occurred: " + ExceptionUtils.getFullStackTrace(e), e);
        // Continuing without throwing exception.
    }

}