Example usage for java.io File equals

List of usage examples for java.io File equals

Introduction

In this page you can find the example usage for java.io File equals.

Prototype

public boolean equals(Object obj) 

Source Link

Document

Tests this abstract pathname for equality with the given object.

Usage

From source file:org.openhab.ui.cometvisu.internal.servlet.CometVisuServlet.java

/**
 * Process the actual request.//from www.  j  av  a 2  s  . c o  m
 *
 * @param request
 *            The request to be processed.
 * @param response
 *            The response to be created.
 * @param content
 *            Whether the request body should be written (GET) or not
 *            (HEAD).
 * @throws IOException
 *             If something fails at I/O level.
 *
 * @author BalusC
 * @link
 *       http://balusc.blogspot.com/2009/02/fileservlet-supporting-resume-and
 *       .html
 */
private void processStaticRequest(File file, HttpServletRequest request, HttpServletResponse response,
        boolean content) throws IOException {
    // Validate the requested file
    // ------------------------------------------------------------
    if (file == null) {
        // Get requested file by path info.
        String requestedFile = request.getPathInfo();

        // Check if file is actually supplied to the request URL.
        if (requestedFile == null) {
            // Do your thing if the file is not supplied to the request URL.
            // Throw an exception, or send 404, or show default/warning
            // page, or
            // just ignore it.
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // URL-decode the file name (might contain spaces and on) and
        // prepare
        // file object.
        file = new File(rootFolder, URLDecoder.decode(requestedFile, "UTF-8"));
    }
    if (file.equals(rootFolder) || (file.exists() && file.isDirectory())) {
        file = new File(file, "index.html");
    }

    // Check if file actually exists in filesystem.
    if (!file.exists()) {
        // show installation hints if the CometVisu-Clients main index.html is requested but cannot be found
        if (file.getParentFile().equals(rootFolder)
                && (file.getName().equalsIgnoreCase("index.html") || file.getName().length() == 0)) {
            // looking for CometVisu clients index.html file
            String path = null;
            File folder = file.isDirectory() ? file : file.getParentFile();
            if (folder.exists()) {
                File index = ClientInstaller.findClientRoot(folder, "index.html");
                path = index.exists() ? index.getPath().replaceFirst(rootFolder.getPath() + "/", "") : null;
            }
            if (path != null) {
                // forward to position
                response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
                response.setHeader("Location", path + "?" + request.getQueryString());
            } else {
                showInstallationHint(request, response);
            }
        } else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
        return;
    }

    // Prepare some variables. The ETag is an unique identifier of the file.
    String fileName = file.getName();
    long length = file.length();
    long lastModified = file.lastModified();
    String eTag = fileName + "_" + length + "_" + lastModified;
    long expires = System.currentTimeMillis() + DEFAULT_EXPIRE_TIME;

    // Validate request headers for caching
    // ---------------------------------------------------

    // If-None-Match header should contain "*" or ETag. If so, then return
    // 304.
    String ifNoneMatch = request.getHeader("If-None-Match");
    if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        response.setHeader("ETag", eTag); // Required in 304.
        response.setDateHeader("Expires", expires); // Postpone cache with 1
                                                    // week.
        return;
    }

    // If-Modified-Since header should be greater than LastModified. If so,
    // then return 304.
    // This header is ignored if any If-None-Match header is specified.
    long ifModifiedSince = request.getDateHeader("If-Modified-Since");
    if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        response.setHeader("ETag", eTag); // Required in 304.
        response.setDateHeader("Expires", expires); // Postpone cache with 1
                                                    // week.
        return;
    }

    // Validate request headers for resume
    // ----------------------------------------------------

    // If-Match header should contain "*" or ETag. If not, then return 412.
    String ifMatch = request.getHeader("If-Match");
    if (ifMatch != null && !matches(ifMatch, eTag)) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // If-Unmodified-Since header should be greater than LastModified. If
    // not, then return 412.
    long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since");
    if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) {
        response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED);
        return;
    }

    // Validate and process range
    // -------------------------------------------------------------

    // Prepare some variables. The full Range represents the complete file.
    Range full = new Range(0, length - 1, length);
    List<Range> ranges = new ArrayList<Range>();

    // Validate and process Range and If-Range headers.
    String range = request.getHeader("Range");
    if (range != null) {

        // Range header should match format "bytes=n-n,n-n,n-n...". If not,
        // then return 416.
        if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) {
            response.setHeader("Content-Range", "bytes */" + length); // Required
                                                                      // in
                                                                      // 416.
            response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
            return;
        }

        // If-Range header should either match ETag or be greater then
        // LastModified. If not,
        // then return full file.
        String ifRange = request.getHeader("If-Range");
        if (ifRange != null && !ifRange.equals(eTag)) {
            try {
                long ifRangeTime = request.getDateHeader("If-Range"); // Throws
                                                                      // IAE
                                                                      // if
                                                                      // invalid.
                if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModified) {
                    ranges.add(full);
                }
            } catch (IllegalArgumentException ignore) {
                ranges.add(full);
            }
        }

        // If any valid If-Range header, then process each part of byte
        // range.
        if (ranges.isEmpty()) {
            for (String part : range.substring(6).split(",")) {
                // Assuming a file with length of 100, the following
                // examples returns bytes at:
                // 50-80 (50 to 80), 40- (40 to length=100), -20
                // (length-20=80 to length=100).
                long start = sublong(part, 0, part.indexOf("-"));
                long end = sublong(part, part.indexOf("-") + 1, part.length());

                if (start == -1) {
                    start = length - end;
                    end = length - 1;
                } else if (end == -1 || end > length - 1) {
                    end = length - 1;
                }

                // Check if Range is syntactically valid. If not, then
                // return 416.
                if (start > end) {
                    response.setHeader("Content-Range", "bytes */" + length); // Required
                                                                              // in
                                                                              // 416.
                    response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                    return;
                }

                // Add range.
                ranges.add(new Range(start, end, length));
            }
        }
    }

    // Prepare and initialize response
    // --------------------------------------------------------

    // Get content type by file name and set default GZIP support and
    // content disposition.
    String contentType = getServletContext().getMimeType(fileName);
    boolean acceptsGzip = false;
    String disposition = "inline";

    // If content type is unknown, then set the default value.
    // For all content types, see:
    // http://www.w3schools.com/media/media_mimeref.asp
    // To add new content types, add new mime-mapping entry in web.xml.
    if (contentType == null) {
        contentType = "application/octet-stream";
    }

    // If content type is text, then determine whether GZIP content encoding
    // is supported by
    // the browser and expand content type with the one and right character
    // encoding.
    if (contentType.startsWith("text")) {
        String acceptEncoding = request.getHeader("Accept-Encoding");
        acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip");
        contentType += ";charset=UTF-8";
    }

    // Else, expect for images, determine content disposition. If content
    // type is supported by
    // the browser, then set to inline, else attachment which will pop a
    // 'save as' dialogue.
    else if (!contentType.startsWith("image")) {
        String accept = request.getHeader("Accept");
        disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment";
    }

    response.setBufferSize(DEFAULT_BUFFER_SIZE);
    response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\"");
    response.setHeader("Accept-Ranges", "bytes");
    response.setHeader("ETag", eTag);
    response.setDateHeader("Last-Modified", lastModified);
    response.setDateHeader("Expires", expires);

    // Send requested file (part(s)) to client
    // ------------------------------------------------

    // Prepare streams.
    RandomAccessFile input = null;
    OutputStream output = null;

    try {
        // Open streams.
        input = new RandomAccessFile(file, "r");
        output = response.getOutputStream();

        if (ranges.isEmpty() || ranges.get(0) == full) {

            // Return full file.
            Range r = full;
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);

            if (content) {
                if (acceptsGzip) {
                    // The browser accepts GZIP, so GZIP the content.
                    response.setHeader("Content-Encoding", "gzip");
                    output = new GZIPOutputStream(output, DEFAULT_BUFFER_SIZE);
                } else {
                    // Content length is not directly predictable in case of
                    // GZIP.
                    // So only add it if there is no means of GZIP, else
                    // browser will hang.
                    response.setHeader("Content-Length", String.valueOf(r.length));
                }

                // Copy full range.
                copy(input, output, r.start, r.length);
            }

        } else if (ranges.size() == 1) {

            // Return single part of file.
            Range r = ranges.get(0);
            response.setContentType(contentType);
            response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total);
            response.setHeader("Content-Length", String.valueOf(r.length));
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            if (content) {
                // Copy single part range.
                copy(input, output, r.start, r.length);
            }

        } else {

            // Return multiple parts of file.
            response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY);
            response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206.

            if (content) {
                // Cast back to ServletOutputStream to get the easy println
                // methods.
                ServletOutputStream sos = (ServletOutputStream) output;

                // Copy multi part range.
                for (Range r : ranges) {
                    // Add multipart boundary and header fields for every
                    // range.
                    sos.println();
                    sos.println("--" + MULTIPART_BOUNDARY);
                    sos.println("Content-Type: " + contentType);
                    sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total);

                    // Copy single part range of multi part range.
                    copy(input, output, r.start, r.length);
                }

                // End with multipart boundary.
                sos.println();
                sos.println("--" + MULTIPART_BOUNDARY + "--");
            }
        }
    } finally {
        // Gently close streams.
        close(output);
        close(input);
    }
}

