Example usage for org.apache.commons.io FilenameUtils separatorsToSystem

List of usage examples for org.apache.commons.io FilenameUtils separatorsToSystem

Introduction

In this page you can find the example usage for org.apache.commons.io FilenameUtils separatorsToSystem.

Prototype

public static String separatorsToSystem(String path) 

Source Link

Document

Converts all separators to the system separator.

Usage

From source file:com.photon.maven.plugins.android.AbstractAndroidMojoTestCase.java

/**
 * Copy the project specified into a temporary testing directory. Create the {@link MavenProject} and
 * {@link ManifestUpdateMojo}, configure it from the <code>plugin-config.xml</code> and return the created Mojo.
 * <p>/*  w w w .jav  a2  s . c  om*/
 * Note: only configuration entries supplied in the plugin-config.xml are presently configured in the mojo returned.
 * That means and 'default-value' settings are not automatically injected by this testing framework (or plexus
 * underneath that is suppling this functionality)
 * 
 * @param resourceProject
 *            the name of the goal to look for in the <code>plugin-config.xml</code> that the configuration will be
 *            pulled from.
 * @param resourceProject
 *            the resourceProject path (in src/test/resources) to find the example/test project.
 * @return the created mojo (unexecuted)
 * @throws Exception
 *             if there was a problem creating the mojo.
 */
protected T createMojo(String resourceProject) throws Exception {
    // Establish test details project example
    String testResourcePath = "src/test/resources/" + resourceProject;
    testResourcePath = FilenameUtils.separatorsToSystem(testResourcePath);
    File exampleDir = new File(getBasedir(), testResourcePath);
    Assert.assertTrue("Path should exist: " + exampleDir, exampleDir.exists());

    // Establish the temporary testing directory.
    String testingPath = "target/tests/" + this.getClass().getSimpleName() + "." + getName();
    testingPath = FilenameUtils.separatorsToSystem(testingPath);
    File testingDir = new File(getBasedir(), testingPath);

    if (testingDir.exists()) {
        FileUtils.cleanDirectory(testingDir);
    } else {
        Assert.assertTrue("Could not create directory: " + testingDir, testingDir.mkdirs());
    }

    // Copy project example into temporary testing directory
    // to avoid messing up the good source copy, as mojo can change
    // the AndroidManifest.xml file.
    FileUtils.copyDirectory(exampleDir, testingDir);

    // Prepare MavenProject
    final MavenProject project = new MojoProjectStub(testingDir);

    // Setup Mojo
    PlexusConfiguration config = extractPluginConfiguration("android-maven-plugin", project.getFile());
    @SuppressWarnings("unchecked")
    final T mojo = (T) lookupMojo(getPluginGoalName(), project.getFile());

    // Inject project itself
    setVariableValueToObject(mojo, "project", project);

    // Configure the rest of the pieces via the PluginParameterExpressionEvaluator
    //  - used for ${plugin.*}
    MojoDescriptor mojoDesc = new MojoDescriptor();
    // - used for error messages in PluginParameterExpressionEvaluator
    mojoDesc.setGoal(getPluginGoalName());
    MojoExecution mojoExec = new MojoExecution(mojoDesc);
    // - Only needed if we start to use expressions like ${settings.*}, ${localRepository}, ${reactorProjects}
    // MavenSession context = null; // Messy to declare, would rather avoid using it.
    // - Used for ${basedir} relative paths
    PathTranslator pathTranslator = new DefaultPathTranslator();
    // - Declared to prevent NPE from logging events in maven core
    Logger logger = new ConsoleLogger(Logger.LEVEL_DEBUG, mojo.getClass().getName());

    MavenSession context = createMock(MavenSession.class);

    expect(context.getExecutionProperties()).andReturn(project.getProperties());
    expect(context.getCurrentProject()).andReturn(project);
    replay(context);

    // Declare evalator that maven itself uses.
    ExpressionEvaluator evaluator = new PluginParameterExpressionEvaluator(context, mojoExec, pathTranslator,
            logger, project, project.getProperties());
    // Lookup plexus configuration component
    ComponentConfigurator configurator = (ComponentConfigurator) lookup(ComponentConfigurator.ROLE, "basic");
    // Configure mojo using above
    ConfigurationListener listener = new DebugConfigurationListener(logger);
    configurator.configureComponent(mojo, config, evaluator, getContainer().getContainerRealm(), listener);

    return mojo;
}

