Example usage for java.io File getCanonicalFile

List of usage examples for java.io File getCanonicalFile

Introduction

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

Prototype

public File getCanonicalFile() throws IOException 

Source Link

Document

Returns the canonical form of this abstract pathname.

Usage

From source file:org.apache.openejb.config.DeploymentLoader.java

protected AppModule createAppModule(final File jarFile, final String jarPath) throws OpenEJBException {
    File appDir = unpack(jarFile);
    try {//from  w ww . j  a  v  a2 s .  c  o m
        appDir = appDir.getCanonicalFile();
    } catch (final IOException e) {
        throw new OpenEJBException("Invalid application directory " + appDir.getAbsolutePath());
    }

    final URL appUrl = getFileUrl(appDir);

    final String appId = appDir.getAbsolutePath();
    final ClassLoader tmpClassLoader = ClassLoaderUtil.createTempClassLoader(appId, new URL[] { appUrl },
            getOpenEJBClassLoader());

    final ResourceFinder finder = new ResourceFinder("", tmpClassLoader, appUrl);
    final Map<String, URL> appDescriptors = getDescriptors(finder);

    try {

        //
        // Find all the modules using either the application xml or by searching for all .jar, .war and .rar files.
        //

        final Map<String, URL> ejbModules = new LinkedHashMap<String, URL>();
        final Map<String, URL> clientModules = new LinkedHashMap<String, URL>();
        final Map<String, URL> resouceModules = new LinkedHashMap<String, URL>();
        final Map<String, URL> webModules = new LinkedHashMap<String, URL>();
        final Map<String, String> webContextRoots = new LinkedHashMap<String, String>();

        final URL applicationXmlUrl = appDescriptors.get("application.xml");
        final List<URL> extraLibs = new ArrayList<URL>();

        final Application application;
        if (applicationXmlUrl != null) {

            application = unmarshal(applicationXmlUrl);
            for (final Module module : application.getModule()) {
                try {
                    if (module.getEjb() != null) {
                        final URL url = finder.find(module.getEjb().trim());
                        ejbModules.put(module.getEjb(), url);
                    } else if (module.getJava() != null) {
                        final URL url = finder.find(module.getJava().trim());
                        clientModules.put(module.getJava(), url);
                        extraLibs.add(url);
                    } else if (module.getConnector() != null) {
                        final URL url = finder.find(module.getConnector().trim());
                        resouceModules.put(module.getConnector(), url);
                    } else if (module.getWeb() != null) {
                        final URL url = finder.find(module.getWeb().getWebUri().trim());
                        webModules.put(module.getWeb().getWebUri(), url);
                        webContextRoots.put(module.getWeb().getWebUri(), module.getWeb().getContextRoot());
                    }
                } catch (final IOException e) {
                    throw new OpenEJBException("Invalid path to module " + e.getMessage(), e);
                }
            }
        } else {
            application = new Application();
            final HashMap<String, URL> files = new HashMap<String, URL>();
            scanDir(appDir, files, "", false);
            files.remove("META-INF/MANIFEST.MF");

            // todo we should also filter URLs here using DeploymentsResolver.loadFromClasspath

            createApplicationFromFiles(appId, tmpClassLoader, ejbModules, clientModules, resouceModules,
                    webModules, files);
        }

        final ClassLoaderConfigurer configurer = QuickJarsTxtParser
                .parse(new File(appDir, "META-INF/" + QuickJarsTxtParser.FILE_NAME));
        final Collection<URL> jarsXmlLib = new ArrayList<>();
        if (configurer != null) {
            for (final URL url : configurer.additionalURLs()) {
                try {
                    detectAndAddModuleToApplication(appId, tmpClassLoader, ejbModules, clientModules,
                            resouceModules, webModules,
                            new ImmutablePair<>(URLs.toFile(url).getAbsolutePath(), url));
                } catch (final Exception e) {
                    jarsXmlLib.add(url);
                }
            }
        }

        //
        // Create a class loader for the application
        //

        // lib/*
        if (application.getLibraryDirectory() == null) {
            application.setLibraryDirectory("lib/");
        } else {
            final String dir = application.getLibraryDirectory();
            if (!dir.endsWith("/")) {
                application.setLibraryDirectory(dir + "/");
            }
        }

        try {
            final Map<String, URL> libs = finder.getResourcesMap(application.getLibraryDirectory());
            extraLibs.addAll(libs.values());
        } catch (final IOException e) {
            logger.warning(
                    "Cannot load libs from '" + application.getLibraryDirectory() + "' : " + e.getMessage(), e);
        }

        // APP-INF/lib/*
        try {
            final Map<String, URL> libs = finder.getResourcesMap("APP-INF/lib/");
            extraLibs.addAll(libs.values());
        } catch (final IOException e) {
            logger.warning("Cannot load libs from 'APP-INF/lib/' : " + e.getMessage(), e);
        }

        // META-INF/lib/*
        try {
            final Map<String, URL> libs = finder.getResourcesMap("META-INF/lib/");
            extraLibs.addAll(libs.values());
        } catch (final IOException e) {
            logger.warning("Cannot load libs from 'META-INF/lib/' : " + e.getMessage(), e);
        }

        // All jars nested in the Resource Adapter
        final HashMap<String, URL> rarLibs = new HashMap<String, URL>();
        for (final Map.Entry<String, URL> entry : resouceModules.entrySet()) {
            try {
                // unpack the resource adapter archive
                File rarFile = URLs.toFile(entry.getValue());
                rarFile = unpack(rarFile);
                entry.setValue(rarFile.toURI().toURL());

                scanDir(appDir, rarLibs, "");
            } catch (final MalformedURLException e) {
                throw new OpenEJBException("Malformed URL to app. " + e.getMessage(), e);
            }
        }
        for (final Iterator<Map.Entry<String, URL>> iterator = rarLibs.entrySet().iterator(); iterator
                .hasNext();) {
            // remove all non jars from the rarLibs
            final Map.Entry<String, URL> fileEntry = iterator.next();
            if (!fileEntry.getKey().endsWith(".jar")) {
                continue;
            }
            iterator.remove();
        }

        final List<URL> classPath = new ArrayList<>();
        classPath.addAll(ejbModules.values());
        classPath.addAll(clientModules.values());
        classPath.addAll(rarLibs.values());
        classPath.addAll(extraLibs);
        classPath.addAll(jarsXmlLib);
        final URL[] urls = classPath.toArray(new URL[classPath.size()]);

        SystemInstance.get().fireEvent(new BeforeDeploymentEvent(urls));

        final ClassLoader appClassLoader = ClassLoaderUtil.createTempClassLoader(appId, urls,
                getOpenEJBClassLoader());

        //
        // Create the AppModule and all nested module objects
        //

        final AppModule appModule = new AppModule(appClassLoader, appId, application, false);
        appModule.getAdditionalLibraries().addAll(extraLibs);
        appModule.getAltDDs().putAll(appDescriptors);
        appModule.getWatchedResources().add(appId);
        if (applicationXmlUrl != null) {
            appModule.getWatchedResources().add(URLs.toFilePath(applicationXmlUrl));
        }

        // EJB modules
        for (final String moduleName : ejbModules.keySet()) {
            try {
                URL ejbUrl = ejbModules.get(moduleName);
                // we should try to use a reference to the temp classloader
                if (ClassLoaderUtil.isUrlCached(appModule.getJarLocation(), ejbUrl)) {
                    try {
                        ejbUrl = ClassLoaderUtil.getUrlCachedName(appModule.getJarLocation(), ejbUrl).toURI()
                                .toURL();

                    } catch (final MalformedURLException ignore) {
                        // no-op
                    }
                }
                final File ejbFile = URLs.toFile(ejbUrl);
                final String absolutePath = ejbFile.getAbsolutePath();

                final EjbModule ejbModule = createEjbModule(ejbUrl, absolutePath, appClassLoader);
                appModule.getEjbModules().add(ejbModule);
            } catch (final OpenEJBException e) {
                logger.error("Unable to load EJBs from EAR: " + appId + ", module: " + moduleName
                        + ". Exception: " + e.getMessage(), e);
            }
        }

        // Application Client Modules
        for (final String moduleName : clientModules.keySet()) {
            try {
                URL clientUrl = clientModules.get(moduleName);
                // we should try to use a reference to the temp classloader
                if (ClassLoaderUtil.isUrlCached(appModule.getJarLocation(), clientUrl)) {
                    try {
                        clientUrl = ClassLoaderUtil.getUrlCachedName(appModule.getJarLocation(), clientUrl)
                                .toURI().toURL();

                    } catch (final MalformedURLException ignore) {
                        // no-op
                    }
                }
                final File clientFile = URLs.toFile(clientUrl);
                final String absolutePath = clientFile.getAbsolutePath();

                final ClientModule clientModule = createClientModule(clientUrl, absolutePath, appClassLoader,
                        null);

                appModule.getClientModules().add(clientModule);
            } catch (final Exception e) {
                logger.error("Unable to load App Client from EAR: " + appId + ", module: " + moduleName
                        + ". Exception: " + e.getMessage(), e);
            }
        }

        // Resource modules
        for (final String moduleName : resouceModules.keySet()) {
            try {
                URL rarUrl = resouceModules.get(moduleName);
                // we should try to use a reference to the temp classloader
                if (ClassLoaderUtil.isUrlCached(appModule.getJarLocation(), rarUrl)) {
                    try {
                        rarUrl = ClassLoaderUtil.getUrlCachedName(appModule.getJarLocation(), rarUrl).toURI()
                                .toURL();

                    } catch (final MalformedURLException ignore) {
                        // no-op
                    }
                }
                final ConnectorModule connectorModule = createConnectorModule(appId, URLs.toFilePath(rarUrl),
                        appClassLoader, moduleName);

                appModule.getConnectorModules().add(connectorModule);
            } catch (final OpenEJBException e) {
                logger.error("Unable to load RAR: " + appId + ", module: " + moduleName + ". Exception: "
                        + e.getMessage(), e);
            }
        }

        // Web modules
        for (final String moduleName : webModules.keySet()) {
            try {
                final URL warUrl = webModules.get(moduleName);
                addWebModule(appModule, warUrl, appClassLoader, webContextRoots.get(moduleName), null);
            } catch (final OpenEJBException e) {
                logger.error("Unable to load WAR: " + appId + ", module: " + moduleName + ". Exception: "
                        + e.getMessage(), e);
            }
        }

        addBeansXmls(appModule);

        // Persistence Units
        final Properties p = new Properties();
        p.put(appModule.getModuleId(), appModule.getJarLocation());
        final FileUtils base = new FileUtils(appModule.getModuleId(), appModule.getModuleId(), p);
        final List<URL> filteredUrls = new ArrayList<>();
        DeploymentsResolver.loadFromClasspath(base, filteredUrls, appModule.getClassLoader());
        addPersistenceUnits(appModule, filteredUrls.toArray(new URL[filteredUrls.size()]));

        final Object pXmls = appModule.getAltDDs().get("persistence.xml");

        for (final WebModule webModule : appModule.getWebModules()) {
            final List<URL> foundRootUrls = new ArrayList<>();
            final List<URL> scannableUrls = webModule.getScannableUrls();
            for (final URL url : scannableUrls) {
                if (!addPersistenceUnits(appModule, url).isEmpty()) {
                    foundRootUrls.add(url);
                }
            }

            if (pXmls != null && Collection.class.isInstance(pXmls)) {
                final File webapp = webModule.getFile();
                if (webapp == null) {
                    continue;
                }
                final String webappAbsolutePath = webapp.getAbsolutePath();

                final Collection<URL> list = Collection.class.cast(pXmls);
                for (final URL url : list) {
                    try {
                        final File file = URLs.toFile(url);
                        if (file.getAbsolutePath().startsWith(webappAbsolutePath)) {
                            foundRootUrls.add(url);
                        }
                    } catch (final IllegalArgumentException iae) {
                        // no-op
                    }
                }
            }

            webModule.getAltDDs().put(EAR_WEBAPP_PERSISTENCE_XML_JARS, foundRootUrls);
        }

        for (final DeploymentModule module : appModule.getDeploymentModule()) {
            module.setStandaloneModule(false);
        }

        return appModule;

    } catch (final OpenEJBException e) {
        logger.error("Unable to load EAR: " + jarPath, e);
        throw e;
    }
}

