Java Code Examples for org.apache.commons.io.FilenameUtils#getPath()

The following examples show how to use org.apache.commons.io.FilenameUtils#getPath() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GitContentRepositoryHelper.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
public boolean replaceParameters(String siteId, Map<String, String> parameters) {
    if (MapUtils.isEmpty(parameters)) {
        logger.debug("Skipping parameter replacement for site {0}", siteId);
        return true;
    }
    String configRootPath = FilenameUtils.getPath(
        studioConfiguration.getProperty(CONFIGURATION_SITE_CONFIG_BASE_PATH));
    Path siteSandboxPath = buildRepoPath(GitRepositories.SANDBOX, siteId);
    Path configFolder = siteSandboxPath.resolve(configRootPath);
    try {
        Files.walkFileTree(configFolder, new StrSubstitutorVisitor(parameters));
        return true;
    } catch (IOException e) {
        logger.error("Error looking for configuration files for site {0}", e, siteId);
        return false;
    }
}
 
Example 2
Source File: AdeInputStreamHandlerExt.java    From ade with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Process the Log Messages coming from a file.
 * 
 * @param file
 * @throws AdeException
 */
public final void incomingStreamFromFile(File file) throws AdeException {
    final InputStream is = AdeFileUtils.openLogFileAsInputStream(file);

    /* Create a AdeInputStream, note that properties is not used by
     * Anomaly Detection Engine */
    final Properties props = new Properties();
    /* Retrieve the name of the file.  FilenameUtil is used here to extract a path without any prefix.
     * Note: Drive Letters show up on Windows System as prefix.  getPath() will return the full path without the drive. */
    final String filename = FilenameUtils.getPath(file.getAbsolutePath()) + file.getName();
    final String parseReportFilename = getParseReportFilename(filename);

    a_adeInputStream = new AdeInputStreamExt(is, props, m_adeExtProperties, parseReportFilename);

    /* Indicate this is a new file, this will allow an interval broken into 
     * to log files. */
    incomingSeparator(new FileSeperator(file.getName()));

    /* Send the stream for further processing */
    incomingObject(a_adeInputStream);
}
 
Example 3
Source File: NewProjectFromScratchPage.java    From xds-ide with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * @param src - Text control after text change
 * @param srcTextBefore - text from 'src' before change 
 * @param dest - Text control to edit
 * 
 * When file name (w/o extension) in 'dest' is the same with file name (w/o extension) from
 * 'srcTextBefore', changes this name in 'dest' with the new one from 'src'  
 */
private void autoEdit(Text src, String srcTextBefore, Text dest) {
    if (hsAutoEditRecursionDetector.add(dest)) {
        String oldSrcName = FilenameUtils.getBaseName(srcTextBefore.trim()).trim();
        String destTxt = dest.getText().trim();
        String destName = FilenameUtils.getBaseName(destTxt).trim();
        if (destName.isEmpty() || (destName.equals(oldSrcName) && !destName.contains("$("))) {
            String newSrcName = FilenameUtils.getBaseName(src.getText().trim()).trim();
            String newDstText = FilenameUtils.getPath(destTxt) + newSrcName;
            String ext = FilenameUtils.getExtension(destTxt);
            if (!ext.isEmpty()) {
                newDstText += '.';
                newDstText += ext;
            }
            dest.setText(newDstText);
        }
        hsAutoEditRecursionDetector.remove(dest);
    }
}
 
Example 4
Source File: HibernateDocumentDAO.java    From document-management-software with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public Document findByPath(String path, long tenantId) {
	String folderPath = FilenameUtils.getPath(path);
	Folder folder = folderDAO.findByPathExtended(folderPath, tenantId);
	if (folder == null)
		return null;

	String fileName = FilenameUtils.getName(path);
	List<Document> docs = findByFileNameAndParentFolderId(folder.getId(), fileName, null, tenantId, null);
	for (Document doc : docs) {
		if (doc.getFileName().equals(fileName))
			return doc;
	}

	return null;
}
 
Example 5
Source File: ProjectMetaInfExporter.java    From webanno with Apache License 2.0 6 votes vote down vote up
/**
 * Copy project META_INF from the exported project
 * 
 * @param aZip
 *            the ZIP file.
 * @param aProject
 *            the project.
 * @throws IOException
 *             if an I/O error occurs.
 */
