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

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

Introduction

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

Prototype

File getFile() throws IOException;

Source Link

Document

Return a File handle for this resource.

Usage

From source file:org.kemri.wellcome.controller.Dhis2ServerController.java

@RequestMapping(value = Views.DB_CONFIGURE, method = RequestMethod.GET)
public String configDatabase(HttpServletRequest request, Model model) {
    DatabaseProperties dbProperties = new DatabaseProperties();
    try {//from   w w w .j a  v a  2 s  . c  o m
        Properties prop = new Properties();
        //load a properties file
        ServletContext servletContext = request.getSession().getServletContext();
        Resource resource = new ServletContextResource(servletContext, databaseProperties);
        prop.load(new FileInputStream(resource.getFile()));

        //get the property value and print it out
        String removeProtocol = prop.getProperty("jdbc.url").replace("jdbc:mysql://", ""); /* localhost:3306/ */
        String databaseUrl = removeProtocol.substring(0, removeProtocol.indexOf(":"));
        String databaseName = removeProtocol.substring(removeProtocol.indexOf("/"));
        dbProperties.setDatabaseUrl(databaseUrl);
        dbProperties.setDatabaseName(databaseName);
        dbProperties.setUsername(prop.getProperty("jdbc.username"));
        dbProperties.setPassword(prop.getProperty("jdbc.password"));
        model.addAttribute("dbProperties", dbProperties);

    } catch (IOException e) {
        model.addAttribute("error", e.getMessage());
        e.printStackTrace();
        log.error("\n " + e.getMessage() + "\n");
    }
    return Views.DB_CONFIGURE;
}

From source file:com.wavemaker.tools.project.LocalStudioFileSystem.java

@Override
public String getPath(Resource resource) {
    try {//from w w w.j av  a 2 s.com
        String path = StringUtils.cleanPath(resource.getFile().getPath());
        if (resource.getFile().isDirectory() && !path.endsWith("/")) {
            path += "/";
        }
        return path;
    } catch (IOException ex) {
        throw new WMRuntimeException(ex);
    }
}

From source file:com.impetus.ankush.common.controller.listener.StartupListener.java

/**
 * Method to set ankush conf reader and ankush properties.
 * //from w w w.  j a  v  a  2s .  c o m
 */
private void setAnkushConfigurator() {
    try {
        // Setting configuration reader.
        Resource resource = new ClassPathResource("/ankush_constants.xml");
        ConfigurationReader ankushConfReader = new ConfigurationReader(resource.getFile().getAbsolutePath());
        if (ankushConfReader != null) {
            AppStoreWrapper.setAnkushConfReader(ankushConfReader);
        }
    } catch (Exception e) {
        log.debug("Unable to set Configuration Reader or properties reader in Singletone Store.");
    }
}

From source file:fr.acxio.tools.agia.io.AbstractFileOperations.java

protected List<String> doOperation(Resource aSourceResource, Map<String, Object> aDestinationParams,
        StepContribution sContribution, StepExecution sStepExecution)
        throws IOException, ResourceCreationException, FileOperationException {

    List<String> aDestinationFilesList = new ArrayList<String>();

    File aOriginFile = aSourceResource.getFile();
    if (aOriginFile.exists()) {
        if (sContribution != null) {
            sContribution.incrementReadCount();
        }/*from  ww w.  ja  v a  2s  .c  om*/

        if (operation == Operation.REMOVE) {

            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("Deleting : {}", aOriginFile.getAbsolutePath());
            }

            removeFile(aSourceResource);
        } else {
            Resource aDestination = getDefaultDestination();
            if (destinationFactory != null) {
                aDestinationParams.put(ResourceFactoryConstants.PARAM_SOURCE, aSourceResource);
                aDestinationParams.put(ResourceFactoryConstants.PARAM_STEP_EXEC, sStepExecution);
                aDestination = destinationFactory.getResource(aDestinationParams);
            }
            if ((aDestination != null) && (aDestination.getFile() != null)) {
                File aDestinationFile = aDestination.getFile();
                if (operation == Operation.COPY) {

                    if (LOGGER.isInfoEnabled()) {
                        LOGGER.info("Copying : {} => {}", aOriginFile.getAbsolutePath(),
                                aDestinationFile.getAbsolutePath());
                    }

                    copyFile(aSourceResource, aDestination);
                } else if (operation == Operation.MOVE) {

                    if (LOGGER.isInfoEnabled()) {
                        LOGGER.info("Moving : {} => {}", aOriginFile.getAbsolutePath(),
                                aDestinationFile.getAbsolutePath());
                    }

                    moveFile(aSourceResource, aDestination);
                } else {
                    throw new FileOperationException("Unknown operation");
                }
            } else {
                throw new FileOperationException("No destination specified");
            }
            aDestinationFilesList.add(aDestination.getFile().getCanonicalPath());
        }

        if (sContribution != null) {
            sContribution.incrementWriteCount(1);
        }
    } else {
        throw new FileOperationException("File not found: " + aOriginFile);
    }

    return aDestinationFilesList;
}

