List of usage examples for org.apache.commons.io FilenameUtils normalizeNoEndSeparator
public static String normalizeNoEndSeparator(String filename)
From source file:avantssar.aslanpp.testing.Tester.java
public static void doTest(TranslationReport rep, ITestTask task, File sourceBaseDir, File targetBaseDir, ASLanPPConnectorImpl translator, TesterCommandLineOptions options, PrintStream err) { String relativePath = FilenameUtils.normalize(task.getASLanPP().getAbsolutePath()) .substring(FilenameUtils.normalizeNoEndSeparator(sourceBaseDir.getAbsolutePath()).length() + 1); File aslanPPinput = new File( FilenameUtils.concat(FilenameUtils.normalize(targetBaseDir.getAbsolutePath()), relativePath)); try {//from w ww .j a v a 2 s. c om FileUtils.copyFile(task.getASLanPP(), aslanPPinput, true); File aslanPPcheck1 = new File( FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".check1.aslan++"); File aslanPPcheck1det = new File( FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".check1.detailed.aslan++"); File aslanPPcheck1err = new File( FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".check1.errors.aslan++"); File aslanPPcheck1warn = new File( FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".check1.warnings.aslan++"); File aslanPPcheck2 = null; File aslanPPcheck2det = null; File aslanPPcheck2err = null; File aslanPPcheck2warn = null; File aslanFile = new File(FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".aslan"); File errorsFile = new File( FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".errors.txt"); File warningsFile = new File( FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".warnings.txt"); // Load the file and write it back to another file. // Then again load it back and write it to another file. // The files should have the same content. String fileName = aslanPPinput.getAbsolutePath(); String aslanppSpec = FileUtils.readFileToString(task.getASLanPP()); TranslatorOptions optPP = new TranslatorOptions(); optPP.setPrettyPrint(true); TranslatorOptions optPPdet = new TranslatorOptions(); optPPdet.setPreprocess(true); // EntityManager.getInstance().purge(); TranslatorOutput firstLoad = translator.translate(optPP, fileName, aslanppSpec); FileUtils.writeStringToFile(aslanPPcheck1, firstLoad.getSpecification()); FileUtils.writeLines(aslanPPcheck1err, firstLoad.getErrors()); aslanPPcheck1err = deleteIfZero(aslanPPcheck1err); FileUtils.writeLines(aslanPPcheck1warn, firstLoad.getWarnings()); aslanPPcheck1warn = deleteIfZero(aslanPPcheck1warn); // EntityManager.getInstance().purge(); TranslatorOutput firstLoadDet = translator.translate(optPPdet, fileName, aslanppSpec); // TODO should use translate_main, since result will be empty FileUtils.writeStringToFile(aslanPPcheck1det, firstLoadDet.getSpecification()); if (firstLoad.getSpecification() != null) { aslanPPcheck2 = new File( FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".check2.aslan++"); aslanPPcheck2det = new File( FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".check2.detailed.aslan++"); aslanPPcheck2err = new File( FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".check2.errors.aslan++"); aslanPPcheck2warn = new File( FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".check2.warnings.aslan++"); // EntityManager.getInstance().purge(); TranslatorOutput secondLoad = translator.translate(optPP, null, firstLoad.getSpecification()); FileUtils.writeStringToFile(aslanPPcheck2, secondLoad.getSpecification()); FileUtils.writeLines(aslanPPcheck2err, secondLoad.getErrors()); aslanPPcheck2err = deleteIfZero(aslanPPcheck2err); FileUtils.writeLines(aslanPPcheck2warn, secondLoad.getWarnings()); aslanPPcheck2warn = deleteIfZero(aslanPPcheck2warn); // EntityManager.getInstance().purge(); TranslatorOutput secondLoadDet = translator.translate(optPPdet, null, firstLoad.getSpecification()); FileUtils.writeStringToFile(aslanPPcheck2det, secondLoadDet.getSpecification()); } // EntityManager.getInstance().purge(); TranslatorOutput result = translator.translate(options, fileName, aslanppSpec); FileUtils.writeStringToFile(aslanFile, result.getSpecification()); FileUtils.writeLines(errorsFile, result.getErrors()); FileUtils.writeLines(warningsFile, result.getWarnings()); File expASLan = null; if (task.getExpectedASLan() != null) { expASLan = new File( FilenameUtils.removeExtension(aslanPPinput.getAbsolutePath()) + ".expected.aslan"); FileUtils.copyFile(task.getExpectedASLan(), expASLan, true); } TranslationInstance ti = rep.newInstance(aslanPPinput, deleteIfZero(aslanPPcheck1), deleteIfZero(aslanPPcheck1det), deleteIfZero(aslanPPcheck2), deleteIfZero(aslanPPcheck2det), result.getErrors().size(), deleteIfZero(errorsFile), result.getWarnings().size(), deleteIfZero(warningsFile), deleteIfZero(expASLan), deleteIfZero(aslanFile), task.getExpectedVerdict()); if (ti.hasTranslation()) { if (bm != null && bm.getBackendRunners().size() > 0) { for (final IBackendRunner runner : bm.getBackendRunners()) { try { List<String> pars = task.getBackendParameters(runner.getName()); pool.execute(new BackendTask(runner.spawn(), pars, aslanFile, ti)); } catch (BackendRunnerInstantiationException bex) { Debug.logger.error("Failed to spawn backend " + runner.getName() + ".", bex); } } } } } catch (Exception e) { System.out.println("Exception while testing file '" + task.getASLanPP().getAbsolutePath() + "': " + e.getMessage()); Debug.logger.error("Failed to test file '" + aslanPPinput + "'.", e); } }
From source file:io.hawkcd.agent.services.FileManagementService.java
@Override public String getRootPath(String path) { String rootPath = path;//w w w. j a v a2s . c o m rootPath = this.normalizePath(path); File file = new File(rootPath); int wildCardCharIndex = path.indexOf('*'); if (wildCardCharIndex != -1) { rootPath = path.substring(0, wildCardCharIndex - 1); return rootPath; } if (file.isFile()) { rootPath = file.getAbsolutePath().replace(file.getName(), ""); FilenameUtils.normalizeNoEndSeparator(rootPath); return rootPath; } if (file.isDirectory()) { rootPath = file.getAbsolutePath(); return rootPath; } return ""; }
From source file:com.apporiented.hermesftp.session.impl.FtpSessionContextImpl.java
/** * {@inheritDoc}//from www.ja v a2 s. co m */ public String getRemoteRelDir() { String relDir = null; try { String canDir = new File(getRemoteDir()).getCanonicalPath(); canDir = FilenameUtils.normalizeNoEndSeparator(canDir); String canRoot = new File(getOptions().getRootDir()).getCanonicalPath(); canRoot = FilenameUtils.normalizeNoEndSeparator(canRoot); if (canDir.toUpperCase().startsWith(canRoot.toUpperCase())) { relDir = canDir.substring(canRoot.length()); if (!relDir.startsWith(File.separator)) { relDir = File.separator + relDir; } } else { relDir = canDir; } } catch (IOException e) { log.error(e); } return relDir; }
From source file:fr.fastconnect.factory.tibco.bw.maven.source.AbstractProjectsListMojo.java
/** * <p>//from w w w.ja v a 2s. c om * Get the relative path from one file to another, specifying the directory * separator. * If one of the provided resources does not exist, it is assumed to be a * file unless it ends with '/' or '\'. * </p> * * @param targetPath targetPath is calculated to this file * @param basePath basePath is calculated from this file * @param pathSeparator directory separator. The platform default is not assumed so that we can test Unix behaviour when running on Windows (for example) * @return */ public static String getRelativePath(String targetPath, String basePath, String pathSeparator) { // Normalize the paths String normalizedTargetPath = FilenameUtils.normalizeNoEndSeparator(targetPath); String normalizedBasePath = FilenameUtils.normalizeNoEndSeparator(basePath); // Undo the changes to the separators made by normalization if (pathSeparator.equals("/")) { normalizedTargetPath = FilenameUtils.separatorsToUnix(normalizedTargetPath); normalizedBasePath = FilenameUtils.separatorsToUnix(normalizedBasePath); } else if (pathSeparator.equals("\\")) { normalizedTargetPath = FilenameUtils.separatorsToWindows(normalizedTargetPath); normalizedBasePath = FilenameUtils.separatorsToWindows(normalizedBasePath); } else { throw new IllegalArgumentException("Unrecognised dir separator '" + pathSeparator + "'"); } String[] base = normalizedBasePath.split(Pattern.quote(pathSeparator)); String[] target = normalizedTargetPath.split(Pattern.quote(pathSeparator)); // First get all the common elements. Store them as a string, // and also count how many of them there are. StringBuffer common = new StringBuffer(); int commonIndex = 0; while (commonIndex < target.length && commonIndex < base.length && target[commonIndex].equals(base[commonIndex])) { common.append(target[commonIndex] + pathSeparator); commonIndex++; } if (commonIndex == 0) { // No single common path element. This most // likely indicates differing drive letters, like C: and D:. // These paths cannot be relativized. throw new PathResolutionException("No common path element found for '" + normalizedTargetPath + "' and '" + normalizedBasePath + "'"); } // The number of directories we have to backtrack depends on whether the base is a file or a dir // For example, the relative path from // // /foo/bar/baz/gg/ff to /foo/bar/baz // // ".." if ff is a file // "../.." if ff is a directory // // The following is a heuristic to figure out if the base refers to a file or dir. It's not perfect, because // the resource referred to by this path may not actually exist, but it's the best I can do boolean baseIsFile = true; File baseResource = new File(normalizedBasePath); if (baseResource.exists()) { baseIsFile = baseResource.isFile(); } else if (basePath.endsWith(pathSeparator)) { baseIsFile = false; } StringBuffer relative = new StringBuffer(); if (base.length != commonIndex) { int numDirsUp = baseIsFile ? base.length - commonIndex - 1 : base.length - commonIndex; for (int i = 0; i < numDirsUp; i++) { relative.append(".." + pathSeparator); } } relative.append(normalizedTargetPath.substring(common.length())); return relative.toString(); }
From source file:com.apporiented.hermesftp.session.impl.FtpSessionContextImpl.java
/** * {@inheritDoc} */ public void setRemoteDir(String remoteDir) { this.remoteDir = FilenameUtils.normalizeNoEndSeparator(remoteDir); }
From source file:io.hawkcd.agent.services.FileManagementService.java
@Override public String pathCombine(String... args) { String output = ""; for (String arg : args) { arg = this.normalizePath(arg); output = FilenameUtils.concat(output, arg); }// ww w .ja v a2 s . c o m FilenameUtils.normalizeNoEndSeparator(output); return output; }
From source file:io.hawkcd.services.FileManagementService.java
@Override public String getAbsolutePath(String path) { String rootPath = this.normalizePath(path); File file = new File(rootPath); if (file.isFile()) { rootPath = file.getAbsolutePath(); FilenameUtils.normalizeNoEndSeparator(rootPath); return rootPath; }/* w w w. j a v a 2 s. co m*/ if (file.isDirectory()) { rootPath = file.getAbsolutePath(); return rootPath; } return ""; }
From source file:com.eryansky.core.web.upload.FileUploadUtils.java
/** * ??/*ww w . j av a2 s. c o m*/ * @param uploadDir * @param filename ?? * @return * @throws java.io.IOException */ private static final File getAbsoluteFile(String uploadDir, String filename) throws IOException { uploadDir = FilenameUtils.normalizeNoEndSeparator(uploadDir); File desc = new File(uploadDir + File.separator + filename); if (!desc.getParentFile().exists()) { desc.getParentFile().mkdirs(); } if (!desc.exists()) { desc.createNewFile(); } return desc; }
From source file:com.ejisto.event.listener.SessionRecorderManager.java
private void modifyWebXml(WebApplicationDescriptor descriptor) throws JDOMException, IOException { String path = FilenameUtils.normalizeNoEndSeparator(descriptor.getDeployablePath()) + File.separator + "WEB-INF" + File.separator + "web.xml"; File webXml = new File(path); if (!webXml.exists()) { throw new IllegalStateException("web.xml doesn't exist"); }//from www.j a v a2 s .co m WebXml xml = WebXmlIo.parseWebXmlFromFile(webXml, null); DescriptorElement param = (DescriptorElement) WebXmlUtils.getContextParam(xml, TARGET_CONTEXT_PATH.getValue()); if (param == null) { WebXmlUtils.addContextParam(xml, TARGET_CONTEXT_PATH.getValue(), descriptor.getContextPath()); } buildFilter(xml); WebXmlUtils.addContextParam(xml, HTTP_INTERFACE_ADDRESS.getValue(), getHttpInterfaceAddress()); WebXmlUtils.addContextParam(xml, SESSION_RECORDING_ACTIVE.getValue(), Boolean.TRUE.toString()); WebXmlIo.writeDescriptor(xml, webXml); }
From source file:net.sourceforge.jencrypt.FileEncrypter.java
private long decryptArchive(String inputFile, String outputFolder) throws Exception { String fileFormatErrorMessage = "Archive '" + inputFile + "' does not conform to the jEncrypt file format."; long fileCounter = 0; FileInputStream fis = getInputFileStream(inputFile); Set<PosixFilePermission> perms = null; byte[] initializationVectorBytes = new byte[CryptoWrapper.AES_BLOCK_SIZE_IN_BYTES]; byte[] saltBytes = new byte[config.getSaltSize()]; byte[] pathSizeBytes = new byte[4]; boolean pathIsFolder = false; outputFolder += File.separator; try {//from w w w. j a v a2s . c o m int nrOfBytesRead = fis.read(saltBytes); nrOfBytesRead += fis.read(initializationVectorBytes); if (nrOfBytesRead == (CryptoWrapper.AES_BLOCK_SIZE_IN_BYTES + config.getSaltSize())) { createCryptoWrappers(initializationVectorBytes, saltBytes); } else { throw new IllegalStateException(fileFormatErrorMessage); } while ((fis.read(pathSizeBytes)) > 0) { // get size of path byte[] pathSizeBytesDec = cryptoWrapperFileNamesAndSizes.cipherBytes(pathSizeBytes, Cipher.DECRYPT_MODE); // 4 byte pathsize int pathSize = Utils.byteArrayToInt(pathSizeBytesDec); // If pathSize > 50MB give warning if (pathSize > 50000000) { logger.warning("Warning: file to decrypt has a full path name of " + Utils.humanReadableByteCount(pathSize) + ".", true); } // get path string byte path[] = new byte[pathSize]; fis.read(path); byte[] pathDec = cryptoWrapperFileNamesAndSizes.cipherBytes(path, Cipher.DECRYPT_MODE); String pathStr = new String(pathDec); // If the path in the archive ends in a Unix file separator then // it's a folder pathIsFolder = (pathStr.charAt(pathStr.length() - 1) == Utils.UNIX_SEPARATOR); // Remove single, double dot path steps and end separator pathStr = FilenameUtils.normalizeNoEndSeparator(pathStr); // get permissions for file or directory byte[] filePermissions = new byte[2]; fis.read(filePermissions); byte[] filePermissionsDec = cryptoWrapperFileNamesAndSizes.cipherBytes(filePermissions, Cipher.DECRYPT_MODE); perms = Utils.byteToPerms(filePermissionsDec); // If the current item is a folder if (pathIsFolder) { File f = new File(outputFolder + pathStr); if (!f.mkdir()) { logger.warning("Error: Unable to create folder '" + pathStr + "'", true); } if (fileSystemIsPosixCompliant) setPosixFilePermissions(f, perms); } else { // get filesize byte b[] = new byte[8]; fis.read(b); byte[] fileSizeDec = cryptoWrapperFileNamesAndSizes.cipherBytes(b, Cipher.DECRYPT_MODE); // 8 byte filesize long fileSize = Utils.byteArrayToLong(fileSizeDec); File fout = new File(outputFolder + pathStr); OutputStream os = null; String message = ""; ProgressInfo progressInfo = null; if (fout.exists()) { logger.warning("Skipping '" + fout.getName() + "'. File already exists.", true); // Use dummy output stream to ensure the cipher counter // (AES CTR mode) will be incremented and have the // correct value for the decryption of the next file. os = new DummyOutputStream(); } else { os = new FileOutputStream(fout); message = getCipherMessage(pathStr, Cipher.DECRYPT_MODE); progressInfo = new FileProgressInfo(message, fileSize, cryptoWrapperFileContent.getReadBufferSize()); } cryptoWrapperFileContent.doCipherOperation(fis, os, fileSize, Cipher.DECRYPT_MODE, progressInfo); os.close(); if (fileSystemIsPosixCompliant) setPosixFilePermissions(fout, perms); // If a file was written to FileOutputStream if (progressInfo != null) { // Increment file counter ++fileCounter; // Ensure next progress info starts on a new line System.out.println(); } } } } catch (NegativeArraySizeException e) { throw new NegativeArraySizeException(fileFormatErrorMessage); } return fileCounter; }