Example usage for java.io File pathSeparator

List of usage examples for java.io File pathSeparator

Introduction

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

Prototype

String pathSeparator

To view the source code for java.io File pathSeparator.

Click Source Link

Document

The system-dependent path-separator character, represented as a string for convenience.

Usage

From source file:org.jboss.web.tomcat.tc5.TomcatDeployer.java

protected void performDeployInternal(String hostName, WebApplication appInfo, String warUrl,
        AbstractWebContainer.WebDescriptorParser webAppParser) throws Exception {

    WebMetaData metaData = appInfo.getMetaData();
    String ctxPath = metaData.getContextRoot();
    if (ctxPath.equals("/") || ctxPath.equals("/ROOT") || ctxPath.equals("")) {
        log.debug("deploy root context=" + ctxPath);
        ctxPath = "/";
        metaData.setContextRoot(ctxPath);
    }/*from   w w  w.  j a  v a2s. co m*/

    log.info("deploy, ctxPath=" + ctxPath + ", warUrl=" + shortWarUrlFromServerHome(warUrl));

    URL url = new URL(warUrl);

    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    /* If we are using the jboss class loader we need to augment its path
    to include the WEB-INF/{lib,classes} dirs or else scoped class loading
    does not see the war level overrides. The call to setWarURL adds these
    paths to the deployment UCL.
    */
    Loader webLoader = null;
    if (config.isUseJBossWebLoader()) {
        WebCtxLoader jbossLoader = new WebCtxLoader(loader);
        jbossLoader.setWarURL(url);
        webLoader = jbossLoader;
    } else {
        String[] pkgs = config.getFilteredPackages();
        WebAppLoader jbossLoader = new WebAppLoader(loader, pkgs);
        jbossLoader.setDelegate(getJava2ClassLoadingCompliance());
        webLoader = jbossLoader;
    }

    // We need to establish the JNDI ENC prior to the start 
    // of the web container so that init on startup servlets are able 
    // to interact with their ENC. We hook into the context lifecycle 
    // events to be notified of the start of the
    // context as this occurs before the servlets are started.
    if (appInfo.getAppData() == null)
        webAppParser.parseWebAppDescriptors(loader, appInfo.getMetaData());

    appInfo.setName(url.getPath());
    appInfo.setClassLoader(loader);
    appInfo.setURL(url);

    String objectNameS = config.getCatalinaDomain() + ":j2eeType=WebModule,name=//"
            + ((hostName == null) ? "localhost" : hostName) + ctxPath + ",J2EEApplication=none,J2EEServer=none";

    ObjectName objectName = new ObjectName(objectNameS);

    if (server.isRegistered(objectName)) {
        log.debug("Already exists, destroying " + objectName);
        server.invoke(objectName, "destroy", new Object[] {}, new String[] {});
    }

    server.createMBean("org.apache.commons.modeler.BaseModelMBean", objectName,
            new Object[] { config.getContextClassName() }, new String[] { "java.lang.String" });

    // Find and set config file on the context
    // If WAR is packed, expand config file to temp folder
    String ctxConfig = null;
    try {
        ctxConfig = findConfig(url);
    } catch (IOException e) {
        log.debug("No " + CONTEXT_CONFIG_FILE + " in " + url, e);
    }

    server.setAttribute(objectName, new Attribute("docBase", url.getFile()));

    server.setAttribute(objectName, new Attribute("configFile", ctxConfig));

    server.setAttribute(objectName, new Attribute("defaultContextXml", "context.xml"));
    server.setAttribute(objectName, new Attribute("defaultWebXml", "conf/web.xml"));

    server.setAttribute(objectName, new Attribute("javaVMs", javaVMs));

    server.setAttribute(objectName, new Attribute("server", serverName));

    server.setAttribute(objectName, new Attribute("saveConfig", Boolean.FALSE));

    if (webLoader != null) {
        server.setAttribute(objectName, new Attribute("loader", webLoader));
    } else {
        server.setAttribute(objectName, new Attribute("parentClassLoader", loader));
    }

    server.setAttribute(objectName, new Attribute("delegate", new Boolean(getJava2ClassLoadingCompliance())));

    String[] jspCP = getCompileClasspath(loader);
    StringBuffer classpath = new StringBuffer();
    for (int u = 0; u < jspCP.length; u++) {
        String repository = jspCP[u];
        if (repository == null)
            continue;
        if (repository.startsWith("file://"))
            repository = repository.substring(7);
        else if (repository.startsWith("file:"))
            repository = repository.substring(5);
        else
            continue;
        if (repository == null)
            continue;
        // ok it is a file.  Make sure that is is a directory or jar file
        File fp = new File(repository);
        if (!fp.isDirectory()) {
            // if it is not a directory, try to open it as a zipfile.
            try {
                // avoid opening .xml files
                if (fp.getName().toLowerCase().endsWith(".xml"))
                    continue;

                ZipFile zip = new ZipFile(fp);
                zip.close();
            } catch (IOException e) {
                continue;
            }

        }
        if (u > 0)
            classpath.append(File.pathSeparator);
        classpath.append(repository);
    }

    server.setAttribute(objectName, new Attribute("compilerClasspath", classpath.toString()));

    // Set the session cookies flag according to metadata
    switch (metaData.getSessionCookies()) {
    case WebMetaData.SESSION_COOKIES_ENABLED:
        server.setAttribute(objectName, new Attribute("cookies", new Boolean(true)));
        log.debug("Enabling session cookies");
        break;
    case WebMetaData.SESSION_COOKIES_DISABLED:
        server.setAttribute(objectName, new Attribute("cookies", new Boolean(false)));
        log.debug("Disabling session cookies");
        break;
    default:
        log.debug("Using session cookies default setting");
    }

    // Add a valve to estalish the JACC context before authorization valves
    Certificate[] certs = null;
    CodeSource cs = new CodeSource(url, certs);
    JaccContextValve jaccValve = new JaccContextValve(metaData.getJaccContextID(), cs);
    server.invoke(objectName, "addValve", new Object[] { jaccValve },
            new String[] { "org.apache.catalina.Valve" });

    // Pass the metadata to the RunAsListener via a thread local
    RunAsListener.metaDataLocal.set(metaData);

    try {
        // Init the container; this will also start it
        server.invoke(objectName, "init", new Object[] {}, new String[] {});
    } finally {
        RunAsListener.metaDataLocal.set(null);
    }

    // make the context class loader known to the WebMetaData, ws4ee needs it
    // to instanciate service endpoint pojos that live in this webapp
    Loader ctxLoader = (Loader) server.getAttribute(objectName, "loader");
    metaData.setContextLoader(ctxLoader.getClassLoader());

    // Clustering
    if (metaData.getDistributable()) {
        // Try to initate clustering, fallback to standard if no clustering is available
        try {
            AbstractJBossManager manager = null;
            String managerClassName = config.getManagerClass();
            Class managerClass = Thread.currentThread().getContextClassLoader().loadClass(managerClassName);
            manager = (AbstractJBossManager) managerClass.newInstance();

            if (manager instanceof JBossCacheManager) {
                // TODO either deprecate snapshot mode or move its config
                // into jboss-web.xml.
                String snapshotMode = config.getSnapshotMode();
                int snapshotInterval = config.getSnapshotInterval();
                JBossCacheManager jbcm = (JBossCacheManager) manager;
                jbcm.setSnapshotMode(snapshotMode);
                jbcm.setSnapshotInterval(snapshotInterval);
            }

            String name = "//" + ((hostName == null) ? "localhost" : hostName) + ctxPath;
            manager.init(name, metaData, config.isUseJK(), config.isUseLocalCache());

            // Don't assign the manager to the context until all config
            // is done, or else the manager will be started without the config
            server.setAttribute(objectName, new Attribute("manager", manager));

            log.debug("Enabled clustering support for ctxPath=" + ctxPath);
        } catch (ClusteringNotSupportedException e) {
            // JBAS-3513 Just log a WARN, not an ERROR
            log.warn("Failed to setup clustering, clustering disabled. ClusteringNotSupportedException: "
                    + e.getMessage());
        } catch (NoClassDefFoundError ncdf) {
            // JBAS-3513 Just log a WARN, not an ERROR
            log.debug("Classes needed for clustered webapp unavailable", ncdf);
            log.warn("Failed to setup clustering, clustering disabled. NoClassDefFoundError: "
                    + ncdf.getMessage());
        } catch (Throwable t) {
            // TODO consider letting this through and fail the deployment
            log.error("Failed to setup clustering, clustering disabled. Exception: ", t);
        }
    }

    /* Add security association valve after the authorization
    valves so that the authenticated user may be associated with the
    request thread/session.
    */
    SecurityAssociationValve valve = new SecurityAssociationValve(metaData, config.getSecurityManagerService());
    valve.setSubjectAttributeName(config.getSubjectAttributeName());
    server.invoke(objectName, "addValve", new Object[] { valve }, new String[] { "org.apache.catalina.Valve" });

    // Retrieve the state, and throw an exception in case of a failure
    Integer state = (Integer) server.getAttribute(objectName, "state");
    if (state.intValue() != 1) {
        throw new DeploymentException("URL " + warUrl + " deployment failed");
    }

    appInfo.setAppData(objectName);

    // Create mbeans for the servlets
    DeploymentInfo di = webAppParser.getDeploymentInfo();
    di.deployedObject = objectName;
    ObjectName servletQuery = new ObjectName(config.getCatalinaDomain() + ":j2eeType=Servlet,WebModule="
            + objectName.getKeyProperty("name") + ",*");
    Iterator iterator = server.queryMBeans(servletQuery, null).iterator();
    while (iterator.hasNext()) {
        di.mbeans.add(((ObjectInstance) iterator.next()).getObjectName());
    }

    log.debug("Initialized: " + appInfo + " " + objectName);

}