From source file:net.erdfelt.android.sdkfido.configer.ConfigCmdLineParserTest.java

@Test
public void testSetDeepOption() throws CmdLineParseException {
    FetcherConfig config = new FetcherConfig();

    File expectedDir = new File(SystemUtils.getUserHome(), FilenameUtils.separatorsToSystem(".sdkfido/work"));

    Assert.assertThat("Config.dryRun", config.isDryRun(), is(false));
    Assert.assertThat("Config.workDir", config.getWorkDir(), is(expectedDir));
    Assert.assertThat("Config.maven.groupId", config.getMaven().getGroupId(), is("com.android.sdk"));

    File otherWork = testingdir.getFile("work");

    StringWriter capture = new StringWriter();
    ConfigCmdLineParser parser = new ConfigCmdLineParser(this, config);
    parser.setOut(capture);/*from  w  w w  .  j a  va 2s  . c o  m*/
    String[] args = { "--dryRun", "true", "--workDir", otherWork.getAbsolutePath(), "--maven.groupId",
            "com.android.sdk.testee" };
    parser.parse(args);

    Assert.assertThat("Config.dryRun", config.isDryRun(), is(true));
    Assert.assertThat("Config.workDir", config.getWorkDir(), is(otherWork));
    Assert.assertThat("Config.maven.groupId", config.getMaven().getGroupId(), is("com.android.sdk.testee"));
}

From source file:dynamicrefactoring.domain.TestImport.java

/**
 * Comprueba que el proceso de importacin de la refactorizacin dinmica
 * Rename Class a partir de un directorio temporal "./temp" se ha realizado
 * correctamente.//  w ww. j  ava2 s. c  om
 * 
 * @throws XMLRefactoringReaderException
 *             XMLRefactoringReaderException.
 * @throws IOException
 *             IOException.
 */
@Test
public void testImportRefactoring() throws XMLRefactoringReaderException, IOException {

    // Eliminamos alguno de los ficheros .class requeridos por dicha
    // refactorizacin para
    // comprobar que tras la importacin esos ficheros se encuentran donde
    // deben
    final String renameClassFile = getMoonRefactoryDir() + "concreteaction" + File.separatorChar
            + "RenameClass.class";
    final String notExistsClassWithNameClassFile = getMoonRefactoryDir() + "concretepredicate"
            + File.separatorChar + "NotExistsClassWithName.class";

    FileManager.deleteFile(renameClassFile);
    FileManager.deleteFile(notExistsClassWithNameClassFile);

    RefactoringCatalogStub catalog = new RefactoringCatalogStub();
    // Importamos la refactorizacin
    ExportImportUtilities.importRefactoring(
            FilenameUtils.separatorsToSystem(".\\temp\\Rename Class\\Rename Class.xml"), false, catalog);

    assertTrue(catalog.hasRefactoring("Rename Class"));

}

From source file:com.ariht.maven.plugins.config.DirectoryReader.java

private List<File> processFilesToIgnore(final List<String> filesToIgnore) {
    if (filesToIgnore == null || filesToIgnore.isEmpty()) {
        return EMPTY_FILE_LIST;
    }/*from ww w.j  av  a  2 s  .c  o  m*/
    final List<File> filesIgnored = new ArrayList<File>(filesToIgnore.size());
    for (String fileToIgnore : new LinkedHashSet<String>(filesToIgnore)) {
        if (StringUtils.isNotBlank(fileToIgnore)) {
            fileToIgnore = FilenameUtils.separatorsToSystem(FilenameUtils.normalize(fileToIgnore.trim()));
            final File file = new File(fileToIgnore);
            if (file.exists()) {
                log.debug("Adding ignore for file: " + file.getAbsolutePath());
                filesIgnored.add(file);
            }
        }
    }
    return filesIgnored;
}

From source file:dynamicrefactoring.domain.TestExport.java