From source file:org.eclipse.swt.examples.fileviewer.FileViewer.java

/**
 * Handles a drop on a dropTarget.//from ww  w.j  a  v a  2s .  co m
 * <p>
 * Used in drop().<br>
 * Note event.detail is modified by this method.
 * </p>
 * 
 * @param event
 *            the DropTargetEvent passed as parameter to the drop() method
 * @param targetFile
 *            the File representing the drop target location under
 *            inspection, or null if none
 */
private void dropTargetHandleDrop(DropTargetEvent event, File targetFile) {
    Log.i("");
    // Get dropped data (an array of filenames)
    if (!dropTargetValidate(event, targetFile))
        return;
    final String[] sourceNames = (String[]) event.data;
    if (sourceNames == null)
        event.detail = DND.DROP_NONE;
    if (event.detail == DND.DROP_NONE)
        return;

    // Open progress dialog
    progressDialog = new ProgressDialog(shell,
            (event.detail == DND.DROP_MOVE) ? ProgressDialog.MOVE : ProgressDialog.COPY);
    progressDialog.setTotalWorkUnits(sourceNames.length);
    progressDialog.open();

    // Copy each file
    Vector /* of File */ processedFiles = new Vector();
    for (int i = 0; (i < sourceNames.length) && (!progressDialog.isCancelled()); i++) {
        final File source = new File(sourceNames[i]);
        final File dest = new File(targetFile, source.getName());
        if (source.equals(dest))
            continue; // ignore if in same location

        progressDialog.setDetailFile(source, ProgressDialog.COPY);
        while (!progressDialog.isCancelled()) {
            if (copyFileStructure(source, dest)) {
                processedFiles.add(source);
                break;
            } else if (!progressDialog.isCancelled()) {
                if (event.detail == DND.DROP_MOVE && (!isDragging)) {
                    // It is not possible to notify an external drag source
                    // that a drop
                    // operation was only partially successful. This is
                    // particularly a
                    // problem for DROP_MOVE operations since unless the
                    // source gets
                    // DROP_NONE, it will delete the original data including
                    // bits that
                    // may not have been transferred successfully.
                    MessageBox box = new MessageBox(shell, SWT.ICON_ERROR | SWT.RETRY | SWT.CANCEL);
                    box.setText(getResourceString("dialog.FailedCopy.title"));
                    box.setMessage(
                            getResourceString("dialog.FailedCopy.description", new Object[] { source, dest }));
                    int button = box.open();
                    if (button == SWT.CANCEL) {
                        i = sourceNames.length;
                        event.detail = DND.DROP_NONE;
                        break;
                    }
                } else {
                    // We can recover gracefully from errors if the drag
                    // source belongs
                    // to this application since it will look at
                    // processedDropFiles.
                    MessageBox box = new MessageBox(shell, SWT.ICON_ERROR | SWT.ABORT | SWT.RETRY | SWT.IGNORE);
                    box.setText(getResourceString("dialog.FailedCopy.title"));
                    box.setMessage(
                            getResourceString("dialog.FailedCopy.description", new Object[] { source, dest }));
                    int button = box.open();
                    if (button == SWT.ABORT)
                        i = sourceNames.length;
                    if (button != SWT.RETRY)
                        break;
                }
            }
            progressDialog.addProgress(1);
        }
    }
    if (isDragging) {
        // Remember exactly which files we processed
        processedDropFiles = ((File[]) processedFiles.toArray(new File[processedFiles.size()]));
    } else {
        progressDialog.close();
        progressDialog = null;
    }
    notifyRefreshFiles(new File[] { targetFile });
}