From source file:org.apache.geode.test.dunit.standalone.ProcessManager.java

private String removeJREJars(String classpath) {
    String[] jars = classpath.split(File.pathSeparator);
    StringBuilder sb = new StringBuilder(classpath.length());
    String jreLib = File.separator + "jre" + File.separator + "lib" + File.separator;
    Boolean firstjar = true;/*ww w. j a  va2s  .com*/
    for (String jar : jars) {
        if (!jar.contains(jreLib)) {
            if (!firstjar) {
                sb.append(File.pathSeparator);
            }
            sb.append(jar);
            firstjar = false;
        }
    }
    return sb.toString();
}

From source file:br.ufpb.dicomflow.integrationAPI.tools.ReadService.java

private static void saveMessages(List<MessageIF> messages, File destDir) throws JAXBException, IOException {
    Iterator<MessageIF> it = messages.iterator();
    while (it.hasNext()) {
        MessageIF messageIF = (MessageIF) it.next();
        ServiceIF service = messageIF.getService();
        Logger.v(rb.getString("loaded-service") + service.getName() + " - " + service.getAction() + " - "
                + service.getMessageID());

        JAXBContext jaxbContext = JAXBContext.newInstance(messageIF.getService().getClass());
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        FileOutputStream fos = new FileOutputStream(destDir.getAbsolutePath() + File.pathSeparator
                + service.getName() + "_" + service.getAction() + "_" + service.getMessageID());
        jaxbMarshaller.marshal(messageIF.getService(), fos);

        if (messageIF.getAttach() != null && messageIF.getAttach().length > 0) {
            fos = new FileOutputStream(destDir.getAbsolutePath() + File.pathSeparator + service.getName() + "_"
                    + service.getAction() + "_" + service.getMessageID() + "_attach");
            fos.write(messageIF.getAttach());
            fos.close();/*from  www .j a va  2  s.com*/
        }

    }
}