/**
 * Comprueba que el proceso de exportacin de la refactorizacin dinmica
 * Rename Class a un directorio temporal "./temp" teniendo en cuenta que uno
 * de los ficheros .class requeridos no se encuentra en el repositorio.
 * /*www .ja  va 2 s .  c  om*/
 * @throws XMLRefactoringReaderException
 *             XMLRefactoringReaderException.
 * @throws IOException
 *             IOException.
 */
@Test
public void testExportFileNotExists() throws XMLRefactoringReaderException, IOException {

    final String refactoringName = "RenameClass.class";

    final String definitionFolderName = new File(RENAME_CLASS_XML_FILE).getParentFile().getName();
    final String ficheroOrigen = FilenameUtils.separatorsToSystem(RefactoringConstants.REFACTORING_CLASSES_DIR
            + "repository\\moon\\concreteaction\\" + refactoringName);

    try {
        // Copiamos uno de los ficheros .class que necesita la
        // refactorizacin al directorio
        // temporal y luego lo borramos para que posteriormente salte la
        // excepcin.

        FileUtils.copyFileToDirectory(new File(ficheroOrigen), new File(TEMP_DIR));
        FileManager.deleteFile(ficheroOrigen);

        ExportImportUtilities.exportRefactoring(TEMP_DIR, RENAME_CLASS_XML_FILE, false);

    } catch (IOException e) {
        // Comprobamos que el directorio en el que se generara la
        // refactorizacin no existe al no
        // poderse completar la operacin.
        assertEquals(false, new File(TEMP_DIR + File.separatorChar + definitionFolderName).exists());

        // Reponemos el fichero .class que habamos borrado para comprobar
        // que saltaba la
        // excepcin.

        FileManager.copyFile(new File(TEMP_DIR + File.separatorChar + refactoringName),
                new File(ficheroOrigen));

        assertEquals(true, new File(ficheroOrigen).exists());

    }
}

From source file:com.photon.maven.plugins.android.standalonemojos.MojoProjectStub.java

/**
 * Normalize a path.//from  ww  w . j  a  v a2s.c  o  m
 * <p>
 * Ensure path is absolute, and has proper system file separators.
 * 
 * @param path the raw path.
 * @return
 */
private File normalize(final String path) {
    String ospath = FilenameUtils.separatorsToSystem(path);
    File file = new File(ospath);
    if (file.isAbsolute()) {
        return file;
    } else {
        return new File(getBasedir(), ospath);
    }
}

From source file:edu.ur.file.db.FileDatabaseTest.java

/**
 * Test adding a file to the file database.
 * @throws LocationAlreadyExistsException 
 * @throws IllegalFileSystemNameException 
 *//*  ww  w . j av  a  2  s.  co m*/
public void addFileTest() throws LocationAlreadyExistsException, IllegalFileSystemNameException {
    DefaultFileServer fs = new DefaultFileServer();

    String databasePath = FilenameUtils.separatorsToSystem(properties.getProperty("FileDatabaseTest.db_path"));
    assert databasePath != null : "Path should not be null";
    DefaultFileDatabase fileDatabaseImpl = fs.createFileDatabase("displayName", "dbName_1", databasePath,
            "dbDescription");

    fileDatabaseImpl.setId(44l);

    TreeFolderInfo folder = fileDatabaseImpl.createRootFolder("rootFolder", "folderName");
    TreeFolderInfo child = folder.createChild("newDbFolder", "newDbFolder");

    // set the default file storage
    assert fileDatabaseImpl.setCurrentFileStore(child.getName()) : "the new default folder should be set";

    // create the first file to store in the temporary folder
    String tempDirectory = properties.getProperty("file_db_temp_directory");
    File directory = new File(tempDirectory);

    // helper to create the file
    FileUtil testUtil = new FileUtil();
    testUtil.createDirectory(directory);

    File f = testUtil.creatFile(directory, "testFile", "Hello  -  This file to add to a file info object");
    FileInfo info = fileDatabaseImpl.addFile(f, "uniqueFileName");

    assert fileDatabaseImpl.getFile(info.getName()) != null : "File should be found";

    fs.deleteFileServer();
}

From source file:net.erdfelt.android.sdkfido.configer.ConfigCmdLineParserTest.java