@Override
public void importData(ProjectImportRequest aRequest, Project aProject,
        ExportedProject aExProject, ZipFile aZip)
    throws Exception
{
    for (Enumeration<? extends ZipEntry> zipEnumerate = aZip.entries(); zipEnumerate
            .hasMoreElements();) {
        ZipEntry entry = zipEnumerate.nextElement();

        // Strip leading "/" that we had in ZIP files prior to 2.0.8 (bug #985)
        String entryName = ZipUtils.normalizeEntryName(entry);

        if (entryName.startsWith(META_INF_FOLDER + "/")) {
            File metaInfDir = new File(projectService.getMetaInfFolder(aProject),
                    FilenameUtils.getPath(entry.getName().replace(META_INF_FOLDER + "/", "")));
            // where the file reside in the META-INF/... directory
            FileUtils.forceMkdir(metaInfDir);
            FileUtils.copyInputStreamToFile(aZip.getInputStream(entry),
                    new File(metaInfDir, FilenameUtils.getName(entry.getName())));

            log.info("Imported META-INF for project [" + aProject.getName() + "] with id ["
                    + aProject.getId() + "]");
        }
    }
}
 
Example 6
Source File: AbstractFileTransformationService.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Returns the name of the localized transformation file
 * if it actually exists, keeps the original in the other case
 *
 * @param filename name of the requested transformation file
 * @return original or localized transformation file to use
 */
protected String getLocalizedProposedFilename(String filename, final WatchService watchService) {
    String extension = FilenameUtils.getExtension(filename);
    String prefix = FilenameUtils.getPath(filename);
    String result = filename;

    if (!prefix.isEmpty()) {
        watchSubDirectory(prefix, watchService);
    }

    // the filename may already contain locale information
    if (!filename.matches(".*_[a-z]{2}." + extension + "$")) {
        String basename = FilenameUtils.getBaseName(filename);
        String alternateName = prefix + basename + "_" + getLocale().getLanguage() + "." + extension;
        String alternatePath = getSourcePath() + alternateName;

        File f = new File(alternatePath);
        if (f.exists()) {
            result = alternateName;
        }
    }

    result = getSourcePath() + result;
    return result;
}
 
Example 7
Source File: ImageUtils.java    From NGA-CLIENT-VER-OPEN-SOURCE with GNU General Public License v2.0 6 votes vote down vote up
public static String newImage(String oldImage, String userId) {
    String extension = FilenameUtils.getExtension(oldImage);
    String path = FilenameUtils.getPath(oldImage);
    String newName;
    if (extension != null) {
        if (path == null || "".equals(path)) {
            return null;
        } else if (extension.length() == 3) {
            newName = HttpUtil.PATH_AVATAR + "/" + userId + "." + extension;

        } else if (extension.length() >= 4
                && "?".equals(extension.substring(3, 4))) {
            newName = HttpUtil.PATH_AVATAR + "/" + userId + "."
                    + extension.substring(0, 3);

        } else {
            newName = HttpUtil.PATH_AVATAR + "/" + userId + ".jpg";
        }
    } else {
        newName = HttpUtil.PATH_AVATAR + "/" + userId + ".jpg";
    }
    return newName;
}
 
Example 8
Source File: AbstractMatrixStorage.java    From sailfish-core with Apache License 2.0 5 votes vote down vote up
protected void removeMatrixFolder(IMatrix matrix) {
    try {
        File matricesFolder = dispatcher.getFolder(FolderType.MATRIX);
        File matrixFolder = new File(matricesFolder, FilenameUtils.getPath(matrix.getFilePath()));
        FileUtils.deleteDirectory(matrixFolder);
    } catch(IOException e) {
        throw new StorageException("Failed to remove matrix from disk: " + matrix.getFilePath());
    }
}
 
Example 9
Source File: Crawler.java    From jbake with MIT License 5 votes vote down vote up
private String createNoExtensionUri(String uri) {
    try {
        return FileUtil.URI_SEPARATOR_CHAR
            + FilenameUtils.getPath(uri)
            + URLEncoder.encode(FilenameUtils.getBaseName(uri), StandardCharsets.UTF_8.name())
            + FileUtil.URI_SEPARATOR_CHAR
            + "index"
            + config.getOutputExtension();
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("Missing UTF-8 encoding??", e); // Won't happen unless JDK is broken.
    }
}
 
Example 10
Source File: Crawler.java    From jbake with MIT License 5 votes vote down vote up
private String createUri(String uri) {
    try {
        return FileUtil.URI_SEPARATOR_CHAR
            + FilenameUtils.getPath(uri)
            + URLEncoder.encode(FilenameUtils.getBaseName(uri), StandardCharsets.UTF_8.name())
            + config.getOutputExtension();
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("Missing UTF-8 encoding??", e); // Won't happen unless JDK is broken.
    }
}
 