From source file:org.apache.cocoon.generation.StatusGenerator.java

private void genVMStatus() throws SAXException {
    AttributesImpl atts = new AttributesImpl();
    startGroup("VM");

    // BEGIN ClassPath
    String classpath = SystemUtils.JAVA_CLASS_PATH;
    if (classpath != null) {
        List paths = new ArrayList();
        StringTokenizer tokenizer = new StringTokenizer(classpath, SystemUtils.PATH_SEPARATOR);
        while (tokenizer.hasMoreTokens()) {
            paths.add(tokenizer.nextToken());
        }/*from  w ww . j a  va2 s .c  o  m*/
        addMultilineValue("classpath", paths);
    }
    // END ClassPath

    // BEGIN CONTEXT CLASSPATH
    String contextClassPath = null;
    try {
        contextClassPath = (String) this.context.get(Constants.CONTEXT_CLASSPATH);
    } catch (ContextException e) {
        // we ignore this
    }
    if (contextClassPath != null) {
        List paths = new ArrayList();
        StringTokenizer tokenizer = new StringTokenizer(contextClassPath, File.pathSeparator);
        while (tokenizer.hasMoreTokens()) {
            paths.add(tokenizer.nextToken());
        }
        addMultilineValue("context-classpath", paths);
    }
    // END CONTEXT CLASSPATH

    // BEGIN Memory status
    startGroup("Memory");
    final long totalMemory = Runtime.getRuntime().totalMemory();
    final long freeMemory = Runtime.getRuntime().freeMemory();
    addValue("total", String.valueOf(totalMemory));
    addValue("used", String.valueOf(totalMemory - freeMemory));
    addValue("free", String.valueOf(freeMemory));
    endGroup();
    // END Memory status

    // BEGIN JRE
    startGroup("JRE");
    addValue("version", SystemUtils.JAVA_VERSION);
    atts.clear();
    // qName = prefix + ':' + localName
    atts.addAttribute(XLINK_NS, "type", XLINK_PREFIX + ":type", "CDATA", "simple");
    atts.addAttribute(XLINK_NS, "href", XLINK_PREFIX + ":href", "CDATA", SystemUtils.JAVA_VENDOR_URL);
    addValue("java-vendor", SystemUtils.JAVA_VENDOR, atts);
    endGroup();
    // END JRE

    // BEGIN Operating system
    startGroup("Operating System");
    addValue("name", SystemUtils.OS_NAME);
    addValue("architecture", SystemUtils.OS_ARCH);
    addValue("version", SystemUtils.OS_VERSION);
    endGroup();
    // END operating system

    // BEGIN Cache
    if (this.storeJanitor != null) {
        startGroup("Store Janitor");

        // For each element in StoreJanitor
        Iterator i = this.storeJanitor.iterator();
        while (i.hasNext()) {
            Store store = (Store) i.next();
            startGroup(
                    store.getClass().getName() + " (hash = 0x" + Integer.toHexString(store.hashCode()) + ")");
            int size = 0;
            int empty = 0;
            atts.clear();
            atts.addAttribute(NAMESPACE, "name", "name", "CDATA", "cached");
            super.contentHandler.startElement(NAMESPACE, "value", "value", atts);

            atts.clear();
            Enumeration e = store.keys();
            while (e.hasMoreElements()) {
                size++;
                Object key = e.nextElement();
                Object val = store.get(key);
                String line;
                if (val == null) {
                    empty++;
                } else {
                    line = key + " (class: " + val.getClass().getName() + ")";
                    super.contentHandler.startElement(NAMESPACE, "line", "line", atts);
                    super.contentHandler.characters(line.toCharArray(), 0, line.length());
                    super.contentHandler.endElement(NAMESPACE, "line", "line");
                }
            }
            if (size == 0) {
                super.contentHandler.startElement(NAMESPACE, "line", "line", atts);
                String value = "[empty]";
                super.contentHandler.characters(value.toCharArray(), 0, value.length());
                super.contentHandler.endElement(NAMESPACE, "line", "line");
            }
            super.contentHandler.endElement(NAMESPACE, "value", "value");

            addValue("size", String.valueOf(size) + " items in cache (" + empty + " are empty)");
            endGroup();
        }
        endGroup();
    }

    if (this.storePersistent != null) {
        startGroup(storePersistent.getClass().getName() + " (hash = 0x"
                + Integer.toHexString(storePersistent.hashCode()) + ")");
        int size = 0;
        int empty = 0;
        atts.clear();
        atts.addAttribute(NAMESPACE, "name", "name", "CDATA", "cached");
        super.contentHandler.startElement(NAMESPACE, "value", "value", atts);

        atts.clear();
        Enumeration e = this.storePersistent.keys();
        while (e.hasMoreElements()) {
            size++;
            Object key = e.nextElement();
            Object val = storePersistent.get(key);
            String line;
            if (val == null) {
                empty++;
            } else {
                line = key + " (class: " + val.getClass().getName() + ")";
                super.contentHandler.startElement(NAMESPACE, "line", "line", atts);
                super.contentHandler.characters(line.toCharArray(), 0, line.length());
                super.contentHandler.endElement(NAMESPACE, "line", "line");
            }
        }
        if (size == 0) {
            super.contentHandler.startElement(NAMESPACE, "line", "line", atts);
            String value = "[empty]";
            super.contentHandler.characters(value.toCharArray(), 0, value.length());
            super.contentHandler.endElement(NAMESPACE, "line", "line");
        }
        super.contentHandler.endElement(NAMESPACE, "value", "value");

        addValue("size", size + " items in cache (" + empty + " are empty)");
        endGroup();
    }
    // END Cache

    endGroup();
}

