Example usage for org.apache.commons.vfs2 FileObject getName

List of usage examples for org.apache.commons.vfs2 FileObject getName

Introduction

In this page you can find the example usage for org.apache.commons.vfs2 FileObject getName.

Prototype

FileName getName();

Source Link

Document

Returns the name of this file.

Usage

From source file:org.kalypso.commons.io.VFSUtilities.java

/**
 * This function will copy one directory to another one. If the destination base directory does not exist, it will be
 * created.//from www. j  a va 2  s  .c om
 *
 * @param source
 *          The source directory.
 * @param destination
 *          The destination directory.
 * @param overwrite
 *          If set, always overwrite existing and newer files
 */
public static void copyDirectoryToDirectory(final FileObject source, final FileObject destination,
        final boolean overwrite) throws IOException {
    if (!FileType.FOLDER.equals(source.getType()))
        throw new IllegalArgumentException(
                Messages.getString("org.kalypso.commons.io.VFSUtilities.3") + source.getURL()); //$NON-NLS-1$

    if (destination.exists()) {
        if (!FileType.FOLDER.equals(destination.getType()))
            throw new IllegalArgumentException(
                    Messages.getString("org.kalypso.commons.io.VFSUtilities.4") + destination.getURL()); //$NON-NLS-1$
    } else {
        KalypsoCommonsDebug.DEBUG.printf("Creating directory '%s'...%", destination.getName()); //$NON-NLS-1$
        destination.createFolder();
    }

    final FileObject[] children = source.getChildren();
    for (final FileObject child : children) {
        if (FileType.FILE.equals(child.getType())) {
            /* Need a destination file with the same name as the source file. */
            final FileObject destinationFile = destination.resolveFile(child.getName().getBaseName());

            /* Copy ... */
            copyFileTo(child, destinationFile, overwrite);
        } else if (FileType.FOLDER.equals(child.getType())) {
            /* Need the same name for destination directory, as the source directory has. */
            final FileObject destinationDir = destination.resolveFile(child.getName().getBaseName());

            /* Copy ... */
            KalypsoCommonsDebug.DEBUG.printf("Copy directory %s to %s ...", child.getName(), //$NON-NLS-1$
                    destinationDir.getName());
            copyDirectoryToDirectory(child, destinationDir, overwrite);
        } else {
            KalypsoCommonsDebug.DEBUG.printf("Could not determine the file type ...%n"); //$NON-NLS-1$
        }
    }
}

From source file:org.kalypso.commons.io.VFSUtilities.java

/**
 * This function creates a temporary directory, which has a unique file name.
 *
 * @param prefix/*  w  ww .  ja  v  a2  s .  co  m*/
 *          This prefix will be used for the temporary directory.
 * @param parentDir
 *          The parent directory. In it the new directory will be created.
 * @return The new unique directory.
 */
public static FileObject createTempDirectory(final String prefix, final FileObject parentDir,
        final FileSystemManager fsManager) throws FileSystemException {
    while (true) {
        final String dirParent = parentDir.getURL().toExternalForm();
        final String dirName = prefix + String.valueOf(System.currentTimeMillis());

        final FileObject newDir = fsManager.resolveFile(dirParent + "/" + dirName); //$NON-NLS-1$
        if (newDir.exists()) {
            continue;
        }

        KalypsoCommonsDebug.DEBUG.printf("Creating folder %s ...%n", newDir.getName().getPath()); //$NON-NLS-1$
        newDir.createFolder();
        return newDir;
    }
}

From source file:org.kalypso.commons.io.VFSUtilities.java

/**
 * This function deletes the given file. If the file object is a directory, all content and the directory itself will
 * be deleted.//from w  w  w  .  j  ava 2s  .  c  o m
 *
 * @param toDel
 *          The file or directory to be deleted.
 * @return The number of deleted files. 0, if none has been deleted.
 */
