List of usage examples for org.springframework.core.io Resource getURL
URL getURL() throws IOException;
From source file:org.globus.security.stores.ResourceSecurityWrapperStore.java
private boolean load(Resource resource, Set<V> currentRoots, Map<String, T> newWrapperMap) throws ResourceStoreException { if (!resource.isReadable()) { throw new ResourceStoreException("Cannot read file"); }/*from w w w .j av a 2 s. c o m*/ try { if (resource.getFile().isDirectory()) { File directory = resource.getFile(); currentRoots.addAll(addCredentials(directory)); return true; } } catch (IOException e) { // This is ok, it just means the resource is not a // filesystemresources logger.log(Level.FINE, "Not a filesystem resource", e); } try { String resourceUri = resource.getURL().toExternalForm(); T fbo = this.wrapperMap.get(resourceUri); if (fbo == null) { fbo = create(resource); } V target = fbo.create(resource); newWrapperMap.put(resourceUri, fbo); currentRoots.add(target); return true; } catch (IOException e) { throw new ResourceStoreException(e); } }
From source file:org.cleverbus.core.common.version.impl.ManifestVersionInfoSource.java
private Collection<VersionInfo> getVersionData(String location, @Nullable VersionInfo filter) throws IOException, PatternSyntaxException { Collection<VersionInfo> result = new ArrayList<VersionInfo>(); Resource[] resources = applicationContext.getResources(location); for (Resource resource : resources) { try {/*from w w w . j a v a2 s . c o m*/ InputStream is = resource.getInputStream(); if (is != null) { Manifest manifest = new Manifest(is); VersionInfo info = createVersionInfo(manifest); // Log.debug(location + ": " + info); // Version entries may be empty or incomplete. // Return only entries that match the specified filter. if (info.matches(filter)) { result.add(info); } } } catch (IOException e) { Log.error("Unable to process manifest resource '{}'", e, resource.getURL()); throw e; } catch (PatternSyntaxException e) { Log.error("Unable to process version data, invalid filter '{}'", e, filter.toString()); } } return result; }
From source file:org.eclipse.gemini.blueprint.test.AbstractOsgiTests.java
/** * Installs an OSGi bundle from the given location. * /* w ww .j av a 2 s . com*/ * @param location * @return * @throws Exception */ private Bundle installBundle(Resource location) throws Exception { Assert.notNull(platformContext, "the OSGi platform is not set"); Assert.notNull(location, "cannot install from a null location"); if (logger.isDebugEnabled()) logger.debug("Installing bundle from location " + location.getDescription()); String bundleLocation; try { bundleLocation = URLDecoder.decode(location.getURL().toExternalForm(), UTF_8_CHARSET); } catch (Exception ex) { // the URL cannot be created, fall back to the description bundleLocation = location.getDescription(); } return platformContext.installBundle(bundleLocation, location.getInputStream()); }
From source file:gov.nih.nci.cabig.caaers2adeers.xslt.CustomXsltComponent.java
private void loadResource(XsltBuilder xslt, Resource resource) throws TransformerConfigurationException { log.debug("Loading resource by :" + this + " , resource : " + resource); try {//from w ww . j a va 2 s . co m if (resource instanceof UrlResource) { // prefer to use file when a file based url File file = resource.getFile(); if (file != null) { // check if the file exists and report a better error as the XSLT // will just say it cannot compile the stylesheet file if (!file.exists()) { throw new FileNotFoundException("File: " + file + " not found."); } xslt.setTransformerFile(file); } else { xslt.setTransformerURL(resource.getURL()); } } else { // fallback and use input stream xslt.setTransformerInputStream(resource.getInputStream()); } } catch (Exception e) { // include information about the resource in the caused exception, so its easier for // end users to know which resource failed throw new TransformerConfigurationException(e.getMessage() + " " + resource.toString(), e); } }
From source file:com.javaetmoi.core.spring.vfs.Vfs2ResourceHttpRequestHandler.java
@Override public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { checkAndPrepare(request, response, true); // check whether a matching resource exists Resource resource = getResource(request); if (resource == null) { logger.debug("No matching resource found - returning 404"); response.sendError(HttpServletResponse.SC_NOT_FOUND); return;/*from w w w. ja v a 2 s .co m*/ } // check the resource's media type MediaType mediaType = getMediaType(resource); if (mediaType != null) { if (logger.isDebugEnabled()) { logger.debug("Determined media type '" + mediaType + "' for " + resource); } } else { if (logger.isDebugEnabled()) { logger.debug("No media type found for " + resource + " - not sending a content-type header"); } } // header phase // Use a Vfs2Resource when asset are probided by the JBoss 5 Virtaul File System URL url = resource.getURL(); if (url.getProtocol().startsWith(ResourceUtils.URL_PROTOCOL_VFS)) { resource = new Vfs2Resource(Vfs2Utils.getRoot(url)); } if (new ServletWebRequest(request, response).checkNotModified(resource.lastModified())) { logger.debug("Resource not modified - returning 304"); return; } setHeaders(response, resource, mediaType); // content phase if (METHOD_HEAD.equals(request.getMethod())) { logger.trace("HEAD request - skipping content"); return; } writeContent(response, resource); }
From source file:org.brekka.stillingar.spring.config.ConfigurationServiceBeanDefinitionParser.java
/** * @param element// w ww . ja v a2 s . c om * @param builder */ protected void prepareJAXB(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { Element jaxbElement = selectSingleChildElement(element, "jaxb", false); // Path String contextPath = jaxbElement.getAttribute("context-path"); builder.addConstructorArgValue(contextPath); // Schemas List<Element> schemaElementList = selectChildElements(jaxbElement, "schema"); ManagedList<URL> schemaUrlList = new ManagedList<URL>(schemaElementList.size()); for (Element schemaElement : schemaElementList) { String schemaPath = schemaElement.getTextContent(); try { Resource resource = parserContext.getReaderContext().getResourceLoader().getResource(schemaPath); schemaUrlList.add(resource.getURL()); } catch (IOException e) { throw new ConfigurationException(String.format("Failed to parse schema location '%s'", schemaPath), e); } } builder.addConstructorArgValue(schemaUrlList); // Namespaces builder.addConstructorArgReference(this.namespacesId); // ConversionManager builder.addConstructorArgValue(prepareJAXBConversionManager()); }
From source file:com.ethlo.geodata.util.ResourceUtil.java
private Entry<Date, File> downloadIfNewer(DataType dataType, Resource resource, CheckedFunction<Path, Path> fun) throws IOException { publisher.publishEvent(new DataLoadedEvent(this, dataType, Operation.DOWNLOAD, 0, 1)); final String alias = dataType.name().toLowerCase(); final File tmpDownloadedFile = new File(tmpDir, alias); final Date remoteLastModified = new Date(resource.lastModified()); final long localLastModified = tmpDownloadedFile.exists() ? tmpDownloadedFile.lastModified() : -2; logger.info(//from w w w . java 2 s. c om "Local file for alias {}" + "\nPath: {}" + "\nExists: {}" + "\nLocal last-modified: {} " + "\nRemote last modified: {}", alias, tmpDownloadedFile.getAbsolutePath(), tmpDownloadedFile.exists(), formatDate(localLastModified), formatDate(remoteLastModified.getTime())); if (!tmpDownloadedFile.exists() || remoteLastModified.getTime() > localLastModified) { logger.info("Downloading {}", resource.getURL()); Files.copy(resource.getInputStream(), tmpDownloadedFile.toPath(), StandardCopyOption.REPLACE_EXISTING); logger.info("Download complete"); } final Path preppedFile = fun.apply(tmpDownloadedFile.toPath()); Files.setLastModifiedTime(tmpDownloadedFile.toPath(), FileTime.fromMillis(remoteLastModified.getTime())); Files.setLastModifiedTime(preppedFile, FileTime.fromMillis(remoteLastModified.getTime())); publisher.publishEvent(new DataLoadedEvent(this, dataType, Operation.DOWNLOAD, 1, 1)); return new AbstractMap.SimpleEntry<>(new Date(remoteLastModified.getTime()), preppedFile.toFile()); }
From source file:spring.osgi.io.OsgiBundleResourcePatternResolver.java
/** * Based on the search type, uses the appropriate searching method. * * @see OsgiBundleResource#BUNDLE_URL_PREFIX * @see org.springframework.core.io.support.PathMatchingResourcePatternResolver#getResources(String) *///w w w . j a v a2s . c o m private Set<Resource> doFindPathMatchingFileResources(Resource rootDirResource, String subPattern, int searchType) throws IOException { String rootPath = null; if (rootDirResource instanceof OsgiBundleResource) { OsgiBundleResource bundleResource = (OsgiBundleResource) rootDirResource; rootPath = bundleResource.getPath(); searchType = bundleResource.getSearchType(); } else if (rootDirResource instanceof UrlResource) { rootPath = rootDirResource.getURL().getPath(); } if (rootPath != null) { String cleanPath = OsgiResourceUtils.stripPrefix(rootPath); // sanitize the root folder (since it's possible to not specify the root which fails any further matches) if (!cleanPath.endsWith(FOLDER_SEPARATOR)) { cleanPath = cleanPath + FOLDER_SEPARATOR; } String fullPattern = cleanPath + subPattern; Set<Resource> result = new LinkedHashSet<>(); doRetrieveMatchingBundleEntries(bundle, fullPattern, cleanPath, result, searchType); return result; } else { return super.doFindPathMatchingFileResources(rootDirResource, subPattern); } }
From source file:gov.nih.nci.ncicb.tcga.dcc.QCLiveTestDataGenerator.java
/** * Executes an arbitrary SQL script file for a specific database schema. * //w ww .j a va2s . c om * <p>The first parameter for this method must be one of the supported {@link SchemaType}s. * * <p>The second parameter is a {@link Resource} that points to a SQL script file resource (e.g. {@link FileSystemResource}). * * @param schemaType - a {@link SchemaType} representing the database schema to run a SQL script file against * @param sqlScriptFileResource - the SQL script file resource to be executed * @throws IOException if the SQL script file resource is not readable * @throws SQLException if an error occurs while executing a SQL script */ public void executeSQLScriptFile(final SchemaType schemaType, final Resource sqlScriptFileResource) throws IOException, SQLException { logger.info("Executing SQL script file '" + sqlScriptFileResource + "' for schema '" + schemaType + "'"); List<String> sqlStmts = null; // Check the provided parameters to ensure that they are not null, otherwise throw an exception if (schemaType != null && sqlScriptFileResource != null) { // If the SQL script file resource is not readable, throw an exception if (!sqlScriptFileResource.isReadable()) throw new IOException("SQL script file resource '" + sqlScriptFileResource + "' is not readable."); // Get the SQL statements from the SQL file sqlStmts = getSQLStmtsToLowerCaseFromFile(sqlScriptFileResource.getURL()); for (String sql : sqlStmts) { System.out.println(sql + ";"); } try { if (schemaType.equals(SchemaType.LOCAL_COMMON)) dccCommonLocalJdbcTemplate.batchUpdate(sqlStmts.toArray(new String[] {})); else if (schemaType.equals(SchemaType.LOCAL_DISEASE)) diseaseLocalJdbcTemplate.batchUpdate(sqlStmts.toArray(new String[] {})); } catch (Exception e) { e.printStackTrace(); } } else throw new NullPointerException("Cannot execute SQL script file for schema '" + schemaType + "' and file '" + sqlScriptFileResource + "'."); logger.info("Done executing SQL script file."); }
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 *//* w w w .ja v a 2 s .co 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; }