From source file:org.apache.accumulo.miniclusterImpl.MiniAccumuloClusterImpl.java

@SuppressFBWarnings(value = "COMMAND_INJECTION", justification = "mini runs in the same security context as user providing the args")
private ProcessInfo _exec(Class<?> clazz, List<String> extraJvmOpts, String... args) throws IOException {
    String javaHome = System.getProperty("java.home");
    String javaBin = javaHome + File.separator + "bin" + File.separator + "java";
    String classpath = getClasspath();

    String className = clazz.getName();

    ArrayList<String> argList = new ArrayList<>();
    argList.addAll(Arrays.asList(javaBin, "-Dproc=" + clazz.getSimpleName(), "-cp", classpath));
    argList.addAll(extraJvmOpts);//from www.  j  a  va2 s.  c  o m
    for (Entry<String, String> sysProp : config.getSystemProperties().entrySet()) {
        argList.add(String.format("-D%s=%s", sysProp.getKey(), sysProp.getValue()));
    }
    // @formatter:off
    argList.addAll(Arrays.asList("-XX:+UseConcMarkSweepGC", "-XX:CMSInitiatingOccupancyFraction=75",
            "-Dapple.awt.UIElement=true", "-Djava.net.preferIPv4Stack=true", "-XX:+PerfDisableSharedMem",
            "-XX:+AlwaysPreTouch", Main.class.getName(), className));
    // @formatter:on
    argList.addAll(Arrays.asList(args));

    ProcessBuilder builder = new ProcessBuilder(argList);

    builder.environment().put("ACCUMULO_HOME", config.getDir().getAbsolutePath());
    builder.environment().put("ACCUMULO_LOG_DIR", config.getLogDir().getAbsolutePath());
    builder.environment().put("ACCUMULO_CLIENT_CONF_PATH", config.getClientConfFile().getAbsolutePath());
    String ldLibraryPath = Joiner.on(File.pathSeparator).join(config.getNativeLibPaths());
    builder.environment().put("LD_LIBRARY_PATH", ldLibraryPath);
    builder.environment().put("DYLD_LIBRARY_PATH", ldLibraryPath);

    // if we're running under accumulo.start, we forward these env vars
    String env = System.getenv("HADOOP_HOME");
    if (env != null)
        builder.environment().put("HADOOP_HOME", env);
    env = System.getenv("ZOOKEEPER_HOME");
    if (env != null)
        builder.environment().put("ZOOKEEPER_HOME", env);
    builder.environment().put("ACCUMULO_CONF_DIR", config.getConfDir().getAbsolutePath());
    if (config.getHadoopConfDir() != null)
        builder.environment().put("HADOOP_CONF_DIR", config.getHadoopConfDir().getAbsolutePath());

    log.debug("Starting MiniAccumuloCluster process with class: " + clazz.getSimpleName() + "\n, jvmOpts: "
            + extraJvmOpts + "\n, classpath: " + classpath + "\n, args: " + argList + "\n, environment: "
            + builder.environment());

    int hashcode = builder.hashCode();

    File stdOut = new File(config.getLogDir(), clazz.getSimpleName() + "_" + hashcode + ".out");
    File stdErr = new File(config.getLogDir(), clazz.getSimpleName() + "_" + hashcode + ".err");

    Process process = builder.redirectError(stdErr).redirectOutput(stdOut).start();

    cleanup.add(process);

    return new ProcessInfo(process, stdOut);
}

