List of usage examples for org.springframework.core.io Resource exists
boolean exists();
From source file:org.opennms.features.vaadin.pmatrix.calculator.PmatrixDpdCalculatorRepository.java
/** * Causes the dataPointMap to be persisted to a file * @param file file definition to persist the data set to * @return true if dataPointMap persisted correctly, false if not *///from w ww. j ava 2 s .c o m public boolean persist() { File currentArchiveFile = null; File tmpCurrentArchiveFile = null; Resource tmpResource = null; if (!persistHistoricData) { LOG.debug("not persisting data as persistHistoricData=false"); return false; } if (archiveFileName == null || archiveFileDirectoryLocation == null) { LOG.error("cannot save historical data to file as incorrect file location:" + " archiveFileDirectoryLocation=" + archiveFileDirectoryLocation + " archiveFileName=" + archiveFileName); return false; } // set the date on which this file was persisted datePersisted = new Date(); // used to get file name suffix SimpleDateFormat dateFormatter = new SimpleDateFormat(dateFormatString); // persist data to temporary file <archiveFileName.tmp> String tmpArchiveFileName = archiveFileName + ".tmp"; String tmpArchiveFileLocation = archiveFileDirectoryLocation + File.separator + tmpArchiveFileName; LOG.debug("historical data will be written to temporary file :" + tmpArchiveFileLocation); try { tmpResource = resourceLoader.getResource(tmpArchiveFileLocation); tmpCurrentArchiveFile = new File(tmpResource.getURL().getFile()); } catch (IOException e) { LOG.error("cannot save historical data to file at archiveFileLocation='" + tmpArchiveFileLocation + "' due to error:", e); return false; } LOG.debug( "persisting historical data to temporary file location:" + tmpCurrentArchiveFile.getAbsolutePath()); // marshal the data PrintWriter writer = null; boolean marshalledCorrectly = false; try { // create directory if doesn't exist File directory = new File(tmpCurrentArchiveFile.getParentFile().getAbsolutePath()); directory.mkdirs(); // create file if doesn't exist writer = new PrintWriter(tmpCurrentArchiveFile, "UTF-8"); writer.close(); // see http://stackoverflow.com/questions/1043109/why-cant-jaxb-find-my-jaxb-index-when-running-inside-apache-felix // need to provide bundles class loader ClassLoader cl = org.opennms.features.vaadin.pmatrix.model.DataPointDefinition.class.getClassLoader(); JAXBContext jaxbContext = JAXBContext.newInstance( "org.opennms.features.vaadin.pmatrix.model:org.opennms.features.vaadin.pmatrix.calculator", cl); //JAXBContext jaxbContext = JAXBContext.newInstance("org.opennms.features.vaadin.pmatrix.model:org.opennms.features.vaadin.pmatrix.calculator"); Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); // TODO CHANGE output pretty printed jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // marshal this Data Repository jaxbMarshaller.marshal(this, tmpCurrentArchiveFile); marshalledCorrectly = true; } catch (JAXBException e) { LOG.error("problem marshalling file: ", e); } catch (Exception e) { LOG.error("problem marshalling file: ", e); } finally { if (writer != null) writer.close(); } if (marshalledCorrectly == false) return false; // marshaling succeeded so rename tmp file String archiveFileLocation = archiveFileDirectoryLocation + File.separator + archiveFileName; LOG.info("historical data will be written to:" + archiveFileLocation); Resource resource = resourceLoader.getResource(archiveFileLocation); if (resource.exists()) { String oldArchiveFileName = archiveFileName + "." + dateFormatter.format(datePersisted); String oldArchiveFileLocation = archiveFileDirectoryLocation + File.separator + oldArchiveFileName; LOG.info("previous historical file at archiveFileLocation='" + archiveFileLocation + "' exists so being renamed to " + oldArchiveFileLocation); Resource oldresource = resourceLoader.getResource(oldArchiveFileLocation); try { currentArchiveFile = new File(resource.getURL().getFile()); File oldArchiveFile = new File(oldresource.getURL().getFile()); // rename current archive file to old archive file name if (!currentArchiveFile.renameTo(oldArchiveFile)) { throw new IOException("cannot rename current archive file:" + currentArchiveFile.getAbsolutePath() + " to " + oldArchiveFile.getAbsolutePath()); } // rename temporary archive file to current archive file name if (!tmpCurrentArchiveFile.renameTo(currentArchiveFile)) { throw new IOException("cannot rename temporary current archive file:" + tmpCurrentArchiveFile.getAbsolutePath() + " to " + currentArchiveFile.getAbsolutePath()); } } catch (IOException e) { LOG.error("Problem archiving old persistance file", e); } // remove excess files try { Resource directoryResource = resourceLoader.getResource(archiveFileDirectoryLocation); File archiveFolder = new File(directoryResource.getURL().getFile()); File[] listOfFiles = archiveFolder.listFiles(); String filename; //this will sort earliest to latest date TreeMap<Date, File> sortedFiles = new TreeMap<Date, File>(); for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile()) { filename = listOfFiles[i].getName(); if ((!filename.equals(archiveFileName)) && (!filename.equals(tmpArchiveFileName)) && (filename.startsWith(archiveFileName))) { String beforeTimeString = archiveFileName + "."; String timeSuffix = filename.substring(beforeTimeString.length()); if (!"".equals(timeSuffix)) { Date fileCreatedate = null; try { fileCreatedate = dateFormatter.parse(timeSuffix); } catch (ParseException e) { LOG.debug("cant parse file name suffix to time for filename:" + filename, e); } if (fileCreatedate != null) { sortedFiles.put(fileCreatedate, listOfFiles[i]); } } } } } while (sortedFiles.size() > archiveFileMaxNumber) { File removeFile = sortedFiles.remove(sortedFiles.firstKey()); LOG.debug("deleting archive file:'" + removeFile.getName() + "' so that number of archive files <=" + archiveFileMaxNumber); removeFile.delete(); } for (File archivedFile : sortedFiles.values()) { LOG.debug("not deleting archive file:'" + archivedFile.getName() + "' so that number of archive files <=" + archiveFileMaxNumber); } return true; } catch (IOException e) { LOG.error("Problem removing old persistance files", e); } } else { // if resource doesn't exist just rename the new tmp file to the archive file name try { currentArchiveFile = new File(resource.getURL().getFile()); // rename temporary archive file to current archive file name if (!tmpCurrentArchiveFile.renameTo(currentArchiveFile)) { throw new IOException("cannot rename temporary current archive file:" + tmpCurrentArchiveFile.getAbsolutePath() + " to " + currentArchiveFile.getAbsolutePath()); } return true; } catch (IOException e) { LOG.error("cannot rename temporary current archive ", e); } } return false; }
From source file:org.jasig.portlet.courses.handler.MobileAwareExceptionHandler.java
@Override protected ModelAndView getModelAndView(String view, Exception ex, PortletRequest request) { boolean isMobile = this.viewSelector.isMobile(request); Resource newView = null; if (isMobile) { try {/* w ww . jav a2s.c o m*/ String mobileViewPath = this.prefix + view + this.mobileSuffix + this.suffix; logger.debug("Looking for mobile friendly Exception view: " + mobileViewPath); newView = resourceLoader.getResource(mobileViewPath); } catch (Exception e) { // No view, eat the exception logger.debug("No mobile view for: " + view, e); } } ModelAndView mav; if (newView != null && newView.exists()) { mav = super.getModelAndView(view + this.mobileSuffix, ex, request); } else { mav = super.getModelAndView(view, ex, request); } mav.getModelMap().put("isMobile", isMobile); if (logger.isDebugEnabled()) logger.debug("Accessing getSelectedTerm from Request/Session"); Term selectedTerm = getSelectedTerm(request); mav.getModelMap().put("selectedTerm", selectedTerm); return mav; }
From source file:com.github.zhanhb.ckfinder.connector.support.XmlConfigurationParser.java
/** * Gets absolute path to XML configuration file. * * @param resourceLoader resource loader to load xml configuration and * watermark resource/*from ww w. j a v a 2s. com*/ * @param xmlFilePath string representation of the xml file * @return absolute path to XML configuration file * @throws ConnectorException when absolute path cannot be obtained. */ private Resource getFullConfigPath(ResourceLoader resourceLoader, String xmlFilePath) throws ConnectorException { Resource resource = resourceLoader.getResource(xmlFilePath); if (!resource.exists()) { throw new ConnectorException(ErrorCode.FILE_NOT_FOUND, "Configuration file could not be found under specified location."); } return resource; }
From source file:fr.acxio.tools.agia.tasks.FilesOperationTaskletTest.java
@Test public void testExecuteRemove() throws Exception { FileUtils.copyFile(new File("src/test/resources/testFiles/input.csv"), new File("target/CP-input.csv")); FilesOperationTasklet aTasklet = new FilesOperationTasklet(); ResourcesFactory aSourceFactory = mock(ResourcesFactory.class); Resource aFileResource1 = mock(Resource.class); when(aFileResource1.getFile()).thenReturn(new File("target/CP-input.csv")); when(aFileResource1.exists()).thenReturn(true); when(aSourceFactory.getResources(anyMapOf(Object.class, Object.class))) .thenReturn(new Resource[] { aFileResource1 }); aTasklet.setSourceFactory(aSourceFactory); aTasklet.setOperation(Operation.REMOVE); aTasklet.afterPropertiesSet();/* www . ja v a 2s . c o m*/ StepContribution aStepContribution = mock(StepContribution.class); assertEquals(RepeatStatus.FINISHED, aTasklet.execute(aStepContribution, null)); verify(aStepContribution, times(1)).incrementReadCount(); verify(aStepContribution, times(1)).incrementWriteCount(1); assertFalse(aFileResource1.getFile().exists()); }
From source file:fr.acxio.tools.agia.tasks.FilesOperationTaskletTest.java
@Test public void testExecuteCopyEmptySource() throws Exception { FilesOperationTasklet aTasklet = new FilesOperationTasklet(); ResourcesFactory aSourceFactory = mock(ResourcesFactory.class); when(aSourceFactory.getResources(anyMapOf(Object.class, Object.class))).thenReturn(new Resource[] {}); ResourceFactory aDestinationFactory = mock(ResourceFactory.class); Resource aDestResource = mock(Resource.class); when(aDestResource.getFile()).thenReturn(new File("target/CP-input.csv")); when(aDestResource.exists()).thenReturn(false); Resource aRelativeResource = mock(Resource.class); when(aRelativeResource.getFile()).thenReturn(new File("target")); when(aDestResource.createRelative("/.")).thenReturn(aRelativeResource); when(aDestinationFactory.getResource(anyMapOf(Object.class, Object.class))).thenReturn(aDestResource); assertFalse(aDestResource.getFile().exists()); aTasklet.setSourceFactory(aSourceFactory); aTasklet.setDestinationFactory(aDestinationFactory); aTasklet.setOperation(Operation.COPY); aTasklet.afterPropertiesSet();/*w ww . jav a2 s . c om*/ assertEquals(RepeatStatus.FINISHED, aTasklet.execute(null, null)); assertFalse(aDestResource.getFile().exists()); }
From source file:fr.acxio.tools.agia.tasks.FilesOperationTaskletTest.java
@Test public void testExecuteMove() throws Exception { FileUtils.copyFile(new File("src/test/resources/testFiles/input.csv"), new File("target/CP-input.csv")); FilesOperationTasklet aTasklet = new FilesOperationTasklet(); ResourcesFactory aSourceFactory = mock(ResourcesFactory.class); Resource aFileResource1 = mock(Resource.class); when(aFileResource1.getFile()).thenReturn(new File("target/CP-input.csv")); when(aFileResource1.exists()).thenReturn(true); when(aSourceFactory.getResources(anyMapOf(Object.class, Object.class))) .thenReturn(new Resource[] { aFileResource1 }); ResourceFactory aDestinationFactory = mock(ResourceFactory.class); Resource aDestResource = mock(Resource.class); when(aDestResource.getFile()).thenReturn(new File("target/MV-input.csv")); when(aDestResource.exists()).thenReturn(false); Resource aRelativeResource = mock(Resource.class); when(aRelativeResource.getFile()).thenReturn(new File("target")); when(aDestResource.createRelative("/.")).thenReturn(aRelativeResource); when(aDestinationFactory.getResource(anyMapOf(Object.class, Object.class))).thenReturn(aDestResource); assertFalse(aDestResource.getFile().exists()); aTasklet.setSourceFactory(aSourceFactory); aTasklet.setDestinationFactory(aDestinationFactory); aTasklet.setOperation(Operation.MOVE); aTasklet.afterPropertiesSet();// w w w . j a v a2 s .c o m StepContribution aStepContribution = mock(StepContribution.class); assertEquals(RepeatStatus.FINISHED, aTasklet.execute(aStepContribution, null)); verify(aStepContribution, times(1)).incrementReadCount(); verify(aStepContribution, times(1)).incrementWriteCount(1); assertTrue(aDestResource.getFile().exists()); assertFalse(aFileResource1.getFile().exists()); }
From source file:com.thoughtworks.go.http.mocks.MockServletContext.java
@Override public InputStream getResourceAsStream(String path) { Resource resource = this.resourceLoader.getResource(getResourceLocation(path)); if (!resource.exists()) { return null; }/*from w ww . java 2s . c om*/ try { return resource.getInputStream(); } catch (IOException ex) { logger.warn("Couldn't open InputStream for " + resource, ex); return null; } }
From source file:fr.acxio.tools.agia.tasks.FilesOperationTaskletTest.java
@Test public void testExecuteMoveToDir() throws Exception { FileUtils.forceMkdir(new File("target/CP-testfiles")); FileUtils.copyFile(new File("src/test/resources/testFiles/input.csv"), new File("target/CP-input.csv")); FilesOperationTasklet aTasklet = new FilesOperationTasklet(); ResourcesFactory aSourceFactory = mock(ResourcesFactory.class); Resource aFileResource1 = mock(Resource.class); when(aFileResource1.getFile()).thenReturn(new File("target/CP-input.csv")); when(aFileResource1.exists()).thenReturn(true); when(aSourceFactory.getResources(anyMapOf(Object.class, Object.class))) .thenReturn(new Resource[] { aFileResource1 }); ResourceFactory aDestinationFactory = mock(ResourceFactory.class); Resource aDestResource = mock(Resource.class); when(aDestResource.getFile()).thenReturn(new File("target/CP-testfiles/")); when(aDestResource.exists()).thenReturn(true); Resource aRelativeResource = mock(Resource.class); when(aRelativeResource.getFile()).thenReturn(new File("target/CP-testfiles/")); when(aDestResource.createRelative("/.")).thenReturn(aRelativeResource); when(aDestinationFactory.getResource(anyMapOf(Object.class, Object.class))).thenReturn(aDestResource); assertEquals(0, aDestResource.getFile().list().length); aTasklet.setSourceFactory(aSourceFactory); aTasklet.setDestinationFactory(aDestinationFactory); aTasklet.setOperation(Operation.MOVE); aTasklet.afterPropertiesSet();//from ww w .j ava 2 s. co m StepContribution aStepContribution = mock(StepContribution.class); assertEquals(RepeatStatus.FINISHED, aTasklet.execute(aStepContribution, null)); verify(aStepContribution, times(1)).incrementReadCount(); verify(aStepContribution, times(1)).incrementWriteCount(1); assertTrue(aDestResource.getFile().exists()); assertFalse(aFileResource1.getFile().exists()); assertEquals("CP-input.csv", aDestResource.getFile().list()[0]); }