@Test
public void testSetEnumOption() throws CmdLineParseException {
    FetcherConfig config = new FetcherConfig();

    File expectedDir = new File(SystemUtils.getUserHome(), FilenameUtils.separatorsToSystem(".sdkfido/work"));

    Assert.assertThat("Config.dryRun", config.isDryRun(), is(false));
    Assert.assertThat("Config.workDir", config.getWorkDir(), is(expectedDir));
    Assert.assertThat("Config.outputType", config.getOutputType(), is(OutputProjectType.SDK));

    File otherWork = testingdir.getFile("work");

    StringWriter capture = new StringWriter();
    ConfigCmdLineParser parser = new ConfigCmdLineParser(this, config);
    parser.setOut(capture);/*from www  . ja va2s.  co  m*/
    String[] args = { "--dryRun", "true", "--workDir", otherWork.getAbsolutePath(), "--outputType", "SDK" };
    parser.parse(args);

    Assert.assertThat("Config.dryRun", config.isDryRun(), is(true));
    Assert.assertThat("Config.workDir", config.getWorkDir(), is(otherWork));
    Assert.assertThat("Config.outputType", config.getOutputType(), is(OutputProjectType.SDK));
}

From source file:dynamicrefactoring.domain.TestImport.java

/**
 * Comprueba que el proceso de importacin de la refactorizacin dinmica
 * Rename Class a partir de un directorio temporal "./temp" devuelve la
 * cadena NotExistsClassWithName en el caso de borrar este mecanismo de la
 * carpeta donde esta exportada la refactorizacin y del repositorio.
 * //from  w  ww .jav a2 s  .  co  m
 * @throws XMLRefactoringReaderException
 *             XMLRefactoringReaderException.
 * @throws IOException
 *             IOException.
 */
@Test
public void testImportErroneousRefactoring() throws XMLRefactoringReaderException, IOException {

    // Eliminamos alguno de los ficheros .class requeridos por dicha
    // refactorizacin tanto
    // del repositorio como de la carpeta exportada para ver que la
    // improtacin devuelve
    //el nombre de este fichero indicando que no existe.
    final String notExistClassWithNameClassFile = FilenameUtils
            .separatorsToSystem(getMoonRefactoryDir() + "concretepredicate\\NotExistsClassWithName.class");
    final String tempRenameNotExistClassWithNameClassFile = FilenameUtils
            .separatorsToSystem(TEMP_DIR + "\\Rename Class\\NotExistsClassWithName.class");
    final String tempNotExistClassWithNameClassFile = TEMP_DIR + File.separatorChar
            + "NotExistsClassWithName.class";

    FileManager.copyFile(new File(notExistClassWithNameClassFile),
            new File(tempNotExistClassWithNameClassFile));
    FileManager.deleteFile(notExistClassWithNameClassFile);
    FileManager.deleteFile(tempRenameNotExistClassWithNameClassFile);

    // comprobamos que el nombre devuelto es el del fichero que no
    // encuentra.
    try {
        // Importamos la refactorizacin
        ExportImportUtilities.importRefactoring(
                FilenameUtils.separatorsToSystem(TEMP_DIR + "\\Rename Class\\Rename Class.xml"), false,
                XMLRefactoringsCatalog.getInstance());
        fail("No salto la excepcion esperada.");
    } catch (FileNotFoundException e) {
        // Comprobamos que no existe el fichero del mecanismo que hemos
        // borrado de la carpeta
        // de la refactorizacin y del repositorio.
        assertEquals(false, new File(notExistClassWithNameClassFile).exists());
    } finally {
        // Reponemos el mecanismo
        FileManager.copyFile(new File(tempNotExistClassWithNameClassFile),
                new File(notExistClassWithNameClassFile));
    }

}

From source file:au.org.ala.delta.model.ResourceSettings.java

/**
 * Checks if a file exists on the resource path.
 * //from w ww  .j  a  v a2s  .  c  om
 * @param file
 *            the file to check.
 * @return true if the supplied file is on the resource path.
 */
public boolean isOnResourcePath(File file) {
    String filePath = file.getParent();
    List<String> resourcePaths = getResourcePathLocations();
    for (String path : resourcePaths) {
        if (filePath.equals(FilenameUtils.separatorsToSystem(path))) {
            return true;
        }
    }
    return false;
}