From source file:org.apache.accumulo.minicluster.impl.MiniAccumuloClusterImpl.java

private String getClasspath() throws IOException {

    try {/*from   w  w w. j a v  a 2 s . co  m*/
        ArrayList<ClassLoader> classloaders = new ArrayList<ClassLoader>();

        ClassLoader cl = this.getClass().getClassLoader();

        while (cl != null) {
            classloaders.add(cl);
            cl = cl.getParent();
        }

        Collections.reverse(classloaders);

        StringBuilder classpathBuilder = new StringBuilder();
        classpathBuilder.append(config.getConfDir().getAbsolutePath());

        if (config.getHadoopConfDir() != null)
            classpathBuilder.append(File.pathSeparator).append(config.getHadoopConfDir().getAbsolutePath());

        if (config.getClasspathItems() == null) {

            // assume 0 is the system classloader and skip it
            for (int i = 1; i < classloaders.size(); i++) {
                ClassLoader classLoader = classloaders.get(i);

                if (classLoader instanceof URLClassLoader) {

                    for (URL u : ((URLClassLoader) classLoader).getURLs()) {
                        append(classpathBuilder, u);
                    }

                } else if (classLoader instanceof VFSClassLoader) {

                    VFSClassLoader vcl = (VFSClassLoader) classLoader;
                    for (FileObject f : vcl.getFileObjects()) {
                        append(classpathBuilder, f.getURL());
                    }
                } else {
                    throw new IllegalArgumentException(
                            "Unknown classloader type : " + classLoader.getClass().getName());
                }
            }
        } else {
            for (String s : config.getClasspathItems())
                classpathBuilder.append(File.pathSeparator).append(s);
        }

        return classpathBuilder.toString();

    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
}

From source file:com.chaschev.install.InstallMojo.java

private String findPath() throws MojoFailureException {
    String path = Optional.fromNullable(System.getenv("path")).or(System.getenv("PATH"));

    ArrayList<String> pathEntries = newArrayList(path == null ? new String[0] : path.split(File.pathSeparator));

    String javaHomeAbsPath = SystemUtils.getJavaHome().getParentFile().getAbsolutePath();

    String mavenHomeAbsPath = getMavenHomeByClass(DefaultMaven.class).getAbsolutePath();

    List<MatchingPath> matchingPaths = new ArrayList<MatchingPath>();

    final LinkedHashSet<File> knownBinFolders = Sets.newLinkedHashSet(
            Lists.transform(Arrays.asList("/usr/local/bin", "/usr/local/sbin"), PATH_TO_FILE));

    for (String pathEntry : pathEntries) {
        File entryFile = new File(pathEntry);
        String absPath = entryFile.getAbsolutePath();

        boolean writable = isWritable(entryFile);

        getLog().debug(//from  w  ww  .j av a2  s  .  c o  m
                "testing " + entryFile.getAbsolutePath() + ": " + (writable ? "writable" : "not writable"));

        if (absPath.startsWith(javaHomeAbsPath)) {
            addMatching(matchingPaths, absPath, writable, 1);
        } else if (absPath.startsWith(mavenHomeAbsPath)) {
            addMatching(matchingPaths, absPath, writable, 2);
        }
    }

    if (IS_OS_UNIX && matchingPaths.isEmpty()) {
        getLog().warn("didn't find maven/jdk writable roots available on path, trying common unix paths: "
                + knownBinFolders);

        final LinkedHashSet<File> pathEntriesSet = Sets
                .newLinkedHashSet(Lists.transform(pathEntries, PATH_TO_FILE));

        for (File knownBinFolder : knownBinFolders) {
            if (pathEntriesSet.contains(knownBinFolder)) {
                addMatching(matchingPaths, knownBinFolder.getAbsolutePath(), isWritable(knownBinFolder), 3);
            }
        }
    }

    Collections.sort(matchingPaths);

    if (matchingPaths.isEmpty()) {
        throw new MojoFailureException("Could not find a bin folder to write to. Tried: \n"
                + Joiner.on("\n").join(mavenHomeAbsPath, javaHomeAbsPath) + "\n"
                + (IS_OS_UNIX ? knownBinFolders + "\n" : "")
                + " but they don't appear on the path or are not writable. You may try running as administrator or specifying -DinstallTo=your-bin-dir-path parameter");
    }

    return matchingPaths.get(0).path;
}

From source file:org.apache.carbondata.spark.load.CarbonLoaderUtil.java

/**
 * This method will delete the local data load folder location after data load is complete
 *
 * @param loadModel//from w  w w.j  ava  2  s .c o m
 */
public static void deleteLocalDataLoadFolderLocation(CarbonLoadModel loadModel, boolean isCompactionFlow) {
    String databaseName = loadModel.getDatabaseName();
    String tableName = loadModel.getTableName();
    String tempLocationKey = CarbonDataProcessorUtil.getTempStoreLocationKey(databaseName, tableName,
            loadModel.getSegmentId(), loadModel.getTaskNo(), isCompactionFlow);
    // form local store location
    final String localStoreLocations = CarbonProperties.getInstance().getProperty(tempLocationKey);
    if (localStoreLocations == null) {
        throw new RuntimeException("Store location not set for the key " + tempLocationKey);
    }
    // submit local folder clean up in another thread so that main thread execution is not blocked
    ExecutorService localFolderDeletionService = Executors.newFixedThreadPool(1);
    try {
        localFolderDeletionService.submit(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                long startTime = System.currentTimeMillis();
                String[] locArray = StringUtils.split(localStoreLocations, File.pathSeparator);
                for (String loc : locArray) {
                    try {
                        CarbonUtil.deleteFoldersAndFiles(new File(loc));
                    } catch (IOException | InterruptedException e) {
                        LOGGER.error(e, "Failed to delete local data load folder location: " + loc);
                    }
                }
                LOGGER.info("Deleted the local store location: " + localStoreLocations + " : Time taken: "
                        + (System.currentTimeMillis() - startTime));
                return null;
            }
        });
    } finally {
        if (null != localFolderDeletionService) {
            localFolderDeletionService.shutdown();
        }
    }

}