From source file:org.eclipse.swt.examples.fileviewer.FileViewer.java

/**
 * Notifies the application components that a new current directory has been
 * selected/*from  w ww . j  a  v  a2s  .  c o  m*/
 * 
 * @param dir
 *            the directory that was selected, null is ignored
 */
void notifySelectedDirectory(File dir, boolean select) {
    if (dir == null)
        return;
    // Log.i("notifySelectedDirectory:" + dir.getPath());
    if (currentDirectory != null && dir.equals(currentDirectory))
        return;
    currentDirectory = dir;
    notifySelectedFiles(null);

    /*
     * Shell: Sets the title to indicate the selected directory
     */
    shell.setText(getResourceString("Title", new Object[] { mDeviceName, currentDirectory.getPath() }));

    /*
     * Table view: Displays the contents of the selected directory.
     */
    workerUpdate(dir, false);

    /*
     * Combo view: Sets the combo box to point to the selected directory.
     */
    final File[] comboRoots = (File[]) combo.getData(COMBODATA_ROOTS);
    int comboEntry = -1;
    if (comboRoots != null) {
        for (int i = 0; i < comboRoots.length; ++i) {
            if (dir.equals(comboRoots[i])) {
                comboEntry = i;
                break;
            }
        }
    }
    if (comboEntry == -1)
        combo.setText(dir.getPath());
    else
        combo.select(comboEntry);

    /*
     * Tree view: If not already expanded, recursively expands the parents
     * of the specified directory until it is visible.
     */
    Vector /* of File */ path = new Vector();
    // Build a stack of paths from the root of the tree
    while (dir != null) {
        path.add(dir);
        dir = dir.getParentFile();
    }
    // Recursively expand the tree to get to the specified directory
    TreeItem[] items = tree.getItems();
    TreeItem lastItem = null;
    for (int i = path.size() - 1; i >= 0; --i) {
        final File pathElement = (File) path.elementAt(i);
        // Search for a particular File in the array of tree items
        // No guarantee that the items are sorted in any recognizable
        // fashion, so we'll
        // just sequential scan. There shouldn't be more than a few thousand
        // entries.
        TreeItem item = null;
        for (int k = 0; k < items.length; ++k) {
            item = items[k];
            if (item.isDisposed())
                continue;
            final File itemFile = (File) item.getData(TREEITEMDATA_FILE);
            if (itemFile != null && itemFile.equals(pathElement))
                break;
        }
        if (item == null)
            break;
        lastItem = item;
        if (i != 0 && !item.getExpanded()) {
            treeExpandItem(item);
            item.setExpanded(true);
        }
        items = item.getItems();
    }
    if (select)
        tree.setSelection((lastItem != null) ? new TreeItem[] { lastItem } : new TreeItem[0]);
}

