List of usage examples for org.apache.commons.io FilenameUtils getName
public static String getName(String filename)
From source file:eu.chocolatejar.eclipse.plugin.cleaner.ArtifactParser.java
/** * Resolve artifact by reg exp from the filename * //from w ww. j a v a 2s . c o m * @param file * @return <code>null</code> if not found */ private Artifact getArtifactBasedOnFilename(File file) { if (file == null) { return null; } try { String baseName = FilenameUtils.getName(file.getAbsolutePath()); Matcher versionMatcher = VERSION_PATTERN.matcher(baseName); if (versionMatcher.find()) { String version = versionMatcher.group(0); if (baseName.contains("_")) { String bundleSymbolicName = StringUtils.substringBeforeLast(baseName, "_" + version); return new Artifact(file, bundleSymbolicName, version); } } } catch (Exception e) { logger.debug("Unable to parse artifact based on filename from the file '{}'.", file, e); } return null; }
From source file:edu.jhuapl.openessence.config.DataSourceLoader.java
/** * @param existingDataSources this can't be injected because the code that initializes the data sources delegates to * this method * @return returns dataSources argument, for chaining * @see AppConfig#dataSources()//from w ww . ja v a 2 s .c om */ public ConcurrentMap<String, JdbcOeDataSource> loadDataSources( ConcurrentMap<String, JdbcOeDataSource> existingDataSources) { try { URL groovyRoot = resourcePatternResolver.getResource("classpath:/ds").getURL(); Resource[] groovyResources = resourcePatternResolver.getResources("classpath:/ds/*.groovy"); String[] groovyScriptNames = new String[groovyResources.length]; for (int i = 0; i < groovyResources.length; i++) { groovyScriptNames[i] = FilenameUtils.getName(groovyResources[i].getFile().getPath()); } GroovyScriptEngine groovyScriptEngine = new GroovyScriptEngine(new URL[] { groovyRoot }); for (String scriptName : groovyScriptNames) { try { log.info("Loading Groovy script {}", scriptName); Class<?> clazz = groovyScriptEngine.loadScriptByName(scriptName); JdbcOeDataSource ds = (JdbcOeDataSource) beanFactory.createBean(clazz); existingDataSources.put(ds.getDataSourceId(), ds); // legacy code expects each DS to be a named bean // TODO remove this when legacy code is updated try { BeanDefinition beanDef = BeanDefinitionReaderUtils.createBeanDefinition(null, clazz.getName(), groovyScriptEngine.getGroovyClassLoader()); BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; registry.registerBeanDefinition(clazz.getName(), beanDef); } catch (ClassNotFoundException e) { log.error("Exception creating bean definition for class " + clazz.getName(), e); } } catch (ResourceException e) { // You can have Exception as last param, see http://slf4j.org/faq.html#paramException log.error("Exception loading data source {}", scriptName, e); } catch (ScriptException e) { log.error("Exception loading data source {}", scriptName, e); } } return existingDataSources; } catch (BeanDefinitionStoreException e) { throw new RuntimeException(e); } catch (BeansException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:com.heliosphere.athena.base.file.internal.resource.AbstractResource.java
/** * Loads the file considering its pathname is relative. * <hr>/*from w w w . java 2s .com*/ * @param pathname Resource path name. * @return {@code True} if the resource can be loaded, {@code false} otherwise. */ @SuppressWarnings("unused") private final boolean loadRelative(String pathname) { URL url = null; try { // Maybe the file pathname is relative. url = Thread.currentThread().getContextClassLoader().getResource(pathname); this.file = new File(url.toURI()); if (!file.exists()) { try { file.createNewFile(); } catch (IOException ioe) { return false; } } } catch (Exception e) { // Try to get the parent directory of the file ... maybe the file does not exist! file = new File(pathname); String name = FilenameUtils.getName(pathname); File directory = file.getParentFile(); try { url = Thread.currentThread().getContextClassLoader().getResource(file.getParent()); try { file = new File(url.toURI()); if (directory.exists() && directory.isDirectory()) { // OK, found the parent directory, then create the file as it does not exist. file = new File(directory.getAbsolutePath() + File.separator + name); try { file.createNewFile(); } catch (IOException e1) { return false; } } } catch (URISyntaxException urie) { return false; } } catch (Exception e2) { return false; } } return this.file.exists(); }
From source file:codes.thischwa.c5c.DispatcherPUT.java
@Override GenericResponse doRequest() {/*from w w w. j av a2 s. c o m*/ logger.debug("Entering DispatcherPUT#doRequest"); InputStream in = null; try { Context ctx = RequestData.getContext(); FilemanagerAction mode = ctx.getMode(); HttpServletRequest req = ctx.getServletRequest(); FilemanagerConfig conf = UserObjectProxy.getFilemanagerUserConfig(req); switch (mode) { case UPLOAD: { boolean overwrite = conf.getUpload().isOverwrite(); String currentPath = IOUtils.toString(req.getPart("currentpath").getInputStream()); String backendPath = buildBackendPath(currentPath); Part uploadPart = req.getPart("newfile"); String newName = getFileName(uploadPart); // Some browsers transfer the entire source path not just the filename String fileName = FilenameUtils.getName(newName); // TODO check forceSingleExtension String sanitizedName = FileUtils.sanitizeName(fileName); if (!overwrite) sanitizedName = getUniqueName(backendPath, sanitizedName); logger.debug("* upload -> currentpath: {}, filename: {}, sanitized filename: {}", currentPath, fileName, sanitizedName); // check 'overwrite' and unambiguity String uniqueName = getUniqueName(backendPath, sanitizedName); if (!overwrite && !uniqueName.equals(sanitizedName)) { throw new FilemanagerException(FilemanagerAction.UPLOAD, FilemanagerException.Key.FileAlreadyExists, sanitizedName); } sanitizedName = uniqueName; in = uploadPart.getInputStream(); // save the file temporary Path tempPath = saveTemp(in, sanitizedName); // pre-process the upload imageProcessingAndSizeCheck(tempPath, sanitizedName, uploadPart.getSize(), conf); connector.upload(backendPath, sanitizedName, new BufferedInputStream(Files.newInputStream(tempPath))); logger.debug("successful uploaded {} bytes", uploadPart.getSize()); Files.delete(tempPath); UploadFile ufResp = new UploadFile(currentPath, sanitizedName); ufResp.setName(newName); ufResp.setPath(currentPath); return ufResp; } case REPLACE: { String newFilePath = IOUtils.toString(req.getPart("newfilepath").getInputStream()); String backendPath = buildBackendPath(newFilePath); Part uploadPart = req.getPart("fileR"); logger.debug("* replacefile -> urlPath: {}, backendPath: {}", newFilePath, backendPath); // check if backendPath is protected boolean protect = connector.isProtected(backendPath); if (protect) { throw new FilemanagerException(FilemanagerAction.UPLOAD, FilemanagerException.Key.NotAllowedSystem, backendPath); } // check if file already exits VirtualFile vf = new VirtualFile(backendPath, false); String fileName = vf.getName(); String uniqueName = getUniqueName(vf.getFolder(), fileName); if (uniqueName.equals(fileName)) { throw new FilemanagerException(FilemanagerAction.UPLOAD, FilemanagerException.Key.FileNotExists, backendPath); } in = uploadPart.getInputStream(); // save the file temporary Path tempPath = saveTemp(in, fileName); // pre-process the upload imageProcessingAndSizeCheck(tempPath, fileName, uploadPart.getSize(), conf); connector.replace(backendPath, new BufferedInputStream(Files.newInputStream(tempPath))); logger.debug("successful replaced {} bytes", uploadPart.getSize()); VirtualFile vfUrlPath = new VirtualFile(newFilePath, false); return new Replace(vfUrlPath.getFolder(), vfUrlPath.getName()); } case SAVEFILE: { String urlPath = req.getParameter("path"); String backendPath = buildBackendPath(urlPath); logger.debug("* savefile -> urlPath: {}, backendPath: {}", urlPath, backendPath); String content = req.getParameter("content"); connector.saveFile(backendPath, content); return new SaveFile(urlPath); } default: { logger.error("Unknown 'mode' for POST: {}", req.getParameter("mode")); throw new C5CException(UserObjectProxy.getFilemanagerErrorMessage(Key.ModeError)); } } } catch (C5CException e) { return ErrorResponseFactory.buildErrorResponseForUpload(e.getMessage()); } catch (ServletException e) { logger.error("A ServletException was thrown while uploading: " + e.getMessage(), e); return ErrorResponseFactory.buildErrorResponseForUpload(e.getMessage(), 200); } catch (IOException e) { logger.error("A IOException was thrown while uploading: " + e.getMessage(), e); return ErrorResponseFactory.buildErrorResponseForUpload(e.getMessage(), 200); } finally { IOUtils.closeQuietly(in); } }
From source file:edu.cornell.med.icb.goby.stats.DifferentialExpressionAnalysis.java
public void parseGroupsDefinition(final String groupsDefinition, final DifferentialExpressionCalculator deCalculator, final String[] inputFilenames) { if (groupsDefinition == null) { // no groups definition to parse. return;/*from ww w .j a v a 2s. c o m*/ } final String[] groupsTmp = groupsDefinition.split("/"); ObjectSet<String> groupSet = new ObjectArraySet<String>(); for (final String group : groupsTmp) { final String[] groupTokens = group.split("="); if (groupTokens.length < 2) { System.err.println("The --group argument must have the syntax groupId=basename"); System.exit(1); } final String groupId = groupTokens[0]; final String groupBasenames = groupTokens[1]; assert groupTokens.length == 2 : "group definition must have only two elements separated by an equal sign."; deCalculator.defineGroup(groupId); groupSet.add(groupId); for (final String groupString : groupBasenames.split(",")) { final String sampleBasename = FilenameUtils.getName(AlignmentReaderImpl.getBasename(groupString)); if (!isInputBasename(sampleBasename, inputFilenames)) { System.err.printf("The group basename %s is not a valid input basename.%n", sampleBasename); System.exit(1); } System.out.println("Associating basename: " + sampleBasename + " to group: " + groupId); deCalculator.associateSampleToGroup(sampleBasename, groupId); } final int groupSize = (groupBasenames.split(",")).length; groupSizes.put(groupId, groupSize); } groups = groupSet.toArray(new String[groupSet.size()]); }
From source file:com.cognifide.cq.cqsm.core.scripts.ScriptReplicatorImpl.java
@Override public void replicate(Script script, ResourceResolver resolver) throws ExecutionException, ReplicationException, PersistenceException { eventManager.trigger(Event.BEFORE_REPLICATE, script); final List<Script> includes = new LinkedList<>(); includes.add(script);//from w w w.j a v a 2s . com includes.addAll(scriptManager.findIncludes(script, resolver)); final boolean autocommit = true; final Resource includeDir = ResourceUtil.getOrCreateResource(resolver, REPLICATION_PATH, JcrConstants.NT_UNSTRUCTURED, JcrConstants.NT_UNSTRUCTURED, autocommit); for (final Script include : includes) { final String path = (script.equals(include) ? SCRIPT_PATH : REPLICATION_PATH) + "/" + FilenameUtils.getName(script.getPath()); LOG.warn("Copying {} to {}", script.getPath(), includeDir.getPath()); copy(resolver, script.getPath(), includeDir); resolver.commit(); final Session session = resolver.adaptTo(Session.class); replicator.replicate(session, ReplicationActionType.ACTIVATE, path); } resolver.delete(includeDir); resolver.commit(); eventManager.trigger(Event.AFTER_REPLICATE, script); }
From source file:br.univali.celine.lms.core.commands.ImportCourseCommand.java
public String executar(HttpServletRequest request, HttpServletResponse response) throws Exception { User user = (User) request.getSession().getAttribute(UserImpl.USER); userName = user.getName();//from ww w . java2 s. co m AjaxInterface ajaxInterface = AjaxInterface.getInstance(); ajaxInterface.updateProgress(userName, 0.0); ajaxInterface.updateStatus(userName, 1); MultipartRequestProcessor mrp = MultipartRequestProcessor.getInstance(); mrp.setProgressListener(this); mrp.processRequest(request); String coursesFolder = LMSConfig.getInstance().getCompleteCoursesFolder(); coursesFolder = coursesFolder.replaceAll("file:", ""); String title = mrp.getParameter("title", true); // TODO: esse title nao deveria vir do formulario, mas ser extraido do contentpackage !!! String id = mrp.getParameter("id", true); // TODO: esse id nao deveria vir do formulario, mas ser extraido do contentpackage !!! while (mrp.hasFiles()) { FileItem item = mrp.getNextFile(); String fileFolder = FilenameUtils.getBaseName(item.getName()).replaceAll(".zip", ""); fileFolder = fileFolder.replace('.', '_'); File dir = new File(coursesFolder + fileFolder); while (dir.exists()) { fileFolder = "_" + fileFolder; dir = new File(coursesFolder + fileFolder); } logger.info("mkdirs " + dir.getAbsolutePath()); dir.mkdirs(); logger.info("done mkdirs"); ajaxInterface.updateProgress(userName, 0.0); ajaxInterface.updateStatus(userName, 2); byte[] buffer = new byte[1024]; long totalBytes = 0; int bytesRead = 0; File zipFile = new File(dir + "\\" + FilenameUtils.getName(item.getName())); FileOutputStream fos = new FileOutputStream(zipFile); InputStream is = item.getInputStream(); while ((bytesRead = is.read(buffer, 0, buffer.length)) > 0) { fos.write(buffer, 0, bytesRead); totalBytes = totalBytes + bytesRead; ajaxInterface.updateProgress(userName, (100 * totalBytes) / item.getSize()); } fos.close(); is.close(); ajaxInterface.updateProgress(userName, 0.0); ajaxInterface.updateStatus(userName, 3); Zip zip = new Zip(); zip.setListener(this); zip.unzip(zipFile, dir); zipFile.delete(); ajaxInterface.removeProgress(userName); ajaxInterface.removeStatus(userName); LMSControl control = LMSControl.getInstance(); CourseImpl course = new CourseImpl(id, fileFolder, title, false, false); logger.info("Inserting course"); control.insertCourse(course); } Map<String, Object> mparams = mrp.getParameters(); String params = ""; for (String name : mparams.keySet()) { params += "&" + name + "=" + mparams.get(name); } params = params.substring(1); return HTMLBuilder.buildRedirect(mrp.getParameter("nextURL", true) + "?" + params); }
From source file:codes.thischwa.c5c.impl.LocalConnector.java
@Override public boolean rename(String oldBackendPath, String sanitizedName) throws C5CException { Path src = buildRealPath(oldBackendPath); boolean isDirectory = Files.isDirectory(src); if (!Files.exists(src)) { logger.error("Source file not found: {}", src.toString()); FilemanagerException.Key key = (isDirectory) ? FilemanagerException.Key.DirectoryNotExist : FilemanagerException.Key.FileNotExists; throw new FilemanagerException(FilemanagerAction.RENAME, key, FilenameUtils.getName(oldBackendPath)); }/*from ww w.ja va 2 s . co m*/ Path dest = src.resolveSibling(sanitizedName); try { Files.move(src, dest); } catch (SecurityException | IOException e) { logger.warn(String.format("Error while renaming [%s] to [%s]", src.getFileName().toString(), dest.getFileName().toString()), e); FilemanagerException.Key key = (Files.isDirectory(src)) ? FilemanagerException.Key.ErrorRenamingDirectory : FilemanagerException.Key.ErrorRenamingFile; throw new FilemanagerException(FilemanagerAction.RENAME, key, FilenameUtils.getName(oldBackendPath), sanitizedName); } catch (FileSystemAlreadyExistsException e) { logger.warn("Destination file already exists: {}", dest.toAbsolutePath()); FilemanagerException.Key key = (Files.isDirectory(dest)) ? FilemanagerException.Key.DirectoryAlreadyExists : FilemanagerException.Key.FileAlreadyExists; throw new FilemanagerException(FilemanagerAction.RENAME, key, sanitizedName); } return isDirectory; }
From source file:net.sf.firemox.xml.XmlConfiguration.java
/** * Build and return a parsed instance of given card file. * /*from w ww. j av a 2 s. com*/ * @param cardFile * the XML card file. * @param workingDir * the working directory. * @param output * the output stream of MDB file. * @return a parsed instance of given card file. * @exception SAXException * parsing error. * @exception IOException * writing error. */ public static XmlConfiguration parseCard(String cardFile, String workingDir, OutputStream output) throws SAXException, IOException { currentCard = FilenameUtils.getName(cardFile); return new XmlConfiguration(cardFile, workingDir, output); }
From source file:fr.gael.dhus.service.ProductUploadService.java
@PreAuthorize("hasRole('ROLE_UPLOAD')") @Transactional(propagation = Propagation.REQUIRED) public void upload(Long user_id, FileItem product, ArrayList<Long> collection_ids) throws UploadingException, RootNotModifiableException, ProductNotAddedException { //userService.getUser (userId); User owner = securityService.getCurrentUser(); ArrayList<Collection> collections = new ArrayList<>(); for (Long cId : collection_ids) { Collection c;/*from w w w. jav a 2 s . co m*/ // try // { c = collectionService.getCollection(cId); // } // catch (CollectionNotExistingException e) // { // continue; // } collections.add(c); } String fileName = product.getName(); try { logger.info(new Message(MessageType.UPLOADS, owner.getUsername() + " tries to upload product '" + fileName + "'")); actionRecordWritterDao.uploadStart(fileName, owner.getUsername()); if (fileName != null) { fileName = FilenameUtils.getName(fileName); } File path = null; try { path = incomingManager.getNewProductIncomingPath(); if (path == null) throw new UnsupportedOperationException("Computed upload path is not available."); } catch (Exception e) { // actionRecordWritterDao.uploadFailed (fileName, owner); throw e; } File uploadedFile = new File(path, fileName); if (uploadedFile.createNewFile()) { product.write(uploadedFile); } else { throw new IOException("The file already exists in repository."); } // uploadDone (uploadedFile.toURI ().toURL (), owner, collections); uploadService.addProduct(uploadedFile.toURI().toURL(), owner, collections); } catch (ProductNotAddedException e) { throw e; } // catch (UploadingException e) // { // throw new UploadingException ("An error occured when uploading '" + // fileName + "'", e); // } catch (Exception e) { actionRecordWritterDao.uploadFailed(fileName, owner.getUsername()); throw new UploadingException("An error occured when uploading '" + fileName + "'", e); } }