From source file:org.hyperic.hq.plugin.jboss7.JBossDetectorBase.java

final String getVersion(Map<String, String> args) {
    String version = "not found";

    File jbossAsServerJar = null;
    String mp = args.get("mp");
    List<String> modulesPAths = Arrays.asList(mp.split(File.pathSeparator));
    log.debug("[getVersion] modulesPAths=" + modulesPAths);
    for (String path : modulesPAths) {
        Collection<File> files = listFileTree(new File(path));
        for (File file : files) {
            String name = file.getName();
            if (name.startsWith("jboss-as-server") && name.endsWith(".jar")) {
                jbossAsServerJar = file;
            }// www .ja  v  a2  s  .c  o m
        }
    }

    if (jbossAsServerJar != null) {
        try {
            JarFile jarFile = new JarFile(jbossAsServerJar);
            log.debug("[getVersion] jboss-as-server.jar = '" + jarFile.getName() + "'");
            Attributes attributes = jarFile.getManifest().getMainAttributes();
            jarFile.close();
            version = attributes.getValue("JBossAS-Release-Version");
        } catch (IOException e) {
            log.debug("[getVersion] Error getting JBoss version (" + e + ")", e);
        }
    } else {
        log.debug("[getVersion] 'jboss-as-server.*.jar' not found.");
    }

    return version;
}