From source file:com.wavemaker.tools.project.LocalStudioFileSystem.java

@Override
protected void makeDirectories(Resource projectsDir) throws FileAccessException, IOException {
    IOUtils.makeDirectories(projectsDir.getFile(), getWaveMakerHome().getFile());
}

From source file:com.gzj.tulip.jade.context.spring.JadeBeanFactoryPostProcessor.java

private List<String> findJadeResources(final List<ResourceRef> resources) {
    List<String> urls = new LinkedList<String>();
    for (ResourceRef ref : resources) {
        if (ref.hasModifier("dao") || ref.hasModifier("DAO")) {
            try {
                Resource resource = ref.getResource();
                File resourceFile = resource.getFile();
                if (resourceFile.isFile()) {
                    urls.add("jar:file:" + resourceFile.toURI().getPath() + ResourceUtils.JAR_URL_SEPARATOR);
                } else if (resourceFile.isDirectory()) {
                    urls.add(resourceFile.toURI().toString());
                }/*from  w  ww.  j ava2  s  . c  om*/
            } catch (IOException e) {
                throw new ApplicationContextException("error on resource.getFile", e);
            }
        }
    }
    if (logger.isInfoEnabled()) {
        logger.info("[jade] found " + urls.size() + " jade urls: " + urls);
    }
    return urls;
}

From source file:com.netflix.genie.web.resources.handlers.GenieResourceHttpRequestHandlerUnitTests.java

/**
 * Make sure if the resource is a directory as HTML it's handled properly.
 *
 * @throws Exception On any error//from   w  w w  .j a v  a 2  s  .  c  om
 */
@Test
public void canHandleRequestForDirectoryHtml() throws Exception {
    final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    final HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
    final String path = UUID.randomUUID().toString();
    Mockito.when(request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).thenReturn(path);
    Mockito.when(request.getHeader(HttpHeaders.ACCEPT)).thenReturn(MediaType.TEXT_HTML_VALUE);
    final String forwardedUrl = UUID.randomUUID().toString();
    Mockito.when(request.getHeader(JobConstants.GENIE_FORWARDED_FROM_HEADER)).thenReturn(forwardedUrl);
    final Resource resource = Mockito.mock(Resource.class);
    Mockito.when(this.location.createRelative(Mockito.eq(path))).thenReturn(resource);
    Mockito.when(resource.exists()).thenReturn(true);
    final File file = Mockito.mock(File.class);
    Mockito.when(resource.getFile()).thenReturn(file);
    Mockito.when(file.isDirectory()).thenReturn(true);

    final String html = UUID.randomUUID().toString();

    Mockito.when(this.directoryWriter.toHtml(Mockito.eq(file), Mockito.eq(forwardedUrl), Mockito.eq(false)))
            .thenReturn(html);

    final ServletOutputStream os = Mockito.mock(ServletOutputStream.class);
    Mockito.when(response.getOutputStream()).thenReturn(os);

    this.handler.handleRequest(request, response);

    Mockito.verify(response, Mockito.times(1)).setContentType(MediaType.TEXT_HTML_VALUE);
    Mockito.verify(response, Mockito.times(1)).getOutputStream();
    Mockito.verify(this.directoryWriter, Mockito.times(1)).toHtml(Mockito.eq(file), Mockito.eq(forwardedUrl),
            Mockito.eq(false));
    Mockito.verify(os, Mockito.times(1)).write(html.getBytes(Charset.forName("UTF-8")));
}

From source file:com.netflix.genie.web.resources.handlers.GenieResourceHttpRequestHandlerUnitTests.java

/**
 * Make sure if the resource is a directory as JSON it's handled properly.
 *
 * @throws Exception On any error/*from ww  w . j ava  2  s .c  o  m*/
 */