From source file:hudson.model.Run.java

/**
 * Backward compatibility./*w w  w .  j  ava2 s  .c om*/
 *
 * We used to have $JENKINS_HOME/jobs/JOBNAME/lastStable and lastSuccessful symlinked to the appropriate
 * builds, but now those are done in {@link PeepholePermalink}. So here, we simply create symlinks that
 * resolves to the symlink created by {@link PeepholePermalink}.
 */
private void createSymlink(@Nonnull TaskListener listener, @Nonnull String name,
        @Nonnull PermalinkProjectAction.Permalink target) throws InterruptedException {
    File buildDir = getParent().getBuildDir();
    File rootDir = getParent().getRootDir();
    String targetDir;
    if (buildDir.equals(new File(rootDir, "builds"))) {
        targetDir = "builds" + File.separator + target.getId();
    } else {
        targetDir = buildDir + File.separator + target.getId();
    }
    Util.createSymlink(rootDir, targetDir, name, listener);
}

From source file:mondrian.gui.Workbench.java

private void saveAsMenuItemActionPerformed(ActionEvent evt) {
    JInternalFrame jf = desktopPane.getSelectedFrame();

    if (jf != null && jf.getContentPane().getComponent(0) instanceof SchemaExplorer) {
        SchemaExplorer se = (SchemaExplorer) jf.getContentPane().getComponent(0);
        java.io.File schemaFile = se.getSchemaFile();
        java.io.File oldSchemaFile = schemaFile;
        java.io.File suggSchemaFile = new File(
                schemaFile == null ? se.getSchema().name.trim() + ".xml" : schemaFile.getName());
        MondrianGuiDef.Schema schema = se.getSchema();
        JFileChooser jfc = new JFileChooser();
        MondrianProperties.instance();//from   w  w  w. java2  s  . c o  m

        jfc.setSelectedFile(suggSchemaFile);

        if (!isSchemaValid(schema)) {
            // the schema would not be re-loadable.  Abort save.
            return;
        }

        if (jfc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) {
            try {
                schemaFile = jfc.getSelectedFile();
                if (!oldSchemaFile.equals(schemaFile) && schemaFile.exists()) { // new file already exists, check for overwrite
                    int answer = JOptionPane.showConfirmDialog(null,
                            getResourceConverter().getFormattedString("workbench.saveAs.schema.confirm",
                                    "{0} schema file already exists. Do you want to replace it?",
                                    schemaFile.getAbsolutePath()),
                            getResourceConverter().getString("workbench.saveAs.schema.confirm.title",
                                    "Save As"),
                            JOptionPane.YES_NO_OPTION);
                    if (answer == 1) { //  no=1 ; yes=0
                        return;
                    }
                }

                if (se.isNewFile() && !oldSchemaFile.equals(schemaFile)) {
                    oldSchemaFile.delete();
                }

                if (se.isNewFile()) {
                    se.setNewFile(false);
                }
                se.setDirty(false);
                se.setDirtyFlag(false);

                XMLOutput out = new XMLOutput(new java.io.FileWriter(jfc.getSelectedFile()));
                out.setAlwaysQuoteCData(true);
                out.setIndentString("  ");
                schema.displayXML(out);
                se.setSchemaFile(schemaFile);
                se.setTitle(); // sets title of iframe
                setLastUsed(jfc.getSelectedFile().getName(), jfc.getSelectedFile().toURI().toURL().toString());

                // Update menu item with new file name, then update catalog
                // list for mdx queries
                JMenuItem sMenuItem = schemaWindowMap.get(jf);
                String mtexttokens[] = sMenuItem.getText().split(" ");
                sMenuItem.setText(mtexttokens[0] + " " + se.getSchemaFile().getName());
                // Schema menu item updated, now update mdx query windows
                // with updated catalog list.
                updateMDXCatalogList();
            } catch (Exception ex) {
                LOGGER.error(ex);
            }
        }
    }
}