From source file:nl.geodienstencentrum.maven.plugin.sass.AbstractSassMojo.java

/**
 * Builds the basic sass script.//  w ww.j  a va 2  s .co  m
 *
 * @param sassScript
 *            the sass script
 * @throws MojoExecutionException
 *             the mojo execution exception
 */
protected void buildBasicSassScript(final StringBuilder sassScript) throws MojoExecutionException {
    final Log log = this.getLog();

    sassScript.append("require 'rubygems'\n");
    if (this.gemPaths.length > 0) {
        sassScript.append("env = { 'GEM_PATH' => [\n");
        for (final String gemPath : this.gemPaths) {
            sassScript.append("    '").append(gemPath).append("',\n");
        }

        final String gemPath = System.getenv("GEM_PATH");
        if (gemPath != null) {
            for (final String p : gemPath.split(File.pathSeparator)) {
                sassScript.append("    '").append(p).append("',\n");
            }
        }
        /* remove trailing comma+\n */
        sassScript.setLength(sassScript.length() - 2);
        sassScript.append("\n] }\n");
        sassScript.append("Gem.paths = env\n");
    }

    for (final String gem : this.gems) {
        sassScript.append("require '").append(gem).append("'\n");
    }

    sassScript.append("require 'sass/plugin'\n");
    sassScript.append("require 'java'\n");

    if (this.useCompass) {
        log.info("Running with Compass enabled.");
        log.warn(
                "Compass support is deprecated, it will be removed in version 3.0, see https://github.com/GeoDienstenCentrum/sass-maven-plugin/issues/77");
        sassScript.append("require 'compass'\n");
        sassScript.append("require 'compass/exec'\n");
        sassScript.append("require 'compass/core'\n");
        sassScript.append("require 'compass/import-once'\n");
        if (compassConfigFile != null) {
            sassScript.append("Compass.add_project_configuration '").append(compassConfigFile.getAbsolutePath())
                    .append("'\n");
        } else {
            sassScript.append("Compass.add_project_configuration \n");
        }
        this.sassOptions.put("load_paths", "Compass.configuration.sass_load_paths");
    }

    // Get all template locations from resources and set option
    // 'template_location' and
    // 'css_location' (to override default "./public/stylesheets/sass",
    // "./public/stylesheets")
    // remaining locations are added later with 'add_template_location'
    final Iterator<Entry<String, String>> templateLocations = this.getTemplateLocations();
    if (templateLocations.hasNext()) {
        final Entry<String, String> location = templateLocations.next();
        this.sassOptions.put("template_location", "'" + location.getKey() + "'");
        this.sassOptions.put("css_location", "'" + location.getValue() + "'");
    }

    // If not explicitly set place the cache location in the target dir
    if (!this.sassOptions.containsKey("cache_location")) {
        final File sassCacheDir = new File(this.buildDirectory, "sass_cache");
        final String sassCacheDirStr = sassCacheDir.toString();
        this.sassOptions.put("cache_location", "'" + FilenameUtils.separatorsToUnix(sassCacheDirStr) + "'");
    }

    // Add the plugin configuration options
    sassScript.append("Sass::Plugin.options.merge!(\n");
    for (final Iterator<Entry<String, String>> entryItr = this.sassOptions.entrySet().iterator(); entryItr
            .hasNext();) {
        final Entry<String, String> optEntry = entryItr.next();
        final String opt = optEntry.getKey();
        final String value = optEntry.getValue();
        sassScript.append("    :").append(opt).append(" => ").append(value);
        if (entryItr.hasNext()) {
            sassScript.append(",");
        }
        sassScript.append('\n');
    }
    sassScript.append(")\n");

    // add remaining template locations with 'add_template_location' (need
    // to be done after options.merge)
    while (templateLocations.hasNext()) {
        final Entry<String, String> location = templateLocations.next();
        sassScript.append("Sass::Plugin.add_template_location('").append(location.getKey()).append("', '")
                .append(location.getValue()).append("')\n");
    }

    if (this.useBourbon) {
        log.info("Running with Bourbon enabled.");
        final String bDest = this.buildDirectory + "/bourbon";
        this.extractBourbonResources(bDest);
        // sassScript.append("require 'bourbon'\n");
        sassScript.append("Sass::Plugin.add_template_location('").append(bDest)
                .append("/app/assets/stylesheets', '").append(destination).append("')\n");
    }

    // set up sass compiler callback for reporting
    sassScript.append(
            "Sass::Plugin.on_compilation_error {|error, template, css| $compiler_callback.compilationError(error.message, template, css) }\n");
    sassScript.append(
            "Sass::Plugin.on_updated_stylesheet {|template, css| $compiler_callback.updatedStylesheeet(template, css) }\n");
    sassScript.append(
            "Sass::Plugin.on_template_modified {|template| $compiler_callback.templateModified(template) }\n");
    sassScript.append(
            "Sass::Plugin.on_template_created {|template| $compiler_callback.templateCreated(template) }\n");
    sassScript.append(
            "Sass::Plugin.on_template_deleted {|template| $compiler_callback.templateDeleted(template) }\n");

    // make ruby give use some debugging info when requested
    if (log.isDebugEnabled()) {
        sassScript.append("require 'pp'\n");
        sassScript.append("pp Sass::Plugin.options\n");
        if (this.useCompass) {
            sassScript.append("pp Compass.base_directory\n");
            sassScript.append("pp Compass::Core.base_directory\n");
            sassScript.append("pp Compass::configuration\n");
        }
    }
}