From source file:org.alfresco.repo.search.impl.lucene.index.IndexInfo.java

/**
 * Get the IndexInfo object based in the given directory. There is only one object per directory per JVM.
 * //from  w  ww.j  a  va2  s  .  c o  m
 * @param file File
 * @param config LuceneConfig
 * @return IndexInfo
 * @throws IndexerException
 */
public static synchronized IndexInfo getIndexInfo(File file, LuceneConfig config) throws IndexerException {
    File canonicalFile;
    try {
        canonicalFile = file.getCanonicalFile();
        IndexInfo indexInfo = indexInfos.get(canonicalFile);
        if (indexInfo == null) {
            indexInfo = new IndexInfo(canonicalFile, config);
            indexInfos.put(canonicalFile, indexInfo);
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Made " + indexInfo + " for " + file.getAbsolutePath());
            }
        }

        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Got " + indexInfo + " for " + file.getAbsolutePath());
        }
        return indexInfo;
    } catch (IOException e) {
        throw new IndexerException("Failed to transform a file into is canonical form", e);
    }

}

From source file:org.gss_project.gss.server.rest.FilesHandler.java

/**
 * @param req//w  ww  .  j  av  a 2  s.  c  o  m
 * @param resp
 * @throws IOException
 * @throws FileNotFoundException
 */