From source file:org.eclipse.swt.examples.fileviewer.FileViewer.java

/**
 * Copies a file or entire directory structure.
 * //from  w  w w.java  2 s .  c o m
 * @param oldFile
 *            the location of the old file or directory
 * @param newFile
 *            the location of the new file or directory
 * @return true iff the operation succeeds without errors
 */
boolean copyFileStructure(File oldFile, File newFile) {
    Log.i("");
    if (oldFile == null || newFile == null)
        return false;

    // ensure that newFile is not a child of oldFile or a dupe
    File searchFile = newFile;
    do {
        if (oldFile.equals(searchFile))
            return false;
        searchFile = searchFile.getParentFile();
    } while (searchFile != null);

    if (oldFile.isDirectory()) {
        /*
         * Copy a directory
         */
        if (progressDialog != null) {
            progressDialog.setDetailFile(oldFile, ProgressDialog.COPY);
        }
        if (simulateOnly) {
            // System.out.println(getResourceString("simulate.DirectoriesCreated.text",
            // new Object[] { newFile.getPath() }));
        } else {
            if (!newFile.mkdirs())
                return false;
        }
        File[] subFiles = oldFile.listFiles();
        if (subFiles != null) {
            if (progressDialog != null) {
                progressDialog.addWorkUnits(subFiles.length);
            }
            for (int i = 0; i < subFiles.length; i++) {
                File oldSubFile = subFiles[i];
                File newSubFile = new File(newFile, oldSubFile.getName());
                if (!copyFileStructure(oldSubFile, newSubFile))
                    return false;
                if (progressDialog != null) {
                    progressDialog.addProgress(1);
                    if (progressDialog.isCancelled())
                        return false;
                }
            }
        }
    } else {
        /*
         * Copy a file
         */
        if (simulateOnly) {
            // System.out.println(getResourceString("simulate.CopyFromTo.text",
            // new Object[] { oldFile.getPath(), newFile.getPath() }));
        } else {
            InputStreamReader in = null;
            OutputStreamWriter out = null;
            try {
                in = new InputStreamReader(oldFile.getInputStream());
                out = new OutputStreamWriter(newFile.getOutputStream());

                int count;
                while ((count = in.read()) != -1)
                    out.write(count);
            } catch (FileNotFoundException e) {
                return false;
            } catch (IOException e) {
                return false;
            } finally {
                try {
                    if (in != null)
                        in.close();
                    if (out != null)
                        out.close();
                } catch (IOException e) {
                    return false;
                }
            }
        }
    }
    return true;
}

