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

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

Introduction

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

Prototype

boolean exists();

Source Link

Document

Determine whether this resource actually exists in physical form.

Usage

From source file:de.codecentric.batch.web.JobOperationsController.java

@RequestMapping(value = "/jobs/{jobName}", method = RequestMethod.POST)
public String launch(@PathVariable String jobName, @RequestParam MultiValueMap<String, String> payload)
        throws NoSuchJobException, JobParametersInvalidException, JobExecutionAlreadyRunningException,
        JobRestartException, JobInstanceAlreadyCompleteException, JobParametersNotFoundException {
    String parameters = payload.getFirst(JOB_PARAMETERS);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Attempt to start job with name " + jobName + " and parameters " + parameters + ".");
    }/*w w  w. jav  a  2 s .  c o  m*/
    try {
        Job job = jobRegistry.getJob(jobName);
        JobParameters jobParameters = createJobParametersWithIncrementerIfAvailable(parameters, job);
        Long id = jobLauncher.run(job, jobParameters).getId();
        return String.valueOf(id);
    } catch (NoSuchJobException e) {
        // Job hasn't been found in normal context, so let's check if there's a JSR-352 job.
        String jobConfigurationLocation = "/META-INF/batch-jobs/" + jobName + ".xml";
        Resource jobXml = new ClassPathResource(jobConfigurationLocation);
        if (!jobXml.exists()) {
            throw e;
        } else {
            Long id = jsrJobOperator.start(jobName, PropertiesConverter.stringToProperties(parameters));
            return String.valueOf(id);
        }
    }
}

From source file:it.scoppelletti.programmerpower.web.rest.ResourceLoaderServerResource.java

/**
 * Restituisce il flusso di lettura della risorsa.
 * /* w  w  w  .  ja  va2 s  . c  o m*/
 * @return Rappresentazione.
 */
@Get
public Representation getResource() throws ResourceException {
    InputStream in = null;
    Resource res;
    List<String> locations;
    IOResources ioRes = new IOResources();

    locations = ResourceUtils.listCandidateLocalizedResourceLocations(myLocation, getLocale());
    for (String loc : locations) {
        res = myResLoader.getResource(loc);
        if (!res.exists()) {
            continue;
        }

        try {
            in = res.getInputStream();
        } catch (Exception ex) {
            throw new ResourceException(Status.SERVER_ERROR_INTERNAL, ex.getMessage(), ex);
        }
        break;
    }

    if (in == null) {
        if (testFlag(ResourceLoaderServerResource.QUERY_STRICT)) {
            throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, ioRes.getFileFoundMessage(myLocation));
        } else {
            return new EmptyRepresentation();
        }
    }

    return new InputRepresentation(in);
}

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

/**
 * Make sure if the resource doesn't exist we return a 404.
 *
 * @throws ServletException On any error
 * @throws IOException      On any error
 *//*from  w ww. ja  v  a  2  s.c  o m*/
@Test
public void cantHandleRequestIfResourceDoesntExist() throws ServletException, IOException {
    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);
    final Resource resource = Mockito.mock(Resource.class);
    Mockito.when(this.location.createRelative(Mockito.eq(path))).thenReturn(resource);
    Mockito.when(resource.exists()).thenReturn(false);

    this.handler.handleRequest(request, response);

    Mockito.verify(response, Mockito.times(1)).sendError(HttpStatus.NOT_FOUND.value());
}

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

/**
 * Make sure if the resource isn't a directory it's sent to super.
 * <p>// w w  w.  ja v a2s .  c o m
 * Note: This doesn't actually test returning a file as we leverage Spring's implementation
 * which we assume is working.
 *
 * @throws ServletException On any error
 * @throws IOException      On any error
 */
@Test
public void canHandleRequestForFile() throws ServletException, IOException {
    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);
    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(false);

    this.handler.handleRequest(request, response);

    Mockito.verify(response, Mockito.times(1)).sendError(HttpStatus.NOT_FOUND.value());
}

From source file:org.codehaus.grails.struts.action.ServletContextWrapper.java

public InputStream getResourceAsStream(String name) {
    if (!application.isWarDeployed() && name.equals("/WEB-INF/web.xml")) {
        BuildSettings settings = BuildSettingsHolder.getSettings();
        try {/*from w ww  .j a  v  a2 s.  c o  m*/
            Resource resource = new FileSystemResource(
                    settings.getResourcesDir().getAbsolutePath() + "/web.xml");
            if (resource.exists()) {
                return resource.getInputStream();
            } else {
                return null;
            }
        } catch (IOException e) {
            adaptee.log(e.getMessage(), e);
            return null;
        }

    } else {
        return adaptee.getResourceAsStream(name);
    }
}

From source file:fr.acxio.tools.agia.tasks.ZipFilesTasklet.java