void putResource(HttpServletRequest req, HttpServletResponse resp) throws IOException, FileNotFoundException {
    String path = getInnerPath(req, PATH_FILES);
    try {
        path = URLDecoder.decode(path, "UTF-8");
    } catch (IllegalArgumentException e) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        return;
    }
    if (logger.isDebugEnabled())
        logger.debug("Updating resource: " + path);

    final User user = getUser(req);
    User owner = getOwner(req);
    boolean exists = true;
    Object resource = null;
    FileHeader fileLocal = null;
    try {
        resource = getService().getResourceAtPath(owner.getId(), path, false);
    } catch (ObjectNotFoundException e) {
        exists = false;
    } catch (RpcException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    }

    if (exists)
        if (resource instanceof FileHeader)
            fileLocal = (FileHeader) resource;
        else {
            resp.sendError(HttpServletResponse.SC_CONFLICT, path + " is a folder");
            return;
        }
    boolean result = true;

    // Temporary content file used to support partial PUT.
    File contentFile = null;

    Range range = parseContentRange(req, resp);

    InputStream resourceInputStream = null;

    // Append data specified in ranges to existing content for this
    // resource - create a temporary file on the local filesystem to
    // perform this operation.
    // Assume just one range is specified for now
    if (range != null) {
        try {
            contentFile = executePartialPut(req, range, path);
        } catch (RpcException e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
            return;
        } catch (ObjectNotFoundException e) {
            resp.sendError(HttpServletResponse.SC_CONFLICT);
            return;
        } catch (InsufficientPermissionsException e) {
            resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            return;
        }
        resourceInputStream = new FileInputStream(contentFile);
    } else
        resourceInputStream = req.getInputStream();

    try {
        Folder folderLocal = null;
        Object parent = getService().getResourceAtPath(owner.getId(), getParentPath(path), true);
        if (!(parent instanceof Folder)) {
            resp.sendError(HttpServletResponse.SC_CONFLICT);
            return;
        }
        folderLocal = (Folder) parent;
        final String name = getLastElement(path);
        final String mimeType = context.getMimeType(name);
        File uploadedFile = null;
        try {
            uploadedFile = getService().uploadFile(resourceInputStream, user.getId());
        } catch (IOException ex) {
            throw new GSSIOException(ex, false);
        }
        FileHeader fileTemp = null;
        final File uploadedf = uploadedFile;
        final Folder parentf = folderLocal;
        final FileHeader f = fileLocal;
        if (exists)
            fileTemp = new TransactionHelper<FileHeader>().tryExecute(new Callable<FileHeader>() {
                @Override
                public FileHeader call() throws Exception {
                    return getService().updateFileContents(user.getId(), f.getId(), mimeType,
                            uploadedf.getCanonicalFile().length(), uploadedf.getAbsolutePath());
                }
            });
        else
            fileTemp = new TransactionHelper<FileHeader>().tryExecute(new Callable<FileHeader>() {
                @Override
                public FileHeader call() throws Exception {
                    return getService().createFile(user.getId(), parentf.getId(), name, mimeType,
                            uploadedf.getCanonicalFile().length(), uploadedf.getAbsolutePath());
                }

            });
        updateAccounting(owner, new Date(), fileTemp.getCurrentBody().getFileSize());
        getService().removeFileUploadProgress(user.getId(), fileTemp.getName());
    } catch (ObjectNotFoundException e) {
        result = false;
    } catch (RpcException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    } catch (IOException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    } catch (GSSIOException e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    } catch (DuplicateNameException e) {
        resp.sendError(HttpServletResponse.SC_CONFLICT);
        return;
    } catch (InsufficientPermissionsException e) {
        resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;
    } catch (QuotaExceededException e) {
        resp.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, e.getMessage());
        return;
    } catch (Exception e) {
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    }

    if (result) {
        if (exists)
            resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
        else
            resp.setStatus(HttpServletResponse.SC_CREATED);
    } else
        resp.sendError(HttpServletResponse.SC_CONFLICT);
}

From source file:org.apache.tools.ant.taskdefs.optional.net.FTPTaskMirrorImpl.java

/**
 * auto find the time difference between local and remote
 * @param ftp handle to ftp client//from   w w  w  .j  a  v a 2s.c  om
 * @return number of millis to add to remote time to make it comparable to local time
 * @since ant 1.6
 */
private long getTimeDiff(FTPClient ftp) {
    long returnValue = 0;
    File tempFile = findFileName(ftp);
    try {
        // create a local temporary file
        FILE_UTILS.createNewFile(tempFile);
        long localTimeStamp = tempFile.lastModified();
        BufferedInputStream instream = new BufferedInputStream(new FileInputStream(tempFile));
        ftp.storeFile(tempFile.getName(), instream);
        instream.close();
        boolean success = FTPReply.isPositiveCompletion(ftp.getReplyCode());
        if (success) {
            FTPFile[] ftpFiles = ftp.listFiles(tempFile.getName());
            if (ftpFiles.length == 1) {
                long remoteTimeStamp = ftpFiles[0].getTimestamp().getTime().getTime();
                returnValue = localTimeStamp - remoteTimeStamp;
            }
            ftp.deleteFile(ftpFiles[0].getName());
        }
        // delegate the deletion of the local temp file to the delete task
        // because of race conditions occurring on Windows
        Delete mydelete = new Delete();
        mydelete.bindToOwner(task);
        mydelete.setFile(tempFile.getCanonicalFile());
        mydelete.execute();
    } catch (Exception e) {
        throw new BuildException(e, task.getLocation());
    }
    return returnValue;
}

From source file:org.moxie.ftp.FTPTaskMirrorImpl.java

/**
 * auto find the time difference between local and remote
 * @param ftp handle to ftp client/*from ww  w.j  a  v a  2s. c  o m*/
 * @return number of millis to add to remote time to make it comparable to local time
 * @since ant 1.6
 */
private long getTimeDiff(FTPClient ftp) {
    long returnValue = 0;
    File tempFile = findFileName(ftp);
    try {
        // create a local temporary file
        FILE_UTILS.createNewFile(tempFile);
        long localTimeStamp = tempFile.lastModified();
        BufferedInputStream instream = new BufferedInputStream(new FileInputStream(tempFile));
        ftp.storeFile(tempFile.getName(), instream);
        instream.close();
        boolean success = FTPReply.isPositiveCompletion(ftp.getReplyCode());
        if (success) {
            FTPFile[] ftpFiles = ftp.listFiles(tempFile.getName());
            if (ftpFiles.length == 1) {
                long remoteTimeStamp = ftpFiles[0].getTimestamp().getTime().getTime();
                returnValue = localTimeStamp - remoteTimeStamp;
            }
            ftp.deleteFile(ftpFiles[0].getName());
        }
        // delegate the deletion of the local temp file to the delete task
        // because of race conditions occuring on Windows
        Delete mydelete = new Delete();
        mydelete.bindToOwner(task);
        mydelete.setFile(tempFile.getCanonicalFile());
        mydelete.execute();
    } catch (Exception e) {
        throw new BuildException(e, task.getLocation());
    }
    return returnValue;
}

From source file:processing.app.Base.java