@Test
public void canHandleRequestForDirectoryJson() throws Exception {
    final HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    final HttpServletResponse response = Mockito.mock(HttpServletResponse.class);
    final String path = UUID.randomUUID().toString();
    Mockito.when(request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)).thenReturn(path);
    Mockito.when(request.getHeader(HttpHeaders.ACCEPT)).thenReturn(null);
    final String requestUrl = UUID.randomUUID().toString();
    Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer(requestUrl));
    final Resource resource = Mockito.mock(Resource.class);
    Mockito.when(this.location.createRelative(Mockito.eq(path))).thenReturn(resource);
    Mockito.when(resource.exists()).thenReturn(true);
    final File file = Mockito.mock(File.class);
    Mockito.when(resource.getFile()).thenReturn(file);
    Mockito.when(file.isDirectory()).thenReturn(true);

    final String html = UUID.randomUUID().toString();

    Mockito.when(this.directoryWriter.toJson(Mockito.eq(file), Mockito.eq(requestUrl), Mockito.eq(false)))
            .thenReturn(html);

    final ServletOutputStream os = Mockito.mock(ServletOutputStream.class);
    Mockito.when(response.getOutputStream()).thenReturn(os);

    this.handler.handleRequest(request, response);

    Mockito.verify(response, Mockito.times(1)).setContentType(MediaType.APPLICATION_JSON_VALUE);
    Mockito.verify(response, Mockito.times(1)).getOutputStream();
    Mockito.verify(this.directoryWriter, Mockito.times(1)).toJson(Mockito.eq(file), Mockito.eq(requestUrl),
            Mockito.eq(false));
    Mockito.verify(os, Mockito.times(1)).write(html.getBytes(Charset.forName("UTF-8")));
}

From source file:com.edgenius.wiki.service.impl.SystemPropertyPlaceholderConfigurer.java

/**
 * Loading global content from Global configure xml file (defined by geniuswiki.properties), then
 * push all value to <code>com.edgenius.core.Global</code> class, which value become static and ready for 
 * later use. //from  w  w w  .  jav  a 2s  .  c  o m
 *
 * There 3 level global setting. First, server.properties will assign a global.xml, this file usually is outside
 * the deploy file, and put together with data file, this is makes upgrade easily. <br>
 * Second, there is global.default.xml is inside classpath. This file is useful when installer initialized setup 
 * system. see publish process.<br>
 * Third, if both above file not exist, Global.java even has its default value. and it also will automatically generate
 * global.xml in this case. <br>
 * @param globalConf 
 *   
 */
private void initGlobal(Resource globalConf) {
    GlobalSetting setting = null;
    try {
        //http://forum.springframework.org/showthread.php?p=201562#post201562
        //don't use Resource.getInputStream() as it can not handle file://c:/var/data format: error is try to get unknown host "c"
        setting = GlobalSetting.loadGlobalSetting(new FileInputStream(globalConf.getFile()));
    } catch (Exception e) {
        log.info("Unable to load global xml, try load global default xml then...");
        setting = null;
    }
    if (setting == null) {
        //try to load global.default.xml from class path.
        try {
            setting = GlobalSetting.loadGlobalSetting(FileUtil.getFileInputStream(Global.DEFAULT_GLOBAL_XML));
        } catch (Exception e) {
            log.warn("Loading global default xml failed, using Global class default instead.");
        }
        if (setting == null) {
            //the third option, just use Global.java value
            //no global file found, so keep Global default static value instead.
            setting = new GlobalSetting();
            Global.syncTo(setting);
        }

        if (globalConf.exists()) {
            //global exist, maybe wrong format, then try to backup original one
            try {
                String dir = FileUtil.getFileDirectory(globalConf.getFile().getAbsolutePath());
                String name = globalConf.getFilename() + "."
                        + new SimpleDateFormat("yyyyMMdd").format(new Date()) + ".failure.backup";
                File orig = new File(FileUtil.getFullPath(dir, name));
                FileUtils.copyFile(globalConf.getFile(), orig);
                log.info("Original global conf file rename to " + name);
            } catch (Exception e) {
                log.warn("Unable backup original global conf file, old one will replaced.");
            }
        }
        //Anyway, global.xml file under data root is missed or crashed, then create or recreate required.
        //As I want to user SettingService.saveOrUpdateGlobalSetting() to save rather than create duplicated code,
        //so here a little bit tricky,  I put a flag value to tell SettingService trigger saving in afterProperties()
        log.info("System is going to create/recreate new global.xml in your data root directory.");
        System.setProperty("rebuild.global.xml", "true");

    }

    //finally, initial Global static varible according to setting
    Global.syncFrom(setting);
}

From source file:com.wavemaker.tools.project.LocalStudioFileSystem.java

@Override
public Resource copyRecursive(Resource root, Resource target, List<String> exclusions) {
    try {/* w  w w. j a v  a 2 s.c  o  m*/
        IOUtils.copy(root.getFile(), target.getFile(), exclusions);
    } catch (IOException ex) {
        throw new WMRuntimeException(ex);
    }
    return target;
}