@Test public void resolveResourceSuccess() throws Exception { String versionFile = "bar-version.css"; String version = "version"; String file = "bar.css"; Resource expected = new ClassPathResource("test/" + file, getClass()); MockServerHttpRequest request = new MockServerHttpRequest(HttpMethod.GET, "/resources/bar-version.css"); MockServerHttpResponse response = new MockServerHttpResponse(); DefaultWebSessionManager sessionManager = new DefaultWebSessionManager(); ServerWebExchange exchange = new DefaultServerWebExchange(request, response, sessionManager); given(this.chain.resolveResource(exchange, versionFile, this.locations)).willReturn(null); given(this.chain.resolveResource(exchange, file, this.locations)).willReturn(expected); given(this.versionStrategy.extractVersion(versionFile)).willReturn(version); given(this.versionStrategy.removeVersion(versionFile, version)).willReturn(file); given(this.versionStrategy.getResourceVersion(expected)).willReturn(version); this.resolver.setStrategyMap(Collections.singletonMap("/**", this.versionStrategy)); Resource actual = this.resolver.resolveResourceInternal(exchange, versionFile, this.locations, this.chain); assertEquals(expected.getFilename(), actual.getFilename()); verify(this.versionStrategy, times(1)).getResourceVersion(expected); assertThat(actual, instanceOf(HttpResource.class)); assertEquals("\"" + version + "\"", ((HttpResource) actual).getResponseHeaders().getETag()); }
/** {@inheritDoc} */ public void afterPropertiesSet() throws Exception { PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); for (String location : locations) { Resource[] findings = resourcePatternResolver.getResources(location); for (Resource resource : findings) { if (resource.getFilename().endsWith(".xsd")) { log.info("Loading XSD schema resource " + resource.getFilename()); SimpleXsdSchema schema = new SimpleXsdSchema(resource); schema.afterPropertiesSet(); schemas.add(schema); } else if (resource.getFilename().endsWith(".wsdl")) { log.info("Loading WSDL schema resource " + resource.getFilename()); WsdlXsdSchema wsdl = new WsdlXsdSchema(resource); wsdl.afterPropertiesSet(); schemas.add(wsdl); } else { log.warn( "Skipped resource other than XSD schema for repository (" + resource.getFilename() + ")"); } } } // Add default Citrus message schemas if available on classpath addCitrusSchema("citrus-mail-message"); addCitrusSchema("citrus-ftp-message"); addCitrusSchema("citrus-ssh-message"); }
/** * Run with * * <p>mvn clean test -Pentry-go,default-test * * <p>The resulting serialized data will then be in ./target/interproEntryGoMapping.gz * * <p>This file should then be copied to * * <p>jms-implementation/support-mini-x86-32/interproEntryGoMapping-NN.N.gz * * <p>and the version number updated in all properties files. * * <p>(DON'T overwrite old versions - commit alongside them please). * * @throws IOException * @throws XMLStreamException * @throws ClassNotFoundException */ @Test @Ignore( "Slow and memory intensive - turn on only to rebuild the InterPro / GO mapping file (each InterPro release)") public void testUnmarshallerAndSerialization() throws IOException, XMLStreamException, ClassNotFoundException { BufferedInputStream bis = null; try { if (interproXmlFile.getFilename().endsWith("gz")) { bis = new BufferedInputStream(new GZIPInputStream(interproXmlFile.getInputStream())); } else if (interproXmlFile.getFilename().endsWith("zip")) { bis = new BufferedInputStream(new ZipInputStream(interproXmlFile.getInputStream())); } else { bis = new BufferedInputStream(interproXmlFile.getInputStream()); } Map<SignatureLibrary, SignatureLibraryIntegratedMethods> unmarshalledData = unmarshaller.unmarshal(bis); // Serialize out un-marshaled data serializerDeserializer.serialize(unmarshalledData); // Serialize back in and cheque for equality. Map<SignatureLibrary, SignatureLibraryIntegratedMethods> retrievedData = serializerDeserializer.deserialize(); Assert.assertTrue(unmarshalledData.equals(retrievedData)); } finally { if (bis != null) bis.close(); } }
public static String load(Resource source, String encoding) { try { return load(source.getInputStream(), encoding); } catch (FileNotFoundException e) { throw new RuntimeException("File not found: " + source.getFilename()); } catch (IOException e) { throw new RuntimeException("File not found: " + source.getFilename()); } }
private String getScriptNameFromFile(Resource scriptPath) { String scriptFileName = scriptPath .getFilename() .substring(0, scriptPath.getFilename().length() - 7); // trim .groovy extension if (scriptFileName.endsWith("_")) { scriptFileName = scriptFileName.substring(0, scriptFileName.length() - 1); } return scriptFileName; }
protected void loadProperties(Properties props) throws IOException { if (this.locations != null) for (int i = 0; i < this.locations.length; ++i) { Resource location = this.locations[i]; InputStream is = null; InputStream keyStream = null; InputStream readIs = null; try { is = location.getInputStream(); keyStream = this.keyLocation.getInputStream(); readIs = DesUtil.decrypt(is, DesUtil.getKey(keyStream)); if (location.getFilename().endsWith(".xml")) { this.propertiesPersister.loadFromXml(props, readIs); } else if (this.fileEncoding != null) this.propertiesPersister.load(props, new InputStreamReader(readIs, this.fileEncoding)); else this.propertiesPersister.load(props, readIs); } catch (Exception ex) { if ((this.ignoreResourceNotFound) && (this.logger.isWarnEnabled())) this.logger.warn("Could not load properties from " + location + ": " + ex.getMessage()); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(keyStream); IOUtils.closeQuietly(readIs); } } }
public Book importApt(Resource apt) { try { String from = "apt"; File out = File.createTempFile("fromAptToXHTML", ".html"); String to = "html"; Converter converter = new DefaultConverter(); InputFileWrapper input = InputFileWrapper.valueOf( apt.getFilename(), from, "ISO-8859-1", converter.getInputFormats()); OutputFileWrapper output = OutputFileWrapper.valueOf( out.getAbsolutePath(), to, "UTF-8", converter.getOutputFormats()); converter.convert(input, output); return importDocbook(fromAptToDocbook.performTransformation(new FileSystemResource(out))); } catch (UnsupportedFormatException e) { e.printStackTrace(); } catch (ConverterException e) { e.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } return null; }
public void afterPropertiesSet() throws Exception { if (pluginCacheMillis == Long.MIN_VALUE) { pluginCacheMillis = cacheMillis; } if (pluginManager == null || localResourceLoader == null) { return; } for (GrailsPlugin plugin : pluginManager.getAllPlugins()) { for (Resource pluginBundle : getPluginBundles(plugin)) { // If the plugin is an inline plugin, use the abosolute path to the plugin's i18n files. // Otherwise, use the relative path to the plugin from the application's perspective. String basePath; if (isInlinePlugin(plugin)) { basePath = getInlinePluginPath(plugin); } else { basePath = WEB_INF_PLUGINS_PATH.substring(1) + plugin.getFileSystemName(); } final String baseName = GrailsStringUtils.substringBefore( GrailsStringUtils.getFileBasename(pluginBundle.getFilename()), "_"); String pathToAdd = basePath + GRAILS_APP_I18N_PATH_COMPONENT + baseName; if (!pluginBaseNames.contains(pathToAdd)) { pluginBaseNames.add(pathToAdd); } } } }
private String fixScriptName(String scriptName, List<Resource> allScripts) { try { Set<String> names = new HashSet<String>(); for (Resource script : allScripts) { names.add(script.getFilename().substring(0, script.getFilename().length() - 7)); } List<String> mostSimilar = CosineSimilarity.mostSimilar(scriptName, names); if (mostSimilar.isEmpty()) { return null; } List<String> topMatches = mostSimilar.subList(0, Math.min(5, mostSimilar.size())); return askUserForBestMatch(scriptName, topMatches); } catch (Exception e) { return null; } }
/** * Load properties into the given instance. * * @param props the Properties instance to load into * @throws java.io.IOException in case of I/O errors * @see #setLocations */ protected void loadProperties(Properties props) throws IOException { if (this.locations != null) { for (int i = 0; i < this.locations.length; i++) { Resource location = this.locations[i]; if (logger.isInfoEnabled()) { logger.info("Loading properties file from " + location); } InputStream is = null; try { is = location.getInputStream(); if (location.getFilename().endsWith(XML_FILE_EXTENSION)) { this.propertiesPersister.loadFromXml(props, is); } else { if (this.fileEncoding != null) { this.propertiesPersister.load(props, new InputStreamReader(is, this.fileEncoding)); } else { this.propertiesPersister.load(props, is); } } } catch (IOException ex) { if (this.ignoreResourceNotFound) { if (logger.isWarnEnabled()) { logger.warn("Could not load properties from " + location + ": " + ex.getMessage()); } } else { throw ex; } } finally { if (is != null) { is.close(); } } } } }
@Override public NodeRef createNode( Resource resource, RepositoryLocation targetLocation, String encoding, String mimetype, QName nodeType) throws IOException { NodeRef rootNode = nodeService.getRootNode(targetLocation.getStoreRef()); final List<NodeRef> parentNodes = searchService.selectNodes( rootNode, targetLocation.getPath(), null, namespaceService, false); Assert.isTrue(parentNodes.size() == 1, "Target location leads to not 1 unique Node reference"); final String fileName = resource.getFilename(); final FileInfo fileInfo = fileFolderService.create(parentNodes.get(0), fileName, nodeType); final NodeRef nodeRef = fileInfo.getNodeRef(); final ContentWriter writer = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true); writer.putContent(resource.getInputStream()); if (mimetype == null) { mimetype = guessMimetype(resource); } if (encoding == null) { encoding = guessEncoding(resource.getInputStream(), mimetype); } writer.setMimetype(mimetype); writer.setEncoding(encoding); return nodeRef; }
@SuppressWarnings({"unchecked", "rawtypes"}) private int executeScriptWithCaching(CommandLine commandLine, String scriptName, String env) { List<Resource> potentialScripts; List<Resource> allScripts = getAvailableScripts(); GantBinding binding = new GantBinding(); binding.setVariable("scriptName", scriptName); setDefaultInputStream(binding); // Now find what scripts match the one requested by the user. boolean exactMatchFound = false; potentialScripts = new ArrayList<Resource>(); for (Resource scriptPath : allScripts) { String scriptFileName = scriptPath .getFilename() .substring(0, scriptPath.getFilename().length() - 7); // trim .groovy extension if (scriptFileName.endsWith("_")) { scriptsAllowedOutsideOfProject.add(scriptPath); scriptFileName = scriptFileName.substring(0, scriptFileName.length() - 1); } if (scriptFileName.equals(scriptName)) { potentialScripts.add(scriptPath); exactMatchFound = true; continue; } if (!exactMatchFound && ScriptNameResolver.resolvesTo(scriptName, scriptFileName)) { potentialScripts.add(scriptPath); } } // First try to load the script from its file. If there is no // file, then attempt to load it as a pre-compiled script. If // that fails, then let the user know and then exit. if (potentialScripts.size() > 0) { potentialScripts = (List) DefaultGroovyMethods.unique(potentialScripts); final Resource scriptFile = potentialScripts.get(0); if (!isGrailsProject() && !isExternalScript(scriptFile)) { return handleScriptExecutedOutsideProjectError(); } return executeScriptFile(commandLine, scriptName, env, binding, scriptFile); } return attemptPrecompiledScriptExecute(commandLine, scriptName, env, binding, allScripts); }
private boolean shouldFilter(Resource resource) { for (String filterPattern : this.filterPatterns) { if (this.matcher.match(filterPattern, resource.getFilename())) { return true; } } return false; }
protected Set<String> extractNames(Resource[] resources) { Set<String> names = new HashSet<String>(); for (Resource resource : resources) { String name = resource.getFilename(); names.add(name.substring(0, name.length() - 4)); } return names; }
public static File getFile(Resource resource) { File file = null; try { file = resource.getFile(); } catch (IOException e) { log.warn(String.format("WebdavUtil.getFile fail... path : %s", resource.getFilename())); } return file; }
private boolean canLoadFileExtension(PropertySourceLoader loader, Resource resource) { String filename = resource.getFilename().toLowerCase(); for (String extension : loader.getFileExtensions()) { if (filename.endsWith("." + extension.toLowerCase())) { return true; } } return false; }
protected void importDataArchive( Resource archive, InputStream resourceStream, BatchImportOptions options) { BufferedInputStream bufferedResourceStream = null; try { // Make sure the stream is buffered if (resourceStream instanceof BufferedInputStream) { bufferedResourceStream = (BufferedInputStream) resourceStream; } else { bufferedResourceStream = new BufferedInputStream(resourceStream); } // Buffer up to 100MB, bad things will happen if we bust this buffer. // TODO see if there is a buffered stream that will write to a file once the buffer fills up bufferedResourceStream.mark(100 * 1024 * 1024); final MediaType type = getMediaType(bufferedResourceStream, archive.getFilename()); if (MT_JAVA_ARCHIVE.equals(type)) { final ArchiveInputStream archiveStream = new JarArchiveInputStream(bufferedResourceStream); importDataArchive(archive, archiveStream, options); } else if (MediaType.APPLICATION_ZIP.equals(type)) { final ArchiveInputStream archiveStream = new ZipArchiveInputStream(bufferedResourceStream); importDataArchive(archive, archiveStream, options); } else if (MT_CPIO.equals(type)) { final ArchiveInputStream archiveStream = new CpioArchiveInputStream(bufferedResourceStream); importDataArchive(archive, archiveStream, options); } else if (MT_AR.equals(type)) { final ArchiveInputStream archiveStream = new ArArchiveInputStream(bufferedResourceStream); importDataArchive(archive, archiveStream, options); } else if (MT_TAR.equals(type)) { final ArchiveInputStream archiveStream = new TarArchiveInputStream(bufferedResourceStream); importDataArchive(archive, archiveStream, options); } else if (MT_BZIP2.equals(type)) { final CompressorInputStream compressedStream = new BZip2CompressorInputStream(bufferedResourceStream); importDataArchive(archive, compressedStream, options); } else if (MT_GZIP.equals(type)) { final CompressorInputStream compressedStream = new GzipCompressorInputStream(bufferedResourceStream); importDataArchive(archive, compressedStream, options); } else if (MT_PACK200.equals(type)) { final CompressorInputStream compressedStream = new Pack200CompressorInputStream(bufferedResourceStream); importDataArchive(archive, compressedStream, options); } else if (MT_XZ.equals(type)) { final CompressorInputStream compressedStream = new XZCompressorInputStream(bufferedResourceStream); importDataArchive(archive, compressedStream, options); } else { throw new RuntimeException("Unrecognized archive media type: " + type); } } catch (IOException e) { throw new RuntimeException("Could not load InputStream for resource: " + archive, e); } finally { IOUtils.closeQuietly(bufferedResourceStream); } }
public Resource findResourceForURI(String uri) { Resource resource = uriToResourceCache.get(uri); if (resource == null) { PluginResourceInfo info = inferPluginNameFromURI(uri); if (warDeployed) { Resource defaultResource = defaultResourceLoader.getResource(uri); if (defaultResource != null && defaultResource.exists()) { resource = defaultResource; } } else { String uriWebAppRelative = WEB_APP_DIR + uri; for (String resourceSearchDirectory : resourceSearchDirectories) { Resource res = resolveExceptionSafe(resourceSearchDirectory + uriWebAppRelative); if (res.exists()) { resource = res; } else if (!warDeployed) { Resource dir = resolveExceptionSafe(resourceSearchDirectory); if (dir.exists() && info != null) { try { String filename = dir.getFilename(); if (filename != null && filename.equals(info.pluginName)) { Resource pluginFile = dir.createRelative(WEB_APP_DIR + info.uri); if (pluginFile.exists()) { resource = pluginFile; } } } catch (IOException e) { // ignore } } } } } if (resource == null && info != null) { resource = findResourceInBinaryPlugins(info); } if (resource == null || !resource.exists()) { Resource tmp = defaultResourceLoader != null ? defaultResourceLoader.getResource(uri) : null; if (tmp != null && tmp.exists()) { resource = tmp; } } if (resource != null) { uriToResourceCache.put(uri, resource); } else if (warDeployed) { uriToResourceCache.put(uri, NULL_RESOURCE); } } return resource == NULL_RESOURCE ? null : resource; }
public List<ResourceHandle> members() throws IOException { Resource[] resources = this.resourceLoader.getResources(getName()); List<ResourceHandle> files = new ArrayList<ResourceHandle>(); for (Resource resource : resources) { if (!resource.getURL().getPath().endsWith("/") && !shouldFilter(resource)) { files.add(new FileHandle(resource.getFilename(), resource)); } } return files; }
// Copies a set of resources to a given directory. The set is specified // by an Ant-style path-matching pattern. public void copyGrailsResources(Object destDir, Object pattern, boolean overwrite) throws FileNotFoundException, IOException { new File(destDir.toString()).mkdirs(); Resource[] resources = resolveResources("classpath:" + pattern); for (Resource resource : resources) { if (resource.isReadable()) { copyGrailsResource(destDir + "/" + resource.getFilename(), resource, overwrite); } } }
@RequestMapping(value = "/uploadedPicture") public void getUploadedPicture(HttpServletResponse response) throws IOException { Resource picturePath = userProfileSession.getPicturePath(); if (picturePath == null) { picturePath = anonymousPicture; } response.setHeader( "Content-Type", URLConnection.guessContentTypeFromName(picturePath.getFilename())); IOUtils.copy(picturePath.getInputStream(), response.getOutputStream()); }
@Deprecated public Project(Resource projectRoot, StudioFileSystem fileSystem) { super(fileSystem); this.projectRoot = projectRoot; this.projectName = projectRoot.getFilename(); try { this.mavenProject = projectRoot.createRelative(ProjectConstants.POM_XML).exists(); } catch (IOException ex) { throw new WMRuntimeException(ex); } }
protected void initConfig(Resource configResource) { if (!configResource.exists()) { throw new ConfigServiceInitializationException( "Failed to initialize config cervice for resource: " + configResource.getFilename()); } config = new Properties(); try { config.load(configResource.getInputStream()); } catch (IOException e) { throw new ConfigServiceInitializationException("Failed to initialize Config service ", e); } }
/** * Adds Citrus message schema to repository if available on classpath. * * @param schemaName */ protected void addCitrusSchema(String schemaName) throws IOException, SAXException, ParserConfigurationException { Resource resource = new PathMatchingResourcePatternResolver() .getResource("classpath:com/consol/citrus/schema/" + schemaName + ".xsd"); if (resource.exists()) { log.info("Loading XSD schema resource " + resource.getFilename()); SimpleXsdSchema schema = new SimpleXsdSchema(resource); schema.afterPropertiesSet(); schemas.add(schema); } }
public void setConfig(List<Resource> resources) { for (Resource configFile : resources) { try (InputStream is = configFile.getInputStream()) { Properties props = new Properties(); props.load(is); config.put(getResourceFileName(configFile), props); } catch (IOException e) { throw new MotechException("Cant load config file " + configFile.getFilename(), e); } } }
/** * Sets the font to use. The resource must either point to a Type 1 or a TrueType font or a * directory containing fonts. In case a directory is specified, the font that contains the most * glyphs needed to render a given text is used. The font type is determined by the filename * extension. Supported extensions are <i>.pfa</i>, <i>.pfb</i> and <i>.ttf</i>. */ public void setFont(Resource res) throws FontFormatException, IOException { try { File f = res.getFile(); if (f.isDirectory()) { addAllFonts(f); } else { addFont(f); } } catch (IOException e) { addFont(res); } Assert.notEmpty(fontBundle.getAllFonts(), "Found no fonts at " + res.getFilename()); }
/** * Extends the base class {@link PathExtensionContentNegotiationStrategy#getMediaTypeForResource} * with the ability to also look up through the ServletContext. * * @param resource the resource to look up * @return the MediaType for the extension or {@code null}. * @since 4.3 */ public MediaType getMediaTypeForResource(Resource resource) { MediaType mediaType = super.getMediaTypeForResource(resource); if (mediaType == null) { String mimeType = this.servletContext.getMimeType(resource.getFilename()); if (StringUtils.hasText(mimeType)) { mediaType = MediaType.parseMediaType(mimeType); } } if (MediaType.APPLICATION_OCTET_STREAM.equals(mediaType)) { mediaType = null; } return mediaType; }
@SuppressWarnings("rawtypes") public List evaluateMappings(Resource resource) { InputStream inputStream = null; try { inputStream = resource.getInputStream(); return evaluateMappings(classLoader.parseClass(DefaultGroovyMethods.getText(inputStream))); } catch (IOException e) { throw new UrlMappingException( "Unable to read mapping file [" + resource.getFilename() + "]: " + e.getMessage(), e); } finally { IOUtils.closeQuietly(inputStream); } }
public String getResourceFileName(Resource resource) { String name = resource.getFilename(); if (resource instanceof ClassPathResource) { name = ((ClassPathResource) resource).getPath(); } else { int colonIndex = name.indexOf(':'); if (colonIndex >= 0) { name = name.substring(colonIndex + 1); } } return name; }
public void displayInfo(Resource r) { System.out.println(r.getClass()); try { System.out.println(r.getURL().getContent()); System.out.println(r.contentLength()); System.out.println(r.getFilename()); System.out.println(r.isOpen()); System.out.println(r.getInputStream().read()); // System.out.println(r.); } catch (IOException e) { System.out.println("crazy error!"); } }