public static int deleteFiles(final FileObject toDel) throws FileSystemException {
    if (FileType.FOLDER.equals(toDel.getType())) {
        /* Delete the directory. */
        KalypsoCommonsDebug.DEBUG.printf("Deleting the directory %s ...%n", toDel.getName()); //$NON-NLS-1$
        return toDel.delete(new AllFileSelector());
    } else if (FileType.FILE.equals(toDel.getType())) {
        /* Delete the file. */
        KalypsoCommonsDebug.DEBUG.printf("Deleting the file %s ...%n", toDel.getName()); //$NON-NLS-1$
        if (toDel.delete())
            return 1;

        KalypsoCommonsDebug.DEBUG.printf("Could not delete %s!%n", toDel.getName()); //$NON-NLS-1$

        return 0;
    } else {
        /* The type of the file could not be determined, or it is an imaginary one. */
        KalypsoCommonsDebug.DEBUG.printf("Could not delete %s!%n", toDel.getName()); //$NON-NLS-1$

        return 0;
    }
}

From source file:org.kalypso.commons.io.VFSUtilities.java

/**
 * Moves the complete content of one directory into another.
 *
 * @throws IOException/*from  ww w.jav a  2s .c  o m*/
 *           If the move failed.
 */
public static void moveContents(final File sourceDir, final File dest) throws IOException {
    final FileSystemManager vfsManager = VFSUtilities.getManager();
    final FileObject source = vfsManager.toFileObject(sourceDir);
    final FileObject destDir = vfsManager.toFileObject(dest);

    final FileObject[] findFiles = source.findFiles(new AllFileSelector());
    // Might happen, if source does not exists... shouldn't we check this?
    if (findFiles == null)
        return;

    for (final FileObject fileObject : findFiles) {
        if (FileType.FILE.equals(fileObject.getType())) {
            final String relPath = source.getName().getRelativeName(fileObject.getName());
            final FileObject destFile = destDir.resolveFile(relPath, NameScope.DESCENDENT_OR_SELF);
            final FileObject folder = destFile.getParent();
            folder.createFolder();
            fileObject.moveTo(destFile);
        }
    }
}

From source file:org.kalypso.commons.io.VFSUtilities.java

/**
 * resolves the input stream from given {@link FileObject} based on the file extention, known types are gz and zip, in
 * case of zip archiv the first file will be taken.
 *//*  ww w  .j ava2 s . c  o m*/
public static InputStream getInputStreamFromFileObject(final FileObject file)
        throws FileSystemException, IOException, URISyntaxException {
    /* open stream */
    if ("gz".equalsIgnoreCase(file.getName().getExtension()))//$NON-NLS-1$
        return new GZIPInputStream(new BufferedInputStream(file.getContent().getInputStream()));

    if ("zip".equalsIgnoreCase(file.getName().getExtension()))//$NON-NLS-1$
        return ZipUtilities.getInputStreamForFirstFile(file.getURL());

    return new BufferedInputStream(file.getContent().getInputStream());
}

From source file:org.kalypso.kalypsomodel1d2d.sim.ProcessResultTelemacOperation.java

private IStatus readActWaveRes() {
    if (m_stepDate == ResultManager.STEADY_DATE || m_stepDate == ResultManager.MAXI_DATE
            || m_inputResFileSWAN == null)
        return Status.OK_STATUS;

    try {/*  ww w.  j av  a  2s  .  c o  m*/
        final FileObject lResFile = getOrUnzipResult(m_inputResFileSWAN, m_outputDir);

        KalypsoModel1D2DPlugin.getDefault().getLog().log(new Status(IStatus.INFO,
                KalypsoModel1D2DPlugin.PLUGIN_ID, Messages.getString("ProcessResultsJob.0") + lResFile)); //$NON-NLS-1$

        // only read the *.mat files
        if (lResFile.getName().getFriendlyURI().endsWith(ISimulation1D2DConstants.SIM_SWAN_MAT_RESULT_EXT)) {
            final SWANResultsReader lSWANResultsReader = new SWANResultsReader(lResFile);
            final String timeStringFormatedForSWANOutput = SWANDataConverterHelper
                    .getTimeStringFormatedForSWANOutput(m_stepDate);
            m_mapResults = lSWANResultsReader.readMatResultsFile(timeStringFormatedForSWANOutput);
            KalypsoModel1D2DPlugin.getDefault().getLog()
                    .log(new Status(IStatus.INFO, KalypsoModel1D2DPlugin.PLUGIN_ID,
                            Messages.getString("ProcessResultsJob.1") + timeStringFormatedForSWANOutput)); //$NON-NLS-1$

            ResultMeta1d2dHelper.addDocument(m_unitResultMeta.addStepResult(),
                    ResultMeta1d2dHelper.SWAN_RAW_DATA_META_NAME,
                    Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ProcessResultsJob.13"), //$NON-NLS-1$
                    IDocumentResultMeta.DOCUMENTTYPE.coreDataZip,
                    new Path("../" + ISimulation1D2DConstants.SIM_SWAN_TRIANGLE_FILE + ".zip"), //$NON-NLS-1$//$NON-NLS-2$
                    Status.OK_STATUS, null, null); //$NON-NLS-4$ //$NON-NLS-5$
        }
    } catch (final Throwable e) {
        e.printStackTrace();
        return new Status(IStatus.ERROR, PluginUtilities.id(KalypsoModel1D2DPlugin.getDefault()),
                "could not zip file", e);
    }
    return Status.OK_STATUS;

}