protected void zipResource(Resource sSourceResource, ZipArchiveOutputStream sZipArchiveOutputStream,
        StepContribution sContribution, ChunkContext sChunkContext) throws IOException, ZipFilesException {
    // TODO : use a queue to reduce the callstack overhead
    if (sSourceResource.exists()) {
        File aSourceFile = sSourceResource.getFile();
        String aSourcePath = aSourceFile.getCanonicalPath();

        if (!aSourcePath.startsWith(sourceBaseDirectoryPath)) {
            throw new ZipFilesException(
                    "Source file " + aSourcePath + " does not match base directory " + sourceBaseDirectoryPath);
        }/*from   w  ww .  j  a v  a  2  s. co  m*/

        if (sContribution != null) {
            sContribution.incrementReadCount();
        }
        String aZipEntryName = aSourcePath.substring(sourceBaseDirectoryPath.length() + 1);
        sZipArchiveOutputStream.putArchiveEntry(new ZipArchiveEntry(aZipEntryName));
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Zipping {} to {}", sSourceResource.getFile().getCanonicalPath(), aZipEntryName);
        }
        if (aSourceFile.isFile()) {
            InputStream aInputStream = sSourceResource.getInputStream();
            IOUtils.copy(aInputStream, sZipArchiveOutputStream);
            aInputStream.close();
            sZipArchiveOutputStream.closeArchiveEntry();
        } else {
            sZipArchiveOutputStream.closeArchiveEntry();
            for (File aFile : aSourceFile
                    .listFiles((FileFilter) (recursive ? TrueFileFilter.TRUE : FileFileFilter.FILE))) {
                zipResource(new FileSystemResource(aFile), sZipArchiveOutputStream, sContribution,
                        sChunkContext);
            }
        }
        if (sContribution != null) {
            sContribution.incrementWriteCount(1);
        }
    } else if (LOGGER.isInfoEnabled()) {
        LOGGER.info("{} does not exist", sSourceResource.getFilename());
    }
}

From source file:com.haulmont.cuba.gui.config.MenuConfig.java

protected void init() {
    rootItems.clear();/*  w w  w.  ja va2  s  .  c  o  m*/

    String configName = AppContext.getProperty(MENU_CONFIG_XML_PROP);

    StrTokenizer tokenizer = new StrTokenizer(configName);
    for (String location : tokenizer.getTokenArray()) {
        Resource resource = resources.getResource(location);
        if (resource.exists()) {
            InputStream stream = null;
            try {
                stream = resource.getInputStream();
                Element rootElement = Dom4j.readDocument(stream).getRootElement();
                loadMenuItems(rootElement, null);
            } catch (IOException e) {
                throw new RuntimeException("Unable to read menu config", e);
            } finally {
                IOUtils.closeQuietly(stream);
            }
        } else {
            log.warn("Resource {} not found, ignore it", location);
        }
    }
}

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

/**
 * Make sure if the resource is a directory it's handled properly until exception thrown.
 *
 * @throws Exception On any error//  ww  w  .  j  a va2  s  . c o m
 */
@Test(expected = ServletException.class)
public void cantHandleRequestForDirectoryWhenException() 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.getAttribute(GenieResourceHttpRequestHandler.GENIE_JOB_IS_ROOT_DIRECTORY))
            .thenReturn(false);
    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);

    Mockito.when(this.directoryWriter.toHtml(Mockito.eq(file), Mockito.eq(requestUrl), Mockito.eq(true)))
            .thenThrow(new Exception());

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

    this.handler.handleRequest(request, response);
}

From source file:architecture.ee.component.core.lifecycle.RepositoryImpl.java

public void setServletContext(ServletContext servletContext) {

    // 1.  ?? ? ? ?  : ARCHITECTURE_INSTALL_ROOT
    String value = servletContext.getInitParameter(ApplicationConstants.ARCHITECTURE_PROFILE_ROOT_ENV_KEY);
    if (!StringUtils.isEmpty(value)) {
        try {//from   w w  w.ja  v  a2 s  . c o m
            ServletContextResourceLoader servletResoruceLoader = new ServletContextResourceLoader(
                    servletContext);
            Resource resource = servletResoruceLoader.getResource(value);
            if (resource.exists()) {
                log.debug(L10NUtils.format("003003", ApplicationConstants.ARCHITECTURE_PROFILE_ROOT_ENV_KEY,
                        resource.getURI()));
                this.rootResource = resource;
                setState(State.INITIALIZED);
                initailized = true;
            }
        } catch (Throwable e) {
            this.rootResource = null;
        }
    }

    if (!initailized && !StringUtils.isEmpty(value)) {
        Resource obj;
        try {
            obj = resoruceLoader.getResource(value);
            if (obj.exists()) {
                log.debug(L10NUtils.format("003003", ApplicationConstants.ARCHITECTURE_PROFILE_ROOT_ENV_KEY,
                        obj.getURI()));
                this.rootResource = obj;
                setState(State.INITIALIZED);
                initailized = true;

            }
        } catch (Throwable e) {
            log.error(e);
        }
    }

    if (!initailized) {
        try {
            ServletContextResource resource = new ServletContextResource(servletContext, "/WEB-INF");
            File file = resource.getFile();
            if (file.exists()) {
                this.rootResource = new FileSystemResource(file);
                setState(State.INITIALIZED);
                initailized = true;
            }
        } catch (Throwable e) {
            log.error(e);
        }
    }
}