From source file:com.alibaba.citrus.maven.eclipse.base.eclipse.EclipsePlugin.java

private void extractAspectDirs(Set directories, MavenProject project, File basedir, File projectBaseDir,
        String testOutput) throws MojoExecutionException {
    Xpp3Dom configuration = getAspectjConfiguration(project);
    if (configuration != null) {
        String aspectDirectory = DEFAULT_ASPECT_DIRECTORY;
        Xpp3Dom aspectDirectoryElement = configuration.getChild(ASPECT_DIRECTORY);
        if (aspectDirectoryElement != null) {
            aspectDirectory = aspectDirectoryElement.getValue();
        }/*from w  w  w .  j  a v a 2s  .  c om*/

        File aspectDirectoryFile = new File(basedir, aspectDirectory);
        if (aspectDirectoryFile.exists() && aspectDirectoryFile.isDirectory()) {
            String sourceRoot = IdeUtils.toRelativeAndFixSeparator(projectBaseDir, aspectDirectoryFile,
                    !projectBaseDir.equals(basedir));

            directories.add(new EclipseSourceDir(sourceRoot, null, false, false, sourceIncludes, sourceExcludes,
                    false));
        }

        String testAspectDirectory = DEFAULT_TEST_ASPECT_DIRECTORY;
        Xpp3Dom testAspectDirectoryElement = configuration.getChild(TEST_ASPECT_DIRECTORY);
        if (testAspectDirectoryElement != null) {
            testAspectDirectory = testAspectDirectoryElement.getValue();
        }

        File testAspectDirectoryFile = new File(basedir, testAspectDirectory);
        if (testAspectDirectoryFile.exists() && testAspectDirectoryFile.isDirectory()) {
            String sourceRoot = IdeUtils.toRelativeAndFixSeparator(projectBaseDir, testAspectDirectoryFile,
                    !projectBaseDir.equals(basedir));

            directories.add(new EclipseSourceDir(sourceRoot, testOutput, false, true, sourceIncludes,
                    sourceExcludes, false));
        }
    }
}

From source file:com.fluidops.iwb.tools.RepositoryTool.java

/**
 * Rebuilds the repository by performing the following steps:
 * /* ww  w  .j a v a 2 s  .c o m*/
 * 1) Open the original repository from dbModelFolder
 * 2) Open a fresh target repository at dbModelFolder.tmp using nativeStoreIndices
 * 3) Copy the content from source repository to target repository (optionally applying a {@link FilterIteration})
 * 4) Move original repository to dbModelFolder.bak
 * 5) Move fresh target repository to dbModelFolder
 * 
 * In case of an error during a physical I/O operation (i.e. moving the original folder, deleting
 * the temporary repository) an IOException is thrown. The original repository remains
 * untouched, the target repository may have created files in dbModelFolder.tmp (which
 * need to be deleted manually)
 * 
 * @param dbModelFolder
 * @param targetFolder
 * @param nativeStoreIndicesSource the native store indices to be used for the source, e.g. "spoc"
 * @param nativeStoreIndicesTarget the native store indices to be used for the target, e.g. "spoc,psoc"
 * @param filterFactory the factory to create a {@link FilterIteration} (can be used to filter 
 *              statements during copying). May be <code>null</<code>
 * @throws IllegalStateException if the repository could not be repaired
 * @throws IOException
 */