public Base(String[] args) throws Exception {
    Thread deleteFilesOnShutdownThread = new Thread(DeleteFilesOnShutdown.INSTANCE);
    deleteFilesOnShutdownThread.setName("DeleteFilesOnShutdown");
    Runtime.getRuntime().addShutdownHook(deleteFilesOnShutdownThread);

    BaseNoGui.initLogger();/*from  w  ww  .  j  a  v  a 2 s . co  m*/

    initLogger();

    BaseNoGui.initPlatform();

    BaseNoGui.getPlatform().init();

    BaseNoGui.initPortableFolder();

    // Look for a possible "--preferences-file" parameter and load preferences
    BaseNoGui.initParameters(args);

    CommandlineParser parser = new CommandlineParser(args);
    parser.parseArgumentsPhase1();
    commandLine = !parser.isGuiMode();

    BaseNoGui.checkInstallationFolder();

    // If no path is set, get the default sketchbook folder for this platform
    if (BaseNoGui.getSketchbookPath() == null) {
        File defaultFolder = getDefaultSketchbookFolderOrPromptForIt();
        if (BaseNoGui.getPortableFolder() != null)
            PreferencesData.set("sketchbook.path", BaseNoGui.getPortableSketchbookFolder());
        else
            PreferencesData.set("sketchbook.path", defaultFolder.getAbsolutePath());
        if (!defaultFolder.exists()) {
            defaultFolder.mkdirs();
        }
    }

    SplashScreenHelper splash;
    if (parser.isGuiMode()) {
        // Setup all notification widgets
        splash = new SplashScreenHelper(SplashScreen.getSplashScreen());
        BaseNoGui.notifier = new GUIUserNotifier(this);

        // Setup the theme coloring fun
        Theme.init();
        System.setProperty("swing.aatext", PreferencesData.get("editor.antialias", "true"));

        // Set the look and feel before opening the window
        try {
            BaseNoGui.getPlatform().setLookAndFeel();
        } catch (Exception e) {
            // ignore
        }

        // Use native popups so they don't look so crappy on osx
        JPopupMenu.setDefaultLightWeightPopupEnabled(false);
    } else {
        splash = new SplashScreenHelper(null);
    }

    splash.splashText(tr("Loading configuration..."));

    BaseNoGui.initVersion();

    // Don't put anything above this line that might make GUI,
    // because the platform has to be inited properly first.

    // Create a location for untitled sketches
    untitledFolder = FileUtils.createTempFolder("untitled" + new Random().nextInt(Integer.MAX_VALUE), ".tmp");
    DeleteFilesOnShutdown.add(untitledFolder);

    splash.splashText(tr("Initializing packages..."));
    BaseNoGui.initPackages();

    splash.splashText(tr("Preparing boards..."));

    if (!isCommandLine()) {
        rebuildBoardsMenu();
        rebuildProgrammerMenu();
    } else {
        TargetBoard lastSelectedBoard = BaseNoGui.getTargetBoard();
        if (lastSelectedBoard != null)
            BaseNoGui.selectBoard(lastSelectedBoard);
    }

    // Setup board-dependent variables.
    onBoardOrPortChange();

    pdeKeywords = new PdeKeywords();
    pdeKeywords.reload();

    contributionInstaller = new ContributionInstaller(BaseNoGui.getPlatform(),
            new GPGDetachedSignatureVerifier());
    libraryInstaller = new LibraryInstaller(BaseNoGui.getPlatform());

    parser.parseArgumentsPhase2();

    // Save the preferences. For GUI mode, this happens in the quit
    // handler, but for other modes we should also make sure to save
    // them.
    if (parser.isForceSavePrefs()) {
        PreferencesData.save();
    }

    if (parser.isInstallBoard()) {
        ContributionsIndexer indexer = new ContributionsIndexer(BaseNoGui.getSettingsFolder(),
                BaseNoGui.getHardwareFolder(), BaseNoGui.getPlatform(), new GPGDetachedSignatureVerifier());
        ProgressListener progressListener = new ConsoleProgressListener();

        List<String> downloadedPackageIndexFiles = contributionInstaller.updateIndex(progressListener);
        contributionInstaller.deleteUnknownFiles(downloadedPackageIndexFiles);
        indexer.parseIndex();
        indexer.syncWithFilesystem();

        String[] boardToInstallParts = parser.getBoardToInstall().split(":");

        ContributedPlatform selected = null;
        if (boardToInstallParts.length == 3) {
            selected = indexer.getIndex().findPlatform(boardToInstallParts[0], boardToInstallParts[1],
                    VersionHelper.valueOf(boardToInstallParts[2]).toString());
        } else if (boardToInstallParts.length == 2) {
            List<ContributedPlatform> platformsByName = indexer.getIndex().findPlatforms(boardToInstallParts[0],
                    boardToInstallParts[1]);
            Collections.sort(platformsByName, new DownloadableContributionVersionComparator());
            if (!platformsByName.isEmpty()) {
                selected = platformsByName.get(platformsByName.size() - 1);
            }
        }
        if (selected == null) {
            System.out.println(tr("Selected board is not available"));
            System.exit(1);
        }

        ContributedPlatform installed = indexer.getInstalled(boardToInstallParts[0], boardToInstallParts[1]);

        if (!selected.isBuiltIn()) {
            contributionInstaller.install(selected, progressListener);
        }

        if (installed != null && !installed.isBuiltIn()) {
            contributionInstaller.remove(installed);
        }

        System.exit(0);

    } else if (parser.isInstallLibrary()) {
        BaseNoGui.onBoardOrPortChange();

        ProgressListener progressListener = new ConsoleProgressListener();
        libraryInstaller.updateIndex(progressListener);

        LibrariesIndexer indexer = new LibrariesIndexer(BaseNoGui.getSettingsFolder());
        indexer.parseIndex();
        indexer.setLibrariesFolders(BaseNoGui.getLibrariesFolders());
        indexer.rescanLibraries();

        for (String library : parser.getLibraryToInstall().split(",")) {
            String[] libraryToInstallParts = library.split(":");

            ContributedLibrary selected = null;
            if (libraryToInstallParts.length == 2) {
                selected = indexer.getIndex().find(libraryToInstallParts[0],
                        VersionHelper.valueOf(libraryToInstallParts[1]).toString());
            } else if (libraryToInstallParts.length == 1) {
                List<ContributedLibrary> librariesByName = indexer.getIndex().find(libraryToInstallParts[0]);
                Collections.sort(librariesByName, new DownloadableContributionVersionComparator());
                if (!librariesByName.isEmpty()) {
                    selected = librariesByName.get(librariesByName.size() - 1);
                }
            }
            if (selected == null) {
                System.out.println(tr("Selected library is not available"));
                System.exit(1);
            }

            Optional<ContributedLibrary> mayInstalled = indexer.getIndex()
                    .getInstalled(libraryToInstallParts[0]);
            if (mayInstalled.isPresent() && selected.isIDEBuiltIn()) {
                System.out.println(tr(I18n.format(
                        "Library {0} is available as built-in in the IDE.\nRemoving the other version {1} installed in the sketchbook...",
                        library, mayInstalled.get().getParsedVersion())));
                libraryInstaller.remove(mayInstalled.get(), progressListener);
            } else {
                libraryInstaller.install(selected, mayInstalled, progressListener);
            }
        }

        System.exit(0);

    } else if (parser.isVerifyOrUploadMode()) {
        // Set verbosity for command line build
        PreferencesData.setBoolean("build.verbose", parser.isDoVerboseBuild());
        PreferencesData.setBoolean("upload.verbose", parser.isDoVerboseUpload());

        // Set preserve-temp flag
        PreferencesData.setBoolean("runtime.preserve.temp.files", parser.isPreserveTempFiles());

        // Make sure these verbosity preferences are only for the current session
        PreferencesData.setDoSave(false);

        Sketch sketch = null;
        String outputFile = null;

        try {
            // Build
            splash.splashText(tr("Verifying..."));

            File sketchFile = BaseNoGui.absoluteFile(parser.getFilenames().get(0));
            sketch = new Sketch(sketchFile);

            outputFile = new Compiler(sketch).build(progress -> {
            }, false);
        } catch (Exception e) {
            // Error during build
            e.printStackTrace();
            System.exit(1);
        }

        if (parser.isUploadMode()) {
            // Upload
            splash.splashText(tr("Uploading..."));

            try {
                List<String> warnings = new ArrayList<>();
                UploaderUtils uploader = new UploaderUtils();
                boolean res = uploader.upload(sketch, null, outputFile, parser.isDoUseProgrammer(),
                        parser.isNoUploadPort(), warnings);
                for (String warning : warnings) {
                    System.out.println(tr("Warning") + ": " + warning);
                }
                if (!res) {
                    throw new Exception();
                }
            } catch (Exception e) {
                // Error during upload
                System.out.flush();
                System.err.flush();
                System.err.println(tr("An error occurred while uploading the sketch"));
                System.exit(1);
            }
        }

        // No errors exit gracefully
        System.exit(0);
    } else if (parser.isGuiMode()) {
        splash.splashText(tr("Starting..."));

        for (String path : parser.getFilenames()) {
            // Correctly resolve relative paths
            File file = absoluteFile(path);

            // Fix a problem with systems that use a non-ASCII languages. Paths are
            // being passed in with 8.3 syntax, which makes the sketch loader code
            // unhappy, since the sketch folder naming doesn't match up correctly.
            // http://dev.processing.org/bugs/show_bug.cgi?id=1089
            if (OSUtils.isWindows()) {
                try {
                    file = file.getCanonicalFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (!parser.isForceSavePrefs())
                PreferencesData.setDoSave(true);
            if (handleOpen(file, retrieveSketchLocation(".default"), false) == null) {
                String mess = I18n.format(tr("Failed to open sketch: \"{0}\""), path);
                // Open failure is fatal in upload/verify mode
                if (parser.isVerifyOrUploadMode())
                    showError(null, mess, 2);
                else
                    showWarning(null, mess, null);
            }
        }

        installKeyboardInputMap();

        // Check if there were previously opened sketches to be restored
        restoreSketches();

        // Create a new empty window (will be replaced with any files to be opened)
        if (editors.isEmpty()) {
            handleNew();
        }

        new Thread(new BuiltInCoreIsNewerCheck(this)).start();

        // Check for boards which need an additional core
        new Thread(new NewBoardListener(this)).start();

        // Check for updates
        if (PreferencesData.getBoolean("update.check")) {
            new UpdateCheck(this);

            contributionsSelfCheck = new ContributionsSelfCheck(this,
                    new UpdatableBoardsLibsFakeURLsHandler(this), contributionInstaller, libraryInstaller);
            new Timer(false).schedule(contributionsSelfCheck,
                    Constants.BOARDS_LIBS_UPDATABLE_CHECK_START_PERIOD);
        }

    } else if (parser.isNoOpMode()) {
        // Do nothing (intended for only changing preferences)
        System.exit(0);
    } else if (parser.isGetPrefMode()) {
        BaseNoGui.dumpPrefs(parser);
    } else if (parser.isVersionMode()) {
        System.out.println("Arduino: " + BaseNoGui.VERSION_NAME_LONG);
        System.exit(0);
    }
}

From source file:com.twinsoft.convertigo.engine.localbuild.BuildLocally.java

private String runCommand(File launchDir, String command, List<String> parameters, boolean mergeError)
        throws Throwable {
    if (is(OS.win32)) {
        // Works for cordova and npm
        command += ".cmd";
    }//from  ww w  .  jav  a2  s.  c  o  m

    String shellFullpath = command;
    String paths = getLocalBuildAdditionalPath();
    paths = (paths.length() > 0 ? paths + File.pathSeparator : "") + System.getenv("PATH");

    String defaultPaths = null;
    if (is(OS.mac) || is(OS.linux)) {
        defaultPaths = "/usr/local/bin";
    } else if (is(OS.win32)) {
        String programFiles = System.getenv("ProgramW6432");
        if (programFiles != null && programFiles.length() > 0) {
            defaultPaths = programFiles + File.separator + "nodejs";
        }

        programFiles = System.getenv("ProgramFiles");
        if (programFiles != null && programFiles.length() > 0) {
            defaultPaths = (defaultPaths == null ? "" : defaultPaths + File.pathSeparator) + programFiles
                    + File.separator + "nodejs";
        }

        String appData = System.getenv("APPDATA");
        if (appData != null && appData.length() > 0) {
            defaultPaths = (defaultPaths == null ? "" : defaultPaths + File.pathSeparator) + appData
                    + File.separator + "npm";
        }
    }
    paths += File.pathSeparator + defaultPaths;

    // Checks if the command is already full path 
    if (!(new File(shellFullpath).exists())) {
        // Else search where the "exec" is and build the absolute path for this "exec"
        shellFullpath = getFullPath(paths, command);

        // If the "exec" is not found then it search it elsewhere
        if (shellFullpath == null) {
            shellFullpath = command;
        }
    }

    // Prepares the command
    parameters.add(0, shellFullpath);
    ProcessBuilder pb = new ProcessBuilder(parameters);
    // Set the directory from where the command will be executed
    pb.directory(launchDir.getCanonicalFile());

    Map<String, String> pbEnv = pb.environment();
    // must set "Path" for Windows 8.1 64
    pbEnv.put(pbEnv.get("PATH") == null ? "Path" : "PATH", paths);

    // Specific to npm command
    if (shellFullpath.endsWith("npm") || shellFullpath.endsWith("npm.cmd")) {

        // Set the proxy for npm
        String proxyMode = EnginePropertiesManager
                .getProperty(EnginePropertiesManager.PropertyName.PROXY_SETTINGS_MODE);
        if (proxyMode.equals(ProxyMode.manual.getValue())) {
            String proxyAuthMethod = EnginePropertiesManager
                    .getProperty(EnginePropertiesManager.PropertyName.PROXY_SETTINGS_METHOD);

            if (proxyAuthMethod.equals(ProxyMethod.anonymous.getValue())
                    || proxyAuthMethod.equals(ProxyMethod.basic.getValue())) {
                String proxyHost = EnginePropertiesManager
                        .getProperty(EnginePropertiesManager.PropertyName.PROXY_SETTINGS_HOST);
                String proxyPort = EnginePropertiesManager
                        .getProperty(EnginePropertiesManager.PropertyName.PROXY_SETTINGS_PORT);

                String npmProxy = proxyHost + ":" + proxyPort;

                if (proxyAuthMethod.equals(ProxyMethod.basic.getValue())) {
                    String proxyUser = EnginePropertiesManager
                            .getProperty(EnginePropertiesManager.PropertyName.PROXY_SETTINGS_USER);
                    String proxyPassword = EnginePropertiesManager
                            .getProperty(EnginePropertiesManager.PropertyName.PROXY_SETTINGS_PASSWORD);

                    npmProxy = proxyUser + ":" + proxyPassword + "@" + npmProxy;
                }

                pbEnv.put("http-proxy", "http://" + npmProxy);
                pbEnv.put("https-proxy", "http://" + npmProxy);
            }
        }
    }

    pb.redirectErrorStream(mergeError);

    Engine.logEngine.info("Executing command : " + parameters);

    process = pb.start();

    cmdOutput = "";
    // Logs the output
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                String line;
                processCanceled = false;

                BufferedReader bis = new BufferedReader(new InputStreamReader(process.getInputStream()));
                while ((line = bis.readLine()) != null) {
                    Engine.logEngine.info(line);
                    BuildLocally.this.cmdOutput += line;
                }
            } catch (IOException e) {
                Engine.logEngine.error("Error while executing command", e);
            }
        }
    }).start();

    if (!mergeError) {
        // Logs the error output
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String line;
                    processCanceled = false;

                    BufferedReader bis = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                    while ((line = bis.readLine()) != null) {
                        Engine.logEngine.error(line);
                        errorLines += line;
                    }
                } catch (IOException e) {
                    Engine.logEngine.error("Error while executing command", e);
                }
            }
        }).start();
    }

    int exitCode = process.waitFor();

    if (exitCode != 0 && exitCode != 127) {
        throw new Exception(
                "Exit code " + exitCode + " when running the command '" + command + "' with parameters : '"
                        + parameters + "'. The output of the command is : '" + cmdOutput + "'");
    }

    return cmdOutput;
}