From source file:org.kalypso.kalypsomodel1d2d.sim.ProcessResultTelemacOperation.java

private FileObject getOrUnzipResult(final FileObject input, final File outputDir) {
    FileObject inputFile = input;
    FileObject outputFile = input;
    if (inputFile.getName().getFriendlyURI().endsWith("zip")) //$NON-NLS-1$
    {/*from   ww w  .  j av a 2 s  . c o m*/
        try {
            ZipUtilities.unzip(new File(inputFile.getURL().toURI()), new File(outputDir.toURI()));
            List<String> listNames = ZipUtilities.getFilesNamesFromZip(inputFile.getURL());
            if (listNames.size() > 1 || listNames.isEmpty()) {
                // should not be
                return null;
            }
            outputFile = m_vfsManager.resolveFile(outputDir, listNames.get(0)); //$NON-NLS-1$
        } catch (IOException | URISyntaxException e) {
            e.printStackTrace();
            return null;
        }
    }
    return outputFile;
}

From source file:org.kalypso.kalypsomodel1d2d.sim.ResultManager.java

private void processSWANTabFile(final FileObject swanResOutTabFile, final FileObject swanResShiftFile) {
    final GM_Position lShiftPosition = SWANDataConverterHelper.readCoordinateShiftValues(swanResShiftFile);
    if (lShiftPosition == null) {
        return;/*from  ww w  .  ja  va 2s .  c  o  m*/
    }
    try {
        if (swanResOutTabFile.isContentOpen()) {
            swanResOutTabFile.close();
        }
        final FileObject swanResOutTabFileBackUp = swanResOutTabFile.getParent()
                .resolveFile(swanResOutTabFile.getName().getBaseName() + ".bck"); //$NON-NLS-1$
        swanResOutTabFile.moveTo(swanResOutTabFileBackUp);

        // int lIntLinesCounter = 0;
        final OutputStream lOutStream = swanResOutTabFile.getContent().getOutputStream();
        final DataInputStream lInDataStream = new DataInputStream(
                swanResOutTabFileBackUp.getContent().getInputStream());
        BufferedReader streamReader = new BufferedReader(new InputStreamReader(lInDataStream));
        final Formatter lFormatter = new Formatter(lOutStream, Charset.defaultCharset().name(), Locale.US);
        while (lInDataStream.available() != 0) {
            final String lStrTmpLine = streamReader.readLine().trim();
            // ++lIntLinesCounter;
            if (lStrTmpLine.startsWith("%")) { //$NON-NLS-1$
                lFormatter.format("%s\n", lStrTmpLine); //$NON-NLS-1$
                continue;
            }
            final StringTokenizer lStrTokenizer = new StringTokenizer(lStrTmpLine, " "); //$NON-NLS-1$
            int lIntTokenCounter = 0;
            String lStrNewLine = ""; //$NON-NLS-1$
            while (lStrTokenizer.hasMoreTokens()) {
                final String lStrToken = lStrTokenizer.nextToken();
                if (lIntTokenCounter == 1) {
                    lStrNewLine += String.format(Locale.US, "%.5f\t", //$NON-NLS-1$
                            NumberUtils.parseQuietDouble(lStrToken) + lShiftPosition.getX());
                } else if (lIntTokenCounter == 2) {
                    lStrNewLine += String.format(Locale.US, "%.5f\t", //$NON-NLS-1$
                            NumberUtils.parseQuietDouble(lStrToken) + lShiftPosition.getY());
                } else {
                    lStrNewLine += lStrToken + "\t"; //$NON-NLS-1$
                }
                lIntTokenCounter++;
            }
            lFormatter.format("%s\n", lStrNewLine); //$NON-NLS-1$

        }
        lFormatter.close();
        lInDataStream.close();
        lOutStream.close();
    } catch (final Exception e) {
        return;
    }

    return;
}