private static void rebuildRepository(File dbModelFolder, File targetFolder, String nativeStoreIndicesSource,
        String nativeStoreIndicesTarget, FilterIterationFactory filterFactory) throws IOException {

    resetIndexConfiguration(dbModelFolder);
    File targetRepoTmpFolder = new File(dbModelFolder.getParentFile(), dbModelFolder.getName() + ".tmp");
    Repository sourceRepo = null;
    RepositoryConnection conn = null;

    try {

        sourceRepo = getRepository(dbModelFolder, nativeStoreIndicesSource);
        sourceRepo.initialize();
        conn = sourceRepo.getConnection();
        long sizeOld = conn.size();
        print("Original repository size: " + sizeOld);

        if (targetRepoTmpFolder.exists()) {
            throw new IOException("Temporary folder for repository from incomplete recovery exists at: "
                    + targetRepoTmpFolder.getPath() + ": Remove it manually.");
        }

        Repository targetRepo = null;
        RepositoryConnection targetConn = null;
        try {
            targetRepo = getRepository(targetRepoTmpFolder, nativeStoreIndicesTarget);
            targetRepo.initialize();
            targetConn = targetRepo.getConnection();
            print("Copying contents of repository to new store ...");
            print("(Note: Depending on the triple store size this might take several minutes)");
            copyRepositoryContent(conn, targetConn, filterFactory);
            long sizeNew = targetConn.size();
            print("New repository size: " + sizeNew);
            if (filterFactory == null && sizeOld != sizeNew)
                print("WARNING: repository size of old and new repository differ, please validate manually.");
        } finally {
            ReadWriteDataManagerImpl.closeQuietly(targetConn);
            ReadWriteDataManagerImpl.shutdownQuietly(targetRepo);
        }

    } catch (Exception e) {
        print("Error while rebuilding repository: " + e.getMessage());
        print("The original repository is still in place at " + dbModelFolder.getPath()
                + ". Temporary files need to be removed manually from " + targetRepoTmpFolder.getPath());
        throw new IllegalStateException("Error while rebuilding repository: " + e.getMessage());
    } finally {
        ReadWriteDataManagerImpl.closeQuietly(conn);
        ReadWriteDataManagerImpl.shutdownQuietly(sourceRepo);
        resetIndexConfiguration(dbModelFolder);
    }

    // Success: change the locations of the new and backup repository
    // 1) if targetFolder and dbModelFolder are the same, backup original repository to %dbModelFolder.bak%
    // 2) move new repository to %targetFolder%

    if (targetFolder.equals(dbModelFolder)) {
        File dbModelFolderBak = new File(dbModelFolder.getParentFile(), dbModelFolder.getName() + ".bak");
        FileUtils.moveDirectory(dbModelFolder, dbModelFolderBak);
        print("Note: the backup of the original repository is available at " + dbModelFolderBak.getPath());
    }
    FileUtils.moveDirectory(targetRepoTmpFolder, targetFolder);

    print("Repository successfully rebuild to " + targetFolder.getPath());

}

From source file:org.apache.maven.plugin.eclipse.EclipsePlugin.java