From source file:org.gss_project.gss.server.rest.FilesHandler.java

/**
 * A method for handling multipart POST requests for uploading
 * files from browser-based JavaScript clients.
 *
 * @param request the HTTP request//from   w  ww. j a v a2s.co m
 * @param response the HTTP response
 * @param path the resource path
 * @throws IOException in case an error occurs writing to the
 *       response stream
 */
private void handleMultipart(HttpServletRequest request, HttpServletResponse response, String path)
        throws IOException {
    if (logger.isDebugEnabled())
        logger.debug("Multipart POST for resource: " + path);

    User owner = getOwner(request);
    boolean exists = true;
    Object resource = null;
    FileHeader file = null;
    try {
        resource = getService().getResourceAtPath(owner.getId(), path, false);
    } catch (ObjectNotFoundException e) {
        exists = false;
    } catch (RpcException e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    }

    if (exists)
        if (resource instanceof FileHeader) {
            file = (FileHeader) resource;
            if (file.isDeleted()) {
                response.sendError(HttpServletResponse.SC_CONFLICT, file.getName() + " is in the trash");
                return;
            }
        } else {
            response.sendError(HttpServletResponse.SC_CONFLICT, path + " is a folder");
            return;
        }

    Object parent;
    String parentPath = null;
    try {
        parentPath = getParentPath(path);
        parent = getService().getResourceAtPath(owner.getId(), parentPath, true);
    } catch (ObjectNotFoundException e) {
        response.sendError(HttpServletResponse.SC_NOT_FOUND, parentPath);
        return;
    } catch (RpcException e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
        return;
    }
    if (!(parent instanceof Folder)) {
        response.sendError(HttpServletResponse.SC_CONFLICT);
        return;
    }
    final Folder folderLocal = (Folder) parent;
    final String fileName = getLastElement(path);

    if (!isValidResourceName(fileName)) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    FileItemIterator iter;
    File uploadedFile = null;
    try {
        // Create a new file upload handler.
        ServletFileUpload upload = new ServletFileUpload();
        StatusProgressListener progressListener = new StatusProgressListener(getService());
        upload.setProgressListener(progressListener);
        iter = upload.getItemIterator(request);
        String dateParam = null;
        String auth = null;
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            InputStream stream = item.openStream();
            if (item.isFormField()) {
                final String value = Streams.asString(stream);
                if (name.equals(DATE_PARAMETER))
                    dateParam = value;
                else if (name.equals(AUTHORIZATION_PARAMETER))
                    auth = value;

                if (logger.isDebugEnabled())
                    logger.debug(name + ":" + value);
            } else {
                // Fetch the timestamp used to guard against replay attacks.
                if (dateParam == null) {
                    response.sendError(HttpServletResponse.SC_FORBIDDEN, "No Date parameter");
                    return;
                }

                long timestamp;
                try {
                    timestamp = DateUtil.parseDate(dateParam).getTime();
                } catch (DateParseException e) {
                    response.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
                    return;
                }

                // Fetch the Authorization parameter and find the user specified in it.
                if (auth == null) {
                    response.sendError(HttpServletResponse.SC_FORBIDDEN, "No Authorization parameter");
                    return;
                }
                String[] authParts = auth.split(" ");
                if (authParts.length != 2) {
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                }
                String username = authParts[0];
                String signature = authParts[1];
                User user = null;
                try {
                    user = getService().findUser(username);
                } catch (RpcException e) {
                    response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
                    return;
                }
                if (user == null) {
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                }
                request.setAttribute(USER_ATTRIBUTE, user);

                // Remove the servlet path from the request URI.
                String p = request.getRequestURI();
                String servletPath = request.getContextPath() + request.getServletPath();
                p = p.substring(servletPath.length());
                // Validate the signature in the Authorization parameter.
                String data = request.getMethod() + dateParam + p;
                if (!isSignatureValid(signature, user, data)) {
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                }

                progressListener.setUserId(user.getId());
                progressListener.setFilename(fileName);
                final String contentType = item.getContentType();

                try {
                    uploadedFile = getService().uploadFile(stream, user.getId());
                } catch (IOException ex) {
                    throw new GSSIOException(ex, false);
                }
                FileHeader fileLocal = null;
                final File upf = uploadedFile;
                final FileHeader f = file;
                final User u = user;
                if (file == null)
                    fileLocal = new TransactionHelper<FileHeader>().tryExecute(new Callable<FileHeader>() {
                        @Override
                        public FileHeader call() throws Exception {
                            return getService().createFile(u.getId(), folderLocal.getId(), fileName,
                                    contentType, upf.getCanonicalFile().length(), upf.getAbsolutePath());
                        }
                    });
                else
                    fileLocal = new TransactionHelper<FileHeader>().tryExecute(new Callable<FileHeader>() {
                        @Override
                        public FileHeader call() throws Exception {
                            return getService().updateFileContents(u.getId(), f.getId(), contentType,
                                    upf.getCanonicalFile().length(), upf.getAbsolutePath());
                        }
                    });
                updateAccounting(owner, new Date(), fileLocal.getCurrentBody().getFileSize());
                getService().removeFileUploadProgress(user.getId(), fileName);
            }
        }
        // We can't return 204 here since GWT's onSubmitComplete won't fire.
        response.setContentType("text/html");
        response.getWriter().print("<pre></pre>");
    } catch (FileUploadException e) {
        String error = "Error while uploading file";
        logger.error(error, e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
    } catch (GSSIOException e) {
        if (uploadedFile != null && uploadedFile.exists())
            uploadedFile.delete();
        String error = "Error while uploading file";
        if (e.logAsError())
            logger.error(error, e);
        else
            logger.debug(error, e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
    } catch (DuplicateNameException e) {
        if (uploadedFile != null && uploadedFile.exists())
            uploadedFile.delete();
        String error = "The specified file name already exists in this folder";
        logger.error(error, e);
        response.sendError(HttpServletResponse.SC_CONFLICT, error);

    } catch (InsufficientPermissionsException e) {
        if (uploadedFile != null && uploadedFile.exists())
            uploadedFile.delete();
        String error = "You don't have the necessary permissions";
        logger.error(error, e);
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, error);

    } catch (QuotaExceededException e) {
        if (uploadedFile != null && uploadedFile.exists())
            uploadedFile.delete();
        String error = "Not enough free space available";
        if (logger.isDebugEnabled())
            logger.debug(error, e);
        response.sendError(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, error);

    } catch (ObjectNotFoundException e) {
        if (uploadedFile != null && uploadedFile.exists())
            uploadedFile.delete();
        String error = "A specified object was not found";
        logger.error(error, e);
        response.sendError(HttpServletResponse.SC_NOT_FOUND, error);
    } catch (RpcException e) {
        if (uploadedFile != null && uploadedFile.exists())
            uploadedFile.delete();
        String error = "An error occurred while communicating with the service";
        logger.error(error, e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
    } catch (Exception e) {
        if (uploadedFile != null && uploadedFile.exists())
            uploadedFile.delete();
        String error = "An internal server error occurred";
        logger.error(error, e);
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, error);
    }
}