From source file:org.kalypso.kalypsomodel1d2d.sim.ResultManager.java

private IStatus processResultFile(final FileObject file, final ICalcUnitResultMeta calcUnitResultMeta,
        final IProgressMonitor monitor, final boolean doFullEvaluate) throws CoreException {
    try {//from www. j a v  a2  s.  co  m
        final String filename = file.getName().getBaseName();

        if (ISimulation1D2DConstants.MODEL_2D.equals(filename))
            return Status.OK_STATUS;
        Date stepDate = null;
        String resultFileName = FileUtilities.nameWithoutExtension(filename);

        // check if the given result file is already compressed
        if (filename != null && filename.endsWith(".2d.zip")) //$NON-NLS-1$
        {
            resultFileName = filename;
            if (file.toString().startsWith(STEADY_PREFIX))
                stepDate = STEADY_DATE;
            else if (file.toString().startsWith(MAXI_PREFIX))
                stepDate = MAXI_DATE;
            else
                stepDate = ResultMeta1d2dHelper.resolveDateFromResultStep(file);

            if (m_resultDirSWAN == null) {
                final IPath lPath = ResultMeta1d2dHelper.getSavedPathFromResultData(calcUnitResultMeta,
                        ResultMeta1d2dHelper.SWAN_RAW_DATA_META_NAME);
                if (lPath != null && lPath.toFile().exists()) {
                    try {
                        m_resultDirSWAN = file.getParent().getParent().resolveFile(lPath.toOSString());
                    } catch (final Exception e) {
                        m_geoLog.formatLog(IStatus.INFO, CODE_RUNNING_FINE,
                                Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ResultManager.15"), //$NON-NLS-1$
                                resultFileName);
                    }
                }
            }
        } else
            stepDate = findStepDate(file);

        if (stepDate == null)
            return Status.OK_STATUS;

        m_geoLog.formatLog(IStatus.INFO, CODE_RUNNING_FINE,
                Messages.getString("org.kalypso.kalypsomodel1d2d.sim.ResultManager.14"), resultFileName); //$NON-NLS-1$

        // start a job for each unknown 2d file.
        final String outDirName = NodeResultHelper.createOutDirName(stepDate);

        final File resultOutputDir = new File(m_outputDir, outDirName);
        resultOutputDir.mkdirs();
        final ProcessResult2DOperation processResultsJob = new ProcessResult2DOperation(file, m_resultDirSWAN,
                resultOutputDir, m_flowModel, m_controlModel, m_discModel, m_parameters, stepDate,
                calcUnitResultMeta, doFullEvaluate, m_geoLog);
        final IStatus result = processResultsJob.execute(monitor);

        m_minMaxCatcher.addNodeResultMinMaxCatcher(processResultsJob.getMinMaxData());

        // TODO: set this status as step result status?
        return result;
    } finally {
        ProgressUtilities.done(monitor);
    }
}

From source file:org.kalypso.kalypsomodel1d2d.sim.ResultManager.java

private Date findStepDate(final FileObject file) {
    final String filename = file.getName().getBaseName();

    if (filename.startsWith(STEADY_PREFIX))
        return STEADY_DATE;

    if (filename.startsWith(MAXI_PREFIX))
        return MAXI_DATE;

    if (filename.startsWith(MINI_PREFIX) || filename.startsWith(MODEL_PREFIX))
        return null;

    // check if the given result file is already compressed
    if (filename.endsWith(".2d.zip")) //$NON-NLS-1$
        return ResultMeta1d2dHelper.resolveDateFromResultStep(file);

    final String name = FilenameUtils.removeExtension(filename);
    final int step = Integer.parseInt(name.substring(1));

    final IComponent componentTime = ComponentUtilities.findComponentByID(m_timeSteps.getComponents(),
            Kalypso1D2DDictConstants.DICT_COMPONENT_TIME);
    int indexTime = m_timeSteps.indexOfComponent(componentTime);
    final XMLGregorianCalendar stepCal = (XMLGregorianCalendar) m_timeSteps.get(step).getValue(indexTime);
    return DateUtilities.toDate(stepCal);
}