final void extractResourceDirs(Set directories, List resources, File basedir, File workspaceProjectBaseDir,
        boolean test, final String output) throws MojoExecutionException {
    for (Iterator it = resources.iterator(); it.hasNext();) {
        Resource resource = (Resource) it.next();

        getLog().debug("Processing resource dir: " + resource.getDirectory());

        List excludes = new ArrayList(resource.getExcludes());
        // automatically exclude java files: eclipse doesn't have the concept of resource directory so it will
        // try to compile any java file found in maven resource dirs
        excludes.add(JAVA_FILE_PATTERN);

        // TODO: figure out how to merge if the same dir is specified twice
        // with different in/exclude patterns.

        File resourceDirectory = new File( /* basedir, */resource.getDirectory());

        if (!resourceDirectory.exists() || !resourceDirectory.isDirectory()) {
            getLog().debug("Resource dir: " + resourceDirectory + " either missing or not a directory.");
            continue;
        }/*from w  ww.  j  a va2  s . c om*/

        String resourcePath = IdeUtils.toRelativeAndFixSeparator(workspaceProjectBaseDir, resourceDirectory,
                !workspaceProjectBaseDir.equals(basedir));
        String thisOutput = output;
        if (thisOutput != null) {
            // sometimes thisOutput is already an absolute path
            File outputFile = new File(thisOutput);
            if (!outputFile.isAbsolute()) {
                outputFile = new File(workspaceProjectBaseDir, thisOutput);
            }
            // create output dir if it doesn't exist
            outputFile.mkdirs();

            if (!StringUtils.isEmpty(resource.getTargetPath())) {
                outputFile = new File(outputFile, resource.getTargetPath());
                // create output dir if it doesn't exist
                outputFile.mkdirs();
            }

            getLog().debug("Making relative and fixing separator: { " + workspaceProjectBaseDir + ", "
                    + outputFile + ", false }.");
            thisOutput = IdeUtils.toRelativeAndFixSeparator(workspaceProjectBaseDir, outputFile, false);
        }

        EclipseSourceDir resourceDir = new EclipseSourceDir(resourcePath, thisOutput, true, test,
                resource.getIncludes(), excludes, resource.isFiltering());

        if (!directories.add(resourceDir)) {
            EclipseSourceDir originalDir = (EclipseSourceDir) get(directories, resourceDir);
            getLog().info(
                    "Resource directory's path matches an existing source directory. Resources will be merged with the source directory "
                            + originalDir.getPath());
            originalDir.merge(resourceDir);
        }
    }
}

From source file:org.atomserver.core.filestore.FileBasedContentStorage.java

/**
 * removes all of the files, except the file passed in
 * No more trash bin, files get deleted/*  w  w w  .jav a  2s  . c  om*/
 * NOTE: this method does not throw an Exception. Instead, it simply logs errors and moves on.
 *
 * @param thisRev    the file pointint at the current revision
 * @param descriptor the entry that relates to the content
 */
private void cleanupExcessFiles(final File thisRev, final EntryDescriptor descriptor) {

    String fullPath = FilenameUtils.getFullPath(thisRev.getAbsolutePath());
    File baseDir = new File(fullPath);
    if (log.isTraceEnabled()) {
        log.trace("%> cleaning up excess files at " + baseDir + " based on " + thisRev);
    }

    try {

        // get a file pointer at the previous revision of the file -- we DON'T want to delete it
        final File oneRevBack = findExistingEntryFile(descriptor, 1);

        // the set of directories to clean is the directories that contain (A) the previous
        // revision, which may or may not be the same as the current rev, and (B) the one two
        // revisions back, which may or may not be the same as the previous rev
        Set<File> directoriesToClean = new HashSet<File>(2);

        // if there was a previous rev
        if (oneRevBack != null) {
            // add it's dir to the ones to clean
            directoriesToClean.add(oneRevBack.getParentFile());
            // and if the revision is greater than 1
            if (descriptor.getRevision() > 1) {
                // then two revs back is a reasonable thing to ask for...
                File twoRevsBack = findExistingEntryFile(descriptor, 2);
                // and if it exists, add its parent to the ones to clean
                if (twoRevsBack != null) {
                    directoriesToClean.add(twoRevsBack.getParentFile());
                }
            }
        }

        // list out all of the files in the directory that are (a) files, and (b) not one of
        // the last two revisions
        for (File directoryToClean : directoriesToClean) {
            final File[] toDelete = directoryToClean.listFiles(new FileFilter() {
                public boolean accept(File fileToCheck) {

                    return fileToCheck != null && fileToCheck.exists() && fileToCheck.isFile()
                            && fileToCheck.canRead() && fileToCheck.canWrite() && !fileToCheck.isHidden()
                            && !thisRev.equals(fileToCheck)
                            && (oneRevBack == null || !oneRevBack.equals(fileToCheck));

                }
            });

            // if there's anything to delete...
            if (toDelete != null && toDelete.length > 0) {

                for (File file : toDelete) {

                    //delete the file
                    if (log.isTraceEnabled()) {
                        log.trace("deleting file" + file.getName());
                    }

                    FileUtils.forceDelete(file);
                }
                cleanUpToCollection(descriptor, directoryToClean);
            }
        }
    } catch (Exception e) {
        // if there was any exception in the move (including the one we might have just thrown
        // above) then we should log it
        log.error("Error when cleaning up dir [" + baseDir + "] when writing file (" + thisRev + ")", e);
    }
}