From source file:org.apache.maven.plugin.jdeps.AbstractJDepsMojo.java

private String getJDepsExecutable() throws IOException {
    Toolchain tc = getToolchain();/*from www.j a  va 2  s  .  c  o m*/

    String jdepsExecutable = null;
    if (tc != null) {
        jdepsExecutable = tc.findTool("jdeps");
    }

    String jdepsCommand = "jdeps" + (SystemUtils.IS_OS_WINDOWS ? ".exe" : "");

    File jdepsExe;

    if (StringUtils.isNotEmpty(jdepsExecutable)) {
        jdepsExe = new File(jdepsExecutable);

        if (jdepsExe.isDirectory()) {
            jdepsExe = new File(jdepsExe, jdepsCommand);
        }

        if (SystemUtils.IS_OS_WINDOWS && jdepsExe.getName().indexOf('.') < 0) {
            jdepsExe = new File(jdepsExe.getPath() + ".exe");
        }

        if (!jdepsExe.isFile()) {
            throw new IOException("The jdeps executable '" + jdepsExe + "' doesn't exist or is not a file.");
        }
        return jdepsExe.getAbsolutePath();
    }

    // ----------------------------------------------------------------------
    // Try to find jdepsExe from System.getProperty( "java.home" )
    // By default, System.getProperty( "java.home" ) = JRE_HOME and JRE_HOME
    // should be in the JDK_HOME
    // ----------------------------------------------------------------------
    // For IBM's JDK 1.2
    if (SystemUtils.IS_OS_AIX) {
        jdepsExe = new File(SystemUtils.getJavaHome() + File.separator + ".." + File.separator + "sh",
                jdepsCommand);
    }
    // For Apple's JDK 1.6.x (and older?) on Mac OSX
    // CHECKSTYLE_OFF: MagicNumber
    else if (SystemUtils.IS_OS_MAC_OSX && SystemUtils.JAVA_VERSION_FLOAT < 1.7f)
    // CHECKSTYLE_ON: MagicNumber
    {
        jdepsExe = new File(SystemUtils.getJavaHome() + File.separator + "bin", jdepsCommand);
    } else {
        jdepsExe = new File(SystemUtils.getJavaHome() + File.separator + ".." + File.separator + "bin",
                jdepsCommand);
    }

    // ----------------------------------------------------------------------
    // Try to find jdepsExe from JAVA_HOME environment variable
    // ----------------------------------------------------------------------
    if (!jdepsExe.exists() || !jdepsExe.isFile()) {
        Properties env = CommandLineUtils.getSystemEnvVars();
        String javaHome = env.getProperty("JAVA_HOME");
        if (StringUtils.isEmpty(javaHome)) {
            throw new IOException("The environment variable JAVA_HOME is not correctly set.");
        }
        if ((!new File(javaHome).getCanonicalFile().exists())
                || (new File(javaHome).getCanonicalFile().isFile())) {
            throw new IOException("The environment variable JAVA_HOME=" + javaHome
                    + " doesn't exist or is not a valid directory.");
        }

        jdepsExe = new File(javaHome + File.separator + "bin", jdepsCommand);
    }

    if (!jdepsExe.getCanonicalFile().exists() || !jdepsExe.getCanonicalFile().isFile()) {
        throw new IOException("The jdeps executable '" + jdepsExe
                + "' doesn't exist or is not a file. Verify the JAVA_HOME environment variable.");
    }

    return jdepsExe.getAbsolutePath();
}

