List of usage examples for org.apache.commons.io FilenameUtils normalize
public static String normalize(String filename)
From source file:org.pentaho.di.resource.ResourceDefinitionHelper.java
/** * Try to get content of given file(text or binary) from Pentaho Repository. * * @param repository repository instance * @param fileName substituted file name * @param isTextFile true if it's a text file; false otherwise * @param logger logger interface/*www . j a v a 2 s .co m*/ * @return an object contains name, type and content of the file */ public static SimpleFileMeta loadFileFromPurRepository(Repository repository, String fileName, boolean isTextFile, LogChannelInterface logger) { String simpleName = FilenameUtils.normalize(fileName); String textContent = ""; byte[] binaryContent = new byte[0]; InputStream is = null; boolean success = false; try { Class repositoryClass = repository.getClass(); Object unifiedRepository = repositoryClass.getMethod(METHOD_GET_PUR).invoke(repository); Class unifiedRepositoryClass = unifiedRepository.getClass(); Object repositoryFile = unifiedRepositoryClass.getMethod(METHOD_GET_FILE, String.class) .invoke(unifiedRepository, simpleName); Class repositoryFileClass = repositoryFile.getClass(); Object fileId = repositoryFileClass.getMethod(METHOD_GET_ID).invoke(repositoryFile); simpleName = (String) repositoryFileClass.getMethod(METHOD_GET_NAME).invoke(repositoryFile); Object fileData = unifiedRepositoryClass.getMethod(METHOD_GET_DATA, Serializable.class, Class.class) .invoke(unifiedRepository, fileId, unifiedRepositoryClass.getClassLoader().loadClass(CLASS_SIMPLE_REPOSITORY_FILE_DATA)); Class fileDataClass = fileData.getClass(); is = (InputStream) fileDataClass.getMethod(METHOD_GET_INPUTSTREAM).invoke(fileData); if (isTextFile) { String encoding = null; // just try to get file encoding if we could try { encoding = (String) repositoryFileClass.getMethod(METHOD_GET_ENCODING).invoke(repositoryFile); } catch (Exception ex) { } textContent = IOUtils.toString(is, encoding); } else { // FIXME this could be a problem, let's hope the binary file is not that large... binaryContent = IOUtils.toByteArray(is); } success = true; } catch (NoSuchMethodException | SecurityException | NullPointerException e) { if (logger != null && logger.isDebug()) { logger.logDebug(WARN_FAILED_TO_LOAD_FILE + fileName, e); } } catch (Exception e) { if (logger != null && logger.isError()) { logger.logError(WARN_FAILED_TO_LOAD_FILE + fileName, e); } } finally { IOUtils.closeQuietly(is); } return new SimpleFileMeta(simpleName, isTextFile, textContent, binaryContent, success); }
From source file:org.pentaho.di.resource.ResourceDefinitionHelper.java
public static String normalizeFileName(String fileName) { String normalizedFileName = FilenameUtils.normalize(fileName); if (!Strings.isNullOrEmpty(normalizedFileName)) { fileName = normalizedFileName;/*from ww w .j ava 2 s .c om*/ } return fileName; }
From source file:org.pentaho.di.resource.ResourceDefinitionHelper.java
public static String generateNewFileNameForOutput(String fileName, boolean fromPur) { if (fileName == null) { return fileName; }//from w ww . j a v a 2 s .c om if (fromPur) { fileName = extractFileName(fileName, false); } String slash = "/"; int index = fileName.indexOf('!'); if (index > 0) { // remove duplicated '/' String pattern = slash + "+"; fileName = fileName.substring(index + 1).replaceAll(pattern, slash); if (fileName.startsWith(slash)) { fileName = fileName.substring(1); } fromPur = true; } if (fromPur) { String tmpDir = FilenameUtils.normalize(System.getProperty("java.io.tmpdir")).replace('\\', '/'); StringBuilder sb = new StringBuilder(); sb.append(tmpDir); if (sb.length() == 0 || sb.charAt(sb.length() - 1) != slash.charAt(0)) { sb.append(slash); } sb.append(fileName); fileName = sb.toString(); } return fileName; }
From source file:org.pepstock.jem.node.StatisticsManager.java
/** * Constructs the object. Uses the passed path to store stats. * @param enable <code>true</code> if statistics are managed * @param path folder where to store stats *///from w w w . ja va 2s . c o m public StatisticsManager(String path) { try { if (path != null) { // checks on storage manager the complete path // starting from path of put in config file PathsContainer checkedPath = Main.DATA_PATHS_MANAGER.getPaths(path); // the folder put in config file folderStatsLog = new File(checkedPath.getCurrent().getContent(), path); // if folder doesn't exist if (!folderStatsLog.exists()) { // creates the folder boolean isCreated = folderStatsLog.mkdirs(); // if created if (isCreated) { // logs the creation nad the status // has been set to enable LogAppl.getInstance().emit(NodeMessage.JEMC075I, FilenameUtils.normalize(folderStatsLog.getAbsolutePath())); this.enable = true; } else { // LogAppl.getInstance().emit(NodeMessage.JEMC153E, FilenameUtils.normalize(folderStatsLog.getAbsolutePath())); LogAppl.getInstance().emit(NodeMessage.JEMC183W); } } else { // the folder already exists // therefore the manager is enable LogAppl.getInstance().emit(NodeMessage.JEMC076I, FilenameUtils.normalize(folderStatsLog.getAbsolutePath())); this.enable = true; } } } catch (InvalidDatasetNameException e) { LogAppl.getInstance().ignore(e.getMessage(), e); LogAppl.getInstance().emit(e.getMessageInterface(), e.getObjects()); } // if not enable, put another warning if (!enable) { LogAppl.getInstance().emit(NodeMessage.JEMC183W); } }
From source file:org.polymap.core.data.imex.shape.ShapeExportFeaturesOperation.java
public Status execute(final IProgressMonitor monitor) throws Exception { monitor.beginTask(context.adapt(FeatureOperationExtension.class).getLabel(), context.features().size()); // complex type? FeatureCollection features = context.features(); if (!(features.getSchema() instanceof SimpleFeatureType)) { throw new UnsupportedOperationException("Complex features are not supported yet."); }// w w w . j a va 2 s .co m SimpleFeatureType srcSchema = (SimpleFeatureType) features.getSchema(); // shapeSchema ILayer layer = context.adapt(ILayer.class); final String basename = layer != null ? FilenameUtils.normalize(layer.getLabel()) : FilenameUtils.normalize(srcSchema.getTypeName()); SimpleFeatureTypeBuilder ftb = new SimpleFeatureTypeBuilder(); ftb.setName(basename); ftb.setCRS(srcSchema.getCoordinateReferenceSystem()); // attributes final Map<String, String> nameMap = new HashMap(); for (AttributeDescriptor attr : srcSchema.getAttributeDescriptors()) { // attribute name (shapefile: 10 max) String targetName = StringUtils.left(attr.getLocalName(), 10); for (int i = 1; nameMap.containsValue(targetName); i++) { targetName = StringUtils.left(attr.getLocalName(), 10 - (i / 10 + 1)) + i; log.info(" Shapefile: " + attr.getLocalName() + " -> " + targetName); } nameMap.put(attr.getLocalName(), targetName); ftb.add(targetName, attr.getType().getBinding()); } final SimpleFeatureType shapeSchema = ftb.buildFeatureType(); // retyped collection final SimpleFeatureBuilder fb = new SimpleFeatureBuilder(shapeSchema); FeatureCollection<SimpleFeatureType, SimpleFeature> retyped = new RetypingFeatureCollection<SimpleFeatureType, SimpleFeature>( features, shapeSchema) { private int count = 0; protected SimpleFeature retype(SimpleFeature feature) { if (monitor.isCanceled()) { throw new RuntimeException("Operation canceled."); } for (Property prop : feature.getProperties()) { Object value = prop.getValue(); // Shapefile has length limit 254 if (value instanceof String) { value = StringUtils.abbreviate((String) value, 254); } fb.set(nameMap.get(prop.getName().getLocalPart()), value); } if (++count % 100 == 0) { monitor.worked(100); monitor.subTask("Objekte: " + count); } return fb.buildFeature(feature.getID()); } }; ShapefileDataStoreFactory shapeFactory = new ShapefileDataStoreFactory(); Map<String, Serializable> params = new HashMap<String, Serializable>(); final File shapefile = File.createTempFile(basename + "-", ".shp"); shapefile.deleteOnExit(); params.put(ShapefileDataStoreFactory.URLP.key, shapefile.toURI().toURL()); params.put(ShapefileDataStoreFactory.CREATE_SPATIAL_INDEX.key, Boolean.FALSE); ShapefileDataStore shapeDs = (ShapefileDataStore) shapeFactory.createNewDataStore(params); shapeDs.createSchema(shapeSchema); //shapeDs.forceSchemaCRS(DefaultGeographicCRS.WGS84); //shapeDs.setStringCharset( ) String typeName = shapeDs.getTypeNames()[0]; FeatureStore<SimpleFeatureType, SimpleFeature> shapeFs = (FeatureStore<SimpleFeatureType, SimpleFeature>) shapeDs .getFeatureSource(typeName); // no tx needed; without tx saves alot of memory shapeFs.addFeatures(retyped); // test code; slow but reads just one feature at a time // FeatureIterator<SimpleFeature> it = retyped.features(); // try { // while (it.hasNext()) { // try { // SimpleFeature feature = it.next(); // DefaultFeatureCollection coll = new DefaultFeatureCollection( null, null ); // coll.add( feature ); // //shapeFs.addFeatures( coll ); // log.info( "Added: " + feature ); // } // catch (Exception e ) { // log.warn( "", e ); // } // } // } // finally { // it.close(); // } // open download Polymap.getSessionDisplay().asyncExec(new Runnable() { public void run() { String url = DownloadServiceHandler.registerContent(new ContentProvider() { public String getContentType() { return "application/zip"; } public String getFilename() { return basename + ".shp.zip"; } public InputStream getInputStream() throws Exception { ByteArrayOutputStream bout = new ByteArrayOutputStream(1024 * 1024); ZipOutputStream zipOut = new ZipOutputStream(bout); for (String fileSuffix : FILE_SUFFIXES) { zipOut.putNextEntry(new ZipEntry(basename + "." + fileSuffix)); File f = new File(shapefile.getParent(), StringUtils.substringBefore(shapefile.getName(), ".") + "." + fileSuffix); InputStream in = new BufferedInputStream(new FileInputStream(f)); IOUtils.copy(in, zipOut); in.close(); f.delete(); } zipOut.close(); return new ByteArrayInputStream(bout.toByteArray()); } public boolean done(boolean success) { // all files deleted in #getInputStream() return true; } }); log.info("Shapefile: download URL: " + url); ExternalBrowser.open("download_window", url, ExternalBrowser.NAVIGATION_BAR | ExternalBrowser.STATUS); } }); monitor.done(); return Status.OK; }
From source file:org.polymap.p4.fs.ShapefileGenerator.java
/** * Create a temporary file in {@link FsPlugin#getCacheDir()} to store the new shapefile in. *//*from w w w. j a v a 2 s .c om*/ public ShapefileGenerator(ILayer layer, IContentSite site) { File tmpDir = FsPlugin.getDefault().getCacheDir(); String basename = FilenameUtils.normalize(layer.getLabel()); String projectname = FilenameUtils.normalize(layer.getMap().getLabel()); String username = site.getUserName() != null ? site.getUserName() : "null"; File basedir = new File(tmpDir, username + "@" + projectname + "@" + basename); basedir.mkdirs(); this.newFile = new File(basedir, basename + ".shp"); }
From source file:org.polymap.service.fs.providers.fs.FsContentProvider.java
public IContentFolder createFolder(FsFolder folder, String newName) { try {//from w w w . j ava 2s.co m File dir = new File(folder.getDir(), FilenameUtils.normalize(newName)); dir.mkdir(); return new FsFolder(dir.getName(), folder.getPath(), this, dir); } finally { getSite().invalidateFolder(folder); } }
From source file:org.rhq.core.pc.drift.FilterFileVisitor.java
/** * Besides converting the {@link Filter} into a {@link PathFilter}, this method does a * couple additional things. If the path is a relative, it is expanded into an absolute * path. If the path denotes a directory and if no pattern is specified, it is assumed * that everything under that directory including sub directories should be considered * matches./*from ww w .j a va 2 s . co m*/ * * @param basedir The base directory from which drift detection is being done * @param filter The filter to convert and normalize * @return The converted and normalized filter */ private PathFilter normalize(File basedir, Filter filter) { File path = new File(filter.getPath()); File filterPath; String filterPattern; if (path.isAbsolute()) { filterPath = path; } else { filterPath = new File(basedir, filter.getPath()); } if (filterPath.isDirectory() && isEmpty(filter.getPattern())) { filterPattern = "**/*"; } else { filterPattern = filter.getPattern(); } return new PathFilter(FilenameUtils.normalize(filterPath.getAbsolutePath()), filterPattern); }
From source file:org.silverpeas.attachment.ActifyDocumentProcessor.java
/** * Processes the specified CAD document by placing it in the location expected by Actify. * * @param document a CAD document.// w ww . j a va 2 s.c om * @throws IOException if an error occurs while putting the document into the expected location. */ public void process(final SimpleDocument document) throws IOException { if (isActifySupportEnabled()) { String componentId = document.getPk().getInstanceId(); String id = document.getForeignId(); String fileName = document.getFilename(); if (isCADDocumentSupported(fileName)) { logger.log(Level.INFO, "CAD document supported by Actify detected: {0}", fileName); String dirPrefix = document.isVersioned() ? "v_" : "a_"; String dirDestName = dirPrefix + componentId + "_" + id; String actifyWorkingPath = getActifySourcePath() + File.separatorChar + dirDestName; File destDir = new File(actifyWorkingPath); if (!destDir.exists()) { FileUtils.forceMkdir(destDir); } String normalizedFileName = FilenameUtils.normalize(fileName); if (normalizedFileName == null) { normalizedFileName = FilenameUtils.getName(fileName); } String destFile = actifyWorkingPath + File.separatorChar + normalizedFileName; FileRepositoryManager.copyFile(document.getAttachmentPath(), destFile); } } }
From source file:org.silverpeas.core.contribution.attachment.ActifyDocumentProcessor.java
/** * Processes the specified CAD document by placing it in the location expected by Actify. * * @param document a CAD document./*from w ww .j a v a2 s . co m*/ * @throws IOException if an error occurs while putting the document into the expected location. */ public void process(final SimpleDocument document) throws IOException { if (isActifySupportEnabled()) { String componentId = document.getPk().getInstanceId(); String id = document.getForeignId(); String fileName = document.getFilename(); if (isCADDocumentSupported(fileName)) { logger.debug("CAD document supported by Actify detected: {0}", fileName); String dirPrefix = document.isVersioned() ? "v_" : "a_"; String dirDestName = dirPrefix + componentId + "_" + id; String actifyWorkingPath = getActifySourcePath() + File.separatorChar + dirDestName; File destDir = new File(actifyWorkingPath); if (!destDir.exists()) { FileUtils.forceMkdir(destDir); } String normalizedFileName = FilenameUtils.normalize(fileName); if (normalizedFileName == null) { normalizedFileName = FilenameUtils.getName(fileName); } String destFile = actifyWorkingPath + File.separatorChar + normalizedFileName; FileRepositoryManager.copyFile(document.getAttachmentPath(), destFile); } } }