Example 11
Source File: YarnAppDeployer.java    From spring-cloud-deployer-yarn with Apache License 2.0 5 votes vote down vote up
private String getHdfsArtifactPath(Resource resource) {
	String path = null;
	try {
		path = "/" + FilenameUtils.getPath(resource.getURI().getPath());
	} catch (IOException e) {
	}
	return path;
}
 
Example 12
Source File: YarnTaskLauncher.java    From spring-cloud-deployer-yarn with Apache License 2.0 5 votes vote down vote up
private String getHdfsArtifactPath(Resource resource) {
	String path = null;
	try {
		path = "/" + FilenameUtils.getPath(resource.getURI().getPath());
	} catch (IOException e) {
	}
	return path;
}
 
Example 13
Source File: Issue.java    From analysis-model with MIT License 5 votes vote down vote up
/**
 * Returns the folder that contains the affected file of this issue. Note that this path is not an absolute path, it
 * is relative to the path of the affected files (returned by {@link #getPath()}).
 *
 * @return the folder of the file that contains this issue
 */
public String getFolder() {
    try {
        String folder = FilenameUtils.getPath(getFileName());
        if (StringUtils.isBlank(folder)) {
            return UNDEFINED;
        }
        return PATH_UTIL.getRelativePath(folder);
    }
    catch (IllegalArgumentException ignore) {
        return UNDEFINED; // fallback
    }
}
 
Example 14
Source File: BinGenerationTool.java    From riiablo with Apache License 2.0 4 votes vote down vote up
private static String generateBinName(String fileName) {
  return FilenameUtils.getPath(fileName) + FilenameUtils.getBaseName(fileName) + ".bin";
}
 
Example 15
Source File: S3File.java    From engine with GNU General Public License v3.0 4 votes vote down vote up
@Override
public String getPath() {
    return FilenameUtils.getPath(key);
}
 
Example 16
Source File: AthenaAuditLoggerConfiguration.java    From cerberus with Apache License 2.0 4 votes vote down vote up
@Autowired
public AthenaAuditLoggerConfiguration(
    @Value("${cerberus.audit.athena.log.path:#{null}}") String logPath,
    AuditLogsS3TimeBasedRollingPolicy<ILoggingEvent> auditLogsS3TimeBasedRollingPolicy) {

  if (StringUtils.isBlank(logPath)) {
    logPath = "";
  } else if (!logPath.endsWith("/")) {
    logPath += "/";
    FilenameUtils.getPath(
        logPath); // this shouldn't be necessary because the path is provided by Spring config,
    // but extra safety
  }
  this.auditLogsS3TimeBasedRollingPolicy = auditLogsS3TimeBasedRollingPolicy;

  LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
  PatternLayoutEncoder patternLayoutEncoder = new PatternLayoutEncoder();
  patternLayoutEncoder.setPattern(MESSAGE_PATTERN);
  patternLayoutEncoder.setContext(loggerContext);
  patternLayoutEncoder.start();

  String hostname;
  try {
    hostname =
        System.getenv("HOSTNAME") != null
            ? System.getenv("HOSTNAME")
            : InetAddress.getLocalHost().getHostName();
  } catch (UnknownHostException e) {
    throw new RuntimeException("Unable to find host name");
  }

  FiveMinuteRollingFileAppender<ILoggingEvent> fiveMinuteRollingFileAppender =
      new FiveMinuteRollingFileAppender<>();
  fiveMinuteRollingFileAppender.setName(ATHENA_LOG_APPENDER_NAME);
  fiveMinuteRollingFileAppender.setContext(loggerContext);
  fiveMinuteRollingFileAppender.setFile(logPath + hostname + "-audit.log");
  fiveMinuteRollingFileAppender.setEncoder(patternLayoutEncoder);

  this.auditLogsS3TimeBasedRollingPolicy.setContext(loggerContext);
  this.auditLogsS3TimeBasedRollingPolicy.setFileNamePattern(
      logPath + hostname + "-audit.%d{yyyy-MM-dd_HH-mm, UTC}.log.gz");
  this.auditLogsS3TimeBasedRollingPolicy.setMaxHistory(100);
  this.auditLogsS3TimeBasedRollingPolicy.setParent(fiveMinuteRollingFileAppender);
  this.auditLogsS3TimeBasedRollingPolicy.setTotalSizeCap(FileSize.valueOf("10gb"));

  fiveMinuteRollingFileAppender.setTriggeringPolicy(this.auditLogsS3TimeBasedRollingPolicy);
  fiveMinuteRollingFileAppender.setRollingPolicy(this.auditLogsS3TimeBasedRollingPolicy);

  this.auditLogsS3TimeBasedRollingPolicy.start();
  fiveMinuteRollingFileAppender.start();

  var logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(ATHENA_AUDIT_LOGGER_NAME);
  logger.addAppender(fiveMinuteRollingFileAppender);
  logger.setLevel(Level.INFO);
  logger.setAdditive(false);
  athenaAuditLogger = logger;
}
 