From source file:org.rhq.core.util.updater.DeployerCanonicalPathTest.java

public void testUpdateDeployRawFileWithRelativePath() throws Exception {
    File tmpDirDest = FileUtil.createTempDirectory("DeployerCanonicalPathTest", ".dest", null);
    File tmpDirSrc = FileUtil.createTempDirectory("DeployerCanonicalPathTest", ".src", null);
    File rawFileRelativeDest = new File("dir-does-not-existA/../rawA.txt"); // relative to "tmpDirDest" that we just created above
    File rawFileRelativeDest2 = new File("dir-does-not-existA/../../rawA.txt"); // relative to "tmpDirDest" but it takes us above it
    File rawFileAbsoluteDest = new File(System.getProperty("java.io.tmpdir"),
            "dir-does-not-existB/../rawB.txt");

    try {// w  ww.j  av a  2  s .  co  m
        // put some source files in our tmpDirSrc location
        File testRawFileA = new File(tmpDirSrc, "updater-testA.txt");
        File testRawFileA2 = new File(tmpDirSrc, "updater-testA2.txt");
        File testRawFileB = new File(tmpDirSrc, "updater-testB.txt");
        FileUtil.copyFile(new File("target/test-classes/updater-testA.txt"), testRawFileA);
        FileUtil.copyFile(new File("target/test-classes/updater-testA.txt"), testRawFileA2);
        FileUtil.copyFile(new File("target/test-classes/updater-testB.txt"), testRawFileB);

        DeploymentProperties deploymentProps = new DeploymentProperties(0, "testbundle", "1.0.test", null,
                DestinationComplianceMode.full);
        HashMap<File, File> zipFiles = null;
        Map<File, File> rawFiles = new HashMap<File, File>(3);
        rawFiles.put(testRawFileA, rawFileRelativeDest);
        rawFiles.put(testRawFileA2, rawFileRelativeDest2);
        rawFiles.put(testRawFileB, rawFileAbsoluteDest);
        File destDir = tmpDirDest;
        Pattern ignoreRegex = null;
        DeploymentData dd = new DeploymentData(deploymentProps, tmpDirSrc, destDir, rawFiles, null, zipFiles,
                null, templateEngine, ignoreRegex, null);
        Deployer deployer = new Deployer(dd);
        DeployDifferences diff = new DeployDifferences();
        FileHashcodeMap map = deployer.deploy(diff);
        System.out.println("map-->\n" + map);
        System.out.println("diff->\n" + diff);
        assert map.size() == 3 : map;

        // make sure the first raw file is in the dest dir
        String f = rawFileRelativeDest.getPath();
        File destFile = new File(tmpDirDest, f).getCanonicalFile(); // notice f is assumed relative to tmpDirDest, must convert to canonical path
        assert destFile.exists() : destFile;
        FileUtil.writeFile(new ByteArrayInputStream("modifiedR".getBytes()), destFile); // change the file so we back it up during update

        // make sure the second raw file, though specified originally as a relative file, is in the external location
        f = rawFileRelativeDest2.getPath();
        destFile = new File(tmpDirDest, f).getCanonicalFile(); // must convert to canonical path
        assert destFile.exists() : destFile;
        FileUtil.writeFile(new ByteArrayInputStream("modifiedR2".getBytes()), destFile); // change the file so we back it up during update

        // make sure the third raw file is in the external location
        destFile = rawFileAbsoluteDest.getCanonicalFile(); // must convert to canonical path
        assert destFile.exists() : destFile;
        FileUtil.writeFile(new ByteArrayInputStream("modifiedA".getBytes()), destFile); // change the file so we back it up during update

        // UPDATE
        // alter the src files so we backup our changed files
        FileUtil.writeFile(new ByteArrayInputStream("src.modifiedR".getBytes()), testRawFileA);
        FileUtil.writeFile(new ByteArrayInputStream("src.modifiedR2".getBytes()), testRawFileA2);
        FileUtil.writeFile(new ByteArrayInputStream("src.modifiedA".getBytes()), testRawFileB);

        deploymentProps = new DeploymentProperties(1, "testbundle", "2.0.test", null,
                DestinationComplianceMode.full);
        dd = new DeploymentData(deploymentProps, tmpDirSrc, destDir, rawFiles, null, zipFiles, null,
                templateEngine, ignoreRegex, null);
        deployer = new Deployer(dd);
        diff = new DeployDifferences();
        map = deployer.deploy(diff);
        System.out.println("map-->\n" + map);
        System.out.println("diff->\n" + diff);

        String rawFileRelativeDestAbsolute = FileUtil
                .normalizePath(new File(tmpDirDest, rawFileRelativeDest.getPath())).getAbsolutePath();
        String rawFileRelativeDestAbsolute2 = FileUtil
                .normalizePath(new File(tmpDirDest, rawFileRelativeDest2.getPath())).getAbsolutePath();
        String rawFileAbsoluteDestAbsolute = FileUtil.normalizePath(rawFileAbsoluteDest).getAbsolutePath();

        assert new String(StreamUtil.slurp(new FileInputStream(new File(rawFileRelativeDestAbsolute))))
                .equals("src.modifiedR");
        assert new String(StreamUtil.slurp(new FileInputStream(new File(rawFileRelativeDestAbsolute2))))
                .equals("src.modifiedR2");
        assert new String(StreamUtil.slurp(new FileInputStream(new File(rawFileAbsoluteDestAbsolute))))
                .equals("src.modifiedA");

        boolean isWindows = File.separatorChar == '\\';
        final File metadir = new File(tmpDirDest, ".rhqdeployments");
        File backupRel = new File(metadir, "1/backup/rawA.txt");
        File backupRel2;
        // test the second raw file, the one that was specified originally as a relative file but took us out of the dest dir
        if (!isWindows) {
            backupRel2 = new File(metadir, "1/ext-backup/" + rawFileRelativeDestAbsolute2);
        } else {
            StringBuilder str = new StringBuilder(rawFileRelativeDestAbsolute2);
            String driveLetter = FileUtil.stripDriveLetter(str);
            if (driveLetter != null) {
                driveLetter = "_" + driveLetter + '/';
            } else {
                driveLetter = "";
            }
            backupRel2 = new File(metadir, "1/ext-backup/" + driveLetter + str.toString());
        }
        // test the third raw file, the one that was specified originally as an absolute, external file
        File backupAbs;
        if (!isWindows) {
            backupAbs = new File(metadir, "1/ext-backup/" + rawFileAbsoluteDestAbsolute);
        } else {
            StringBuilder str = new StringBuilder(rawFileAbsoluteDestAbsolute);
            String driveLetter = FileUtil.stripDriveLetter(str);
            if (driveLetter != null) {
                driveLetter = "_" + driveLetter + '/';
            } else {
                driveLetter = "";
            }
            backupAbs = new File(metadir, "1/ext-backup/" + driveLetter + str.toString());
        }

        // the backup files should exist
        assert backupRel.exists() : backupRel;
        assert backupRel2.exists() : backupRel2;
        assert backupAbs.exists() : backupAbs;

        assert map.size() == 3 : map;
        assert diff.getChangedFiles().size() == 3 : diff;
        assert diff.getChangedFiles().contains(diff.convertPath("rawA.txt")) : diff;
        assert diff.getChangedFiles().contains(diff.convertPath(rawFileRelativeDestAbsolute2)) : diff;
        assert diff.getChangedFiles().contains(diff.convertPath(rawFileAbsoluteDestAbsolute)) : diff;
        assert diff.getDeletedFiles().isEmpty() : diff;
        assert diff.getBackedUpFiles().size() == 3 : diff;
        assert diff.getBackedUpFiles().keySet().contains(diff.convertPath("rawA.txt")) : diff;
        assert diff.getBackedUpFiles().keySet().contains(diff.convertPath(rawFileRelativeDestAbsolute2)) : diff;
        assert diff.getBackedUpFiles().keySet().contains(diff.convertPath(rawFileAbsoluteDestAbsolute)) : diff;
    } finally {
        FileUtil.purge(tmpDirDest, true);
        FileUtil.purge(tmpDirSrc, true);
        rawFileAbsoluteDest.getCanonicalFile().delete();
    }
}