Example 17
Source File: Path.java    From Albianj2 with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static String relativeToAbsolute(String currentPath, String relativePath) {
    //begin with /
    if (relativePath.startsWith(File.separator)) {
        return relativePath;
    }

    String path = currentPath;
    File f = new File(currentPath);
    if (f.isFile()) {
        path = FilenameUtils.getPath(currentPath);
    }


    //begin with . means current path
    if (!relativePath.startsWith("..")) {
        if (relativePath.startsWith(".")) {
            return joinWithFilename(relativePath.substring(1), currentPath);
        } else {
            return joinWithFilename(relativePath, currentPath);
        }
    }

    //begin with .. means back path
    int count = StringUtils.countMatches(relativePath, "..");
    if (path.endsWith(File.separator)) {
        path = path.substring(0, path.length() - 1);
    }

    int idx = StringUtils.lastIndexOf(relativePath, "..");
    String realpath = relativePath.substring(idx + 1);

    String[] paths = StringUtils.split(path, File.separatorChar);
    int basepathCount = paths.length - count;
    if (0 > basepathCount) throw new RuntimeException("parent folder is so short.");
    if (0 == basepathCount) return realpath;
    String[] basePaths = new String[basepathCount];
    for (int i = 0; i < basepathCount; i++) {
        basePaths[i] = paths[i];
    }

    String basepath = StringUtils.join(basePaths, File.separator);
    return joinWithFilename(realpath, basepath);
}
 
Example 18
Source File: DropboxServiceImpl.java    From document-management-software with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public int importDocuments(long targetFolder, String[] paths) throws ServerException {
	Session session = SessionUtil.validateSession(getThreadLocalRequest());
	FolderDAO fdao = (FolderDAO) Context.get().getBean(FolderDAO.class);

	if (!fdao.isPermissionEnabled(Permission.IMPORT, targetFolder, session.getUserId()))
		return 0;

	int count = 0;
	try {
		User user = session.getUser();
		Dropbox dbox = new Dropbox();
		String token = loadAccessToken(user);
		if (token == null)
			return 0;
		dbox.login(token);

		Folder root = fdao.findById(targetFolder);

		Set<String> imported = new HashSet<String>();
		for (String path : paths) {
			if (imported.contains(path))
				continue;

			Metadata entry = dbox.get(path);
			if (entry instanceof FileMetadata) {
				importDocument(root, (FileMetadata) entry, dbox, session);
				imported.add(entry.getPathDisplay());
			} else {
				String rootPath = entry.getPathDisplay();
				if (!rootPath.endsWith("/"))
					rootPath += "/";

				List<FileMetadata> files = dbox.listFilesInTree(rootPath);
				for (FileMetadata file : files) {
					if (imported.contains(file.getPathDisplay()))
						continue;

					FolderHistory transaction = new FolderHistory();
					transaction.setSession(session);

					String folderPath = file.getPathDisplay().substring(rootPath.length());
					folderPath = FilenameUtils.getPath(file.getPathDisplay());
					folderPath = folderPath.replaceAll("\\\\", "/");

					Folder folder = fdao.createPath(root, folderPath, true, transaction);

					importDocument(folder, file, dbox, session);
					imported.add(file.getPathDisplay());
				}
			}
		}

		count = imported.size();
	} catch (Throwable t) {
		log.error(t.getMessage(), t);
	}

	return count;
}
 
Example 19
Source File: FileTools.java    From OSPREY3 with GNU General Public License v2.0 3 votes vote down vote up
public static ResourcePathRoot parentOf(String path) {
	
	// get the parent path of this path
	String parentPath = FilenameUtils.getPrefix(path) + FilenameUtils.getPath(path);
	
	return new ResourcePathRoot(parentPath);
}
 
Example 20
Source File: UcteExporterTest.java    From powsybl-core with Mozilla Public License 2.0 2 votes vote down vote up
/**
 * Utility method to load a network file from resource directory without calling
 * @param filePath path of the file relative to resources directory
 * @return imported network
 */
private static Network loadNetworkFromResourceFile(String filePath) {
    ReadOnlyDataSource dataSource = new ResourceDataSource(FilenameUtils.getBaseName(filePath), new ResourceSet(FilenameUtils.getPath(filePath), FilenameUtils.getName(filePath)));
    return new UcteImporter().importData(dataSource, NetworkFactory.findDefault(), null);
}