Example usage for java.io File pathSeparatorChar

List of usage examples for java.io File pathSeparatorChar

Introduction

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

Prototype

char pathSeparatorChar

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

Click Source Link

Document

The system-dependent path-separator character.

Usage

From source file:org.n52.wps.webadmin.ConfigUploadBean.java

public void compile(String fileName) {
    ClassLoader cl = this.getClass().getClassLoader();
    List<URL> classpath = new ArrayList<URL>();
    if (cl instanceof URLClassLoader) {
        URLClassLoader cl2 = (URLClassLoader) cl;
        for (URL jar : cl2.getURLs()) {
            classpath.add(jar);/*ww w  .  ja v  a  2 s .  c  o m*/
        }
    }
    String classPath = System.getProperty("java.class.path");
    for (String path : classPath.split(File.pathSeparator)) {
        try {
            classpath.add(new URL("file:" + path));
        } catch (MalformedURLException e) {
            System.err.println("Wrong url: " + e.getMessage());
            e.printStackTrace();
        }
    }

    StringBuffer sb = new StringBuffer();
    for (URL jar : classpath) {
        if (SystemUtils.IS_OS_WINDOWS == false) {
            sb.append(jar.getPath());
            sb.append(File.pathSeparatorChar);
        } else {
            sb.append(jar.getPath().substring(1));
            sb.append(File.pathSeparatorChar);
        }
    }
    String ops[] = new String[] { "-classpath", sb.toString() };

    List<String> opsIter = new ArrayList<String>();
    try {
        for (String s : ops) {
            // XXX test usage, removed use of deprecated method
            // ((ArrayList) opsIter).add(URLDecoder.decode(s));
            ((ArrayList) opsIter).add(URLDecoder.decode(s, Charset.forName("UTF-8").toString()));
        }
    } catch (UnsupportedEncodingException e) {
        LOGGER.warn(e.getMessage(), e);
    }

    File[] files1 = new File[1];
    files1[0] = new File(fileName);

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

    Iterable<? extends JavaFileObject> compilationUnits1 = fileManager
            .getJavaFileObjectsFromFiles(Arrays.asList(files1));

    compiler.getTask(null, fileManager, null, opsIter, null, compilationUnits1).call();

    try {
        fileManager.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:hudson.Launcher.java

/**
 * Returns true if this {@link Launcher} is going to launch on Unix.
 *///  w w  w .ja v  a 2 s .  co m
public boolean isUnix() {
    return File.pathSeparatorChar == ':';
}

From source file:org.apache.cocoon.servlet.CocoonServlet.java

/**
 * This builds the important ClassPath used by this Servlet.  It
 * does so in a Servlet Engine neutral way.  It uses the
 * <code>ServletContext</code>'s <code>getRealPath</code> method
 * to get the Servlet 2.2 identified classes and lib directories.
 * It iterates in alphabetical order through every file in the
 * lib directory and adds it to the classpath.
 *
 * Also, we add the files to the ClassLoader for the Cocoon system.
 * In order to protect ourselves from skitzofrantic classloaders,
 * we need to work with a known one./*from www.j  a  v a2  s . c om*/
 *
 * We need to get this to work properly when Cocoon is in a war.
 *
 * @throws ServletException
 */
protected String getClassPath() throws ServletException {
    StringBuffer buildClassPath = new StringBuffer();

    File root = null;
    if (servletContextPath != null) {
        // Old method.  There *MUST* be a better method than this...

        String classDir = this.servletContext.getRealPath("/WEB-INF/classes");
        String libDir = this.servletContext.getRealPath("/WEB-INF/lib");

        if (libDir != null) {
            root = new File(libDir);
        }

        if (classDir != null) {
            buildClassPath.append(classDir);

            addClassLoaderDirectory(classDir);
        }
    } else {
        // New(ish) method for war'd deployments
        URL classDirURL = null;
        URL libDirURL = null;

        try {
            classDirURL = this.servletContext.getResource("/WEB-INF/classes");
        } catch (MalformedURLException me) {
            if (getLogger().isWarnEnabled()) {
                this.getLogger().warn("Unable to add WEB-INF/classes to the classpath", me);
            }
        }

        try {
            libDirURL = this.servletContext.getResource("/WEB-INF/lib");
        } catch (MalformedURLException me) {
            if (getLogger().isWarnEnabled()) {
                this.getLogger().warn("Unable to add WEB-INF/lib to the classpath", me);
            }
        }

        if (libDirURL != null && libDirURL.toExternalForm().startsWith("file:")) {
            root = new File(libDirURL.toExternalForm().substring("file:".length()));
        }

        if (classDirURL != null) {
            buildClassPath.append(classDirURL.toExternalForm());

            addClassLoaderURL(classDirURL);
        }
    }

    // Unable to find lib directory. Going the hard way.
    if (root == null) {
        root = extractLibraries();
    }

    if (root != null && root.isDirectory()) {
        File[] libraries = root.listFiles();
        Arrays.sort(libraries);
        for (int i = 0; i < libraries.length; i++) {
            String fullName = IOUtils.getFullFilename(libraries[i]);
            buildClassPath.append(File.pathSeparatorChar).append(fullName);

            addClassLoaderDirectory(fullName);
        }
    }

    buildClassPath.append(File.pathSeparatorChar).append(SystemUtils.JAVA_CLASS_PATH);

    buildClassPath.append(File.pathSeparatorChar).append(getExtraClassPath());
    return buildClassPath.toString();
}

From source file:org.apache.cocoon.portlet.CocoonPortlet.java

/**
 * This builds the important ClassPath used by this Portlet.  It
 * does so in a Portlet Engine neutral way.  It uses the
 * <code>PortletContext</code>'s <code>getRealPath</code> method
 * to get the Portlet identified classes and lib directories.
 * It iterates in alphabetical order through every file in the
 * lib directory and adds it to the classpath.
 *
 * Also, we add the files to the ClassLoader for the Cocoon system.
 * In order to protect ourselves from skitzofrantic classloaders,
 * we need to work with a known one./*from   ww w  .  j a v a  2s.  c  om*/
 *
 * We need to get this to work properly when Cocoon is in a war.
 *
 * @throws PortletException
 */
protected String getClassPath() throws PortletException {
    StringBuffer buildClassPath = new StringBuffer();

    File root = null;
    if (portletContextPath != null) {
        // Old method.  There *MUST* be a better method than this...

        String classDir = this.portletContext.getRealPath("/WEB-INF/classes");
        String libDir = this.portletContext.getRealPath("/WEB-INF/lib");

        if (libDir != null) {
            root = new File(libDir);
        }

        if (classDir != null) {
            buildClassPath.append(classDir);

            addClassLoaderDirectory(classDir);
        }
    } else {
        // New(ish) method for war'd deployments
        URL classDirURL = null;
        URL libDirURL = null;

        try {
            classDirURL = this.portletContext.getResource("/WEB-INF/classes");
        } catch (MalformedURLException me) {
            if (getLogger().isWarnEnabled()) {
                this.getLogger().warn("Unable to add WEB-INF/classes to the classpath", me);
            }
        }

        try {
            libDirURL = this.portletContext.getResource("/WEB-INF/lib");
        } catch (MalformedURLException me) {
            if (getLogger().isWarnEnabled()) {
                this.getLogger().warn("Unable to add WEB-INF/lib to the classpath", me);
            }
        }

        if (libDirURL != null && libDirURL.toExternalForm().startsWith("file:")) {
            root = new File(libDirURL.toExternalForm().substring("file:".length()));
        }

        if (classDirURL != null) {
            buildClassPath.append(classDirURL.toExternalForm());

            addClassLoaderURL(classDirURL);
        }
    }

    // Unable to find lib directory. Going the hard way.
    if (root == null) {
        root = extractLibraries();
    }

    if (root != null && root.isDirectory()) {
        File[] libraries = root.listFiles();
        Arrays.sort(libraries);
        for (int i = 0; i < libraries.length; i++) {
            String fullName = IOUtils.getFullFilename(libraries[i]);
            buildClassPath.append(File.pathSeparatorChar).append(fullName);

            addClassLoaderDirectory(fullName);
        }
    }

    buildClassPath.append(File.pathSeparatorChar).append(SystemUtils.JAVA_CLASS_PATH);

    buildClassPath.append(File.pathSeparatorChar).append(getExtraClassPath());
    return buildClassPath.toString();
}

From source file:com.bigjob.Client.java

/**
 * Main run function for the client//w  ww . ja  va 2  s .  c o m
 * @return true if application completed successfully
 * @throws IOException
 * @throws YarnException
 */
public boolean run() throws IOException, YarnException {

    LOG.info("Running Client");
    yarnClient.start();

    YarnClusterMetrics clusterMetrics = yarnClient.getYarnClusterMetrics();
    LOG.info("Got Cluster metric info from ASM (RM)" + ", numNodeManagers="
            + clusterMetrics.getNumNodeManagers());

    List<NodeReport> clusterNodeReports = yarnClient.getNodeReports(NodeState.RUNNING);
    LOG.info("Got Cluster node info from ASM");
    for (NodeReport node : clusterNodeReports) {
        LOG.info("Got node report from ASM for" + ", nodeId=" + node.getNodeId() + ", nodeAddress"
                + node.getHttpAddress() + ", nodeRackName" + node.getRackName() + ", nodeNumContainers"
                + node.getNumContainers());
    }

    QueueInfo queueInfo = yarnClient.getQueueInfo(this.amQueue);
    LOG.info("Queue info" + ", queueName=" + queueInfo.getQueueName() + ", queueCurrentCapacity="
            + queueInfo.getCurrentCapacity() + ", queueMaxCapacity=" + queueInfo.getMaximumCapacity()
            + ", queueApplicationCount=" + queueInfo.getApplications().size() + ", queueChildQueueCount="
            + queueInfo.getChildQueues().size());

    List<QueueUserACLInfo> listAclInfo = yarnClient.getQueueAclsInfo();
    for (QueueUserACLInfo aclInfo : listAclInfo) {
        for (QueueACL userAcl : aclInfo.getUserAcls()) {
            LOG.info("User ACL Info for Queue" + ", queueName=" + aclInfo.getQueueName() + ", userAcl="
                    + userAcl.name());
        }
    }

    // Get a new application id
    YarnClientApplication app = yarnClient.createApplication();
    GetNewApplicationResponse appResponse = app.getNewApplicationResponse();
    // TODO get min/max resource capabilities from RM and change memory ask if needed
    // If we do not have min/max, we may not be able to correctly request 
    // the required resources from the RM for the app master
    // Memory ask has to be a multiple of min and less than max. 
    // Dump out information about cluster capability as seen by the resource manager
    int maxMem = appResponse.getMaximumResourceCapability().getMemory();
    LOG.info("Max mem capabililty of resources in this cluster " + maxMem);

    // A resource ask cannot exceed the max. 
    if (amMemory > maxMem) {
        LOG.info("AM memory specified above max threshold of cluster. Using max value." + ", specified="
                + amMemory + ", max=" + maxMem);
        amMemory = maxMem;
    }

    int maxVCores = appResponse.getMaximumResourceCapability().getVirtualCores();
    LOG.info("Max virtual cores capabililty of resources in this cluster " + maxVCores);

    if (amVCores > maxVCores) {
        LOG.info("AM virtual cores specified above max threshold of cluster. " + "Using max value."
                + ", specified=" + amVCores + ", max=" + maxVCores);
        amVCores = maxVCores;
    }

    // set the application name
    ApplicationSubmissionContext appContext = app.getApplicationSubmissionContext();
    ApplicationId appId = appContext.getApplicationId();
    appContext.setApplicationName(appName);

    // Set up the container launch context for the application master
    ContainerLaunchContext amContainer = Records.newRecord(ContainerLaunchContext.class);

    // set local resources for the application master
    // local files or archives as needed
    // In this scenario, the jar file for the application master is part of the local resources         
    Map<String, LocalResource> localResources = new HashMap<String, LocalResource>();

    LOG.info("Copy App Master jar from local filesystem and add to local environment");
    // Copy the application master jar to the filesystem 
    // Create a local resource to point to the destination jar path 
    //    if (dfsUrl!=null && dfsUrl.equals("")==false){
    //       conf.set("fs.defaultFS", dfsUrl);
    //    }
    FileSystem fs = FileSystem.get(conf);
    addToLocalResources(fs, appMasterJar, appMasterJarPath, appId.getId(), localResources, null);

    // Set the log4j properties if needed 
    if (!log4jPropFile.isEmpty()) {
        addToLocalResources(fs, log4jPropFile, log4jPath, appId.getId(), localResources, null);
    }

    // The shell script has to be made available on the final container(s)
    // where it will be executed. 
    // To do this, we need to first copy into the filesystem that is visible 
    // to the yarn framework. 
    // We do not need to set this as a local resource for the application 
    // master as the application master does not need it.       
    String hdfsShellScriptLocation = "";
    long hdfsShellScriptLen = 0;
    long hdfsShellScriptTimestamp = 0;
    if (!shellScriptPath.isEmpty()) {
        Path shellSrc = new Path(shellScriptPath);
        String shellPathSuffix = appName + "/" + appId.getId() + "/"
                + (Shell.WINDOWS ? windowBatPath : linuxShellPath);
        Path shellDst = new Path(fs.getHomeDirectory(), shellPathSuffix);
        fs.copyFromLocalFile(false, true, shellSrc, shellDst);
        hdfsShellScriptLocation = shellDst.toUri().toString();
        FileStatus shellFileStatus = fs.getFileStatus(shellDst);
        hdfsShellScriptLen = shellFileStatus.getLen();
        hdfsShellScriptTimestamp = shellFileStatus.getModificationTime();
    }

    if (!shellCommand.isEmpty()) {
        addToLocalResources(fs, null, shellCommandPath, appId.getId(), localResources, shellCommand);
    }

    if (shellArgs.length > 0) {
        addToLocalResources(fs, null, shellArgsPath, appId.getId(), localResources,
                StringUtils.join(shellArgs, " "));
    }
    // Set local resource info into app master container launch context
    amContainer.setLocalResources(localResources);

    // Set the necessary security tokens as needed
    //amContainer.setContainerTokens(containerToken);

    // Set the env variables to be setup in the env where the application master will be run
    LOG.info("Set the environment for the application master");
    Map<String, String> env = new HashMap<String, String>();

    // put location of shell script into env
    // using the env info, the application master will create the correct local resource for the 
    // eventual containers that will be launched to execute the shell scripts
    env.put(DSConstants.DISTRIBUTEDSHELLSCRIPTLOCATION, hdfsShellScriptLocation);
    env.put(DSConstants.DISTRIBUTEDSHELLSCRIPTTIMESTAMP, Long.toString(hdfsShellScriptTimestamp));
    env.put(DSConstants.DISTRIBUTEDSHELLSCRIPTLEN, Long.toString(hdfsShellScriptLen));

    // Add AppMaster.jar location to classpath       
    // At some point we should not be required to add 
    // the hadoop specific classpaths to the env. 
    // It should be provided out of the box. 
    // For now setting all required classpaths including
    // the classpath to "." for the application jar
    StringBuilder classPathEnv = new StringBuilder(Environment.CLASSPATH.$()).append(File.pathSeparatorChar)
            .append("./*");
    for (String c : conf.getStrings(YarnConfiguration.YARN_APPLICATION_CLASSPATH,
            YarnConfiguration.DEFAULT_YARN_APPLICATION_CLASSPATH)) {
        classPathEnv.append(File.pathSeparatorChar);
        classPathEnv.append(c.trim());
    }
    classPathEnv.append(File.pathSeparatorChar).append("./log4j.properties");

    // add the runtime classpath needed for tests to work
    if (conf.getBoolean(YarnConfiguration.IS_MINI_YARN_CLUSTER, false)) {
        classPathEnv.append(':');
        classPathEnv.append(System.getProperty("java.class.path"));
    }

    env.put("CLASSPATH", classPathEnv.toString());

    amContainer.setEnvironment(env);

    // Set the necessary command to execute the application master 
    Vector<CharSequence> vargs = new Vector<CharSequence>(30);

    // Set java executable command 
    LOG.info("Setting up app master command");
    vargs.add(Environment.JAVA_HOME.$() + "/bin/java");
    // Set Xmx based on am memory size
    vargs.add("-Xmx" + amMemory + "m");
    // Set class name 
    vargs.add(appMasterMainClass);
    // Set params for Application Master
    vargs.add("--container_memory " + String.valueOf(containerMemory));
    vargs.add("--container_vcores " + String.valueOf(containerVirtualCores));
    vargs.add("--num_containers " + String.valueOf(numContainers));
    vargs.add("--priority " + String.valueOf(shellCmdPriority));

    for (Map.Entry<String, String> entry : shellEnv.entrySet()) {
        vargs.add("--shell_env " + entry.getKey() + "=" + entry.getValue());
    }
    if (debugFlag) {
        vargs.add("--debug");
    }

    vargs.add("1>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/AppMaster.stdout");
    vargs.add("2>" + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/AppMaster.stderr");

    // Get final commmand
    StringBuilder command = new StringBuilder();
    for (CharSequence str : vargs) {
        command.append(str).append(" ");
    }

    LOG.info("Completed setting up app master command " + command.toString());
    List<String> commands = new ArrayList<String>();
    commands.add(command.toString());
    amContainer.setCommands(commands);

    // Set up resource type requirements
    // For now, both memory and vcores are supported, so we set memory and 
    // vcores requirements
    Resource capability = Records.newRecord(Resource.class);
    capability.setMemory(amMemory);
    capability.setVirtualCores(amVCores);
    appContext.setResource(capability);

    // Service data is a binary blob that can be passed to the application
    // Not needed in this scenario
    // amContainer.setServiceData(serviceData);

    // Setup security tokens
    if (UserGroupInformation.isSecurityEnabled()) {
        Credentials credentials = new Credentials();
        String tokenRenewer = conf.get(YarnConfiguration.RM_PRINCIPAL);
        if (tokenRenewer == null || tokenRenewer.length() == 0) {
            throw new IOException("Can't get Master Kerberos principal for the RM to use as renewer");
        }

        // For now, only getting tokens for the default file-system.
        final Token<?> tokens[] = fs.addDelegationTokens(tokenRenewer, credentials);
        if (tokens != null) {
            for (Token<?> token : tokens) {
                LOG.info("Got dt for " + fs.getUri() + "; " + token);
            }
        }
        DataOutputBuffer dob = new DataOutputBuffer();
        credentials.writeTokenStorageToStream(dob);
        ByteBuffer fsTokens = ByteBuffer.wrap(dob.getData(), 0, dob.getLength());
        amContainer.setTokens(fsTokens);
    }

    appContext.setAMContainerSpec(amContainer);

    // Set the priority for the application master
    Priority pri = Records.newRecord(Priority.class);
    // TODO - what is the range for priority? how to decide? 
    pri.setPriority(amPriority);
    appContext.setPriority(pri);

    // Set the queue to which this application is to be submitted in the RM
    appContext.setQueue(amQueue);

    // Submit the application to the applications manager
    // SubmitApplicationResponse submitResp = applicationsManager.submitApplication(appRequest);
    // Ignore the response as either a valid response object is returned on success 
    // or an exception thrown to denote some form of a failure
    LOG.info("Submitting application to ASM");

    yarnClient.submitApplication(appContext);

    // TODO
    // Try submitting the same request again
    // app submission failure?

    // Monitor the application
    //return monitorApplication(appId);
    System.out.println("ApplicationId:" + appId);
    return true;
}

From source file:org.jenkinsci.plugins.zap.ZAPDriver.java

/**
 * Return the ZAP program name with separator prefix (\zap.bat or /zap.sh) depending of the build node and the OS.
 *
 * @param build//from  ww  w  .  j  a v  a2s . com
 * @return of type String: the ZAP program name with separator prefix (\zap.bat or /zap.sh).
 * @throws IOException
 * @throws InterruptedException
 */
private String getZAPProgramNameWithSeparator(AbstractBuild<?, ?> build)
        throws IOException, InterruptedException {
    Node node = build.getBuiltOn();
    String zapProgramName = "";

    /* Append zap program following Master/Slave and Windows/Unix */
    if ("".equals(node.getNodeName())) { // Master
        if (File.pathSeparatorChar == ':')
            zapProgramName = "/" + ZAP_PROG_NAME_SH;
        else
            zapProgramName = "\\" + ZAP_PROG_NAME_BAT;
    } else if ("Unix".equals(((SlaveComputer) node.toComputer()).getOSDescription()))
        zapProgramName = "/" + ZAP_PROG_NAME_SH;
    else
        zapProgramName = "\\" + ZAP_PROG_NAME_BAT;
    return zapProgramName;
}

From source file:org.codehaus.enunciate.modules.amf.AMFDeploymentModule.java

/**
 * Invokes the flex compiler on the apps specified in the configuration file.
 */// w ww  .  j  av  a  2  s . co m
protected void doFlexCompile() throws EnunciateException, IOException {
    File swcFile = null;
    File asSources = null;
    Enunciate enunciate = getEnunciate();
    if (isSwcDownloadable() || !flexApps.isEmpty()) {
        if (this.flexHome == null) {
            throw new EnunciateException(
                    "To compile a flex app you must specify the Flex SDK home directory, either in configuration, by setting the FLEX_HOME environment variable, or setting the 'flex.home' system property.");
        }

        File flexHomeDir = new File(this.flexHome);
        if (!flexHomeDir.exists()) {
            throw new EnunciateException("Flex home not found ('" + flexHomeDir.getAbsolutePath() + "').");
        }

        File javaBinDir = new File(System.getProperty("java.home"), "bin");
        File javaExecutable = new File(javaBinDir, "java");
        if (!javaExecutable.exists()) {
            //append the "exe" for windows users.
            javaExecutable = new File(javaBinDir, "java.exe");
        }

        String javaCommand = javaExecutable.getAbsolutePath();
        if (!javaExecutable.exists()) {
            warn("No java executable found in %s.  We'll just hope the environment is set up to execute 'java'...",
                    javaBinDir.getAbsolutePath());
            javaCommand = "java";
        }

        int compileCommandIndex;
        int outputFileIndex;
        int sourcePathIndex;
        int mainMxmlPathIndex;
        List<String> commandLine = new ArrayList<String>();
        int argIndex = 0;
        commandLine.add(argIndex++, javaCommand);
        for (String jvmarg : this.compilerConfig.getJVMArgs()) {
            commandLine.add(argIndex++, jvmarg);
        }
        commandLine.add(argIndex++, "-cp");
        File flexHomeLib = new File(flexHomeDir, "lib");
        if (!flexHomeLib.exists()) {
            throw new EnunciateException("File not found: " + flexHomeLib);
        } else {
            StringBuilder builder = new StringBuilder();
            Iterator<File> flexLibIt = Arrays.asList(flexHomeLib.listFiles()).iterator();
            while (flexLibIt.hasNext()) {
                File flexJar = flexLibIt.next();
                if (flexJar.getAbsolutePath().endsWith("jar")) {
                    builder.append(flexJar.getAbsolutePath());
                    if (flexLibIt.hasNext()) {
                        builder.append(File.pathSeparatorChar);
                    }
                } else {
                    debug("File %s will not be included on the classpath because it's not a jar.", flexJar);
                }
            }
            commandLine.add(argIndex++, builder.toString());
        }

        compileCommandIndex = argIndex;
        commandLine.add(argIndex++, null);

        commandLine.add(argIndex++, "-output");
        outputFileIndex = argIndex;
        commandLine.add(argIndex++, null);

        if (compilerConfig.getFlexConfig() == null) {
            compilerConfig.setFlexConfig(new File(new File(flexHome, "frameworks"), "flex-config.xml"));
        }

        if (compilerConfig.getFlexConfig().exists()) {
            commandLine.add(argIndex++, "-load-config");
            commandLine.add(argIndex++, compilerConfig.getFlexConfig().getAbsolutePath());
        } else {
            warn("Configured flex configuration file %s doesn't exist.  Ignoring...",
                    compilerConfig.getFlexConfig());
        }

        if (compilerConfig.getContextRoot() == null) {
            if (getEnunciate().getConfig().getLabel() != null) {
                compilerConfig.setContextRoot("/" + getEnunciate().getConfig().getLabel());
            } else {
                compilerConfig.setContextRoot("/enunciate");
            }
        }

        commandLine.add(argIndex++, "-compiler.context-root");
        commandLine.add(argIndex++, compilerConfig.getContextRoot());

        if (compilerConfig.getLocale() != null) {
            commandLine.add(argIndex++, "-compiler.locale");
            commandLine.add(argIndex++, compilerConfig.getLocale());
        }

        if (compilerConfig.getLicenses().size() > 0) {
            commandLine.add(argIndex++, "-licenses.license");
            for (License license : compilerConfig.getLicenses()) {
                commandLine.add(argIndex++, license.getProduct());
                commandLine.add(argIndex++, license.getSerialNumber());
            }
        }

        if (compilerConfig.getOptimize() != null && compilerConfig.getOptimize()) {
            commandLine.add(argIndex++, "-compiler.optimize");
        }

        if (compilerConfig.getDebug() != null && compilerConfig.getDebug()) {
            commandLine.add(argIndex++, "-compiler.debug=true");
        }

        if (compilerConfig.getStrict() != null && compilerConfig.getStrict()) {
            commandLine.add(argIndex++, "-compiler.strict");
        }

        if (compilerConfig.getUseNetwork() != null && compilerConfig.getUseNetwork()) {
            commandLine.add(argIndex++, "-use-network");
        }

        if (compilerConfig.getIncremental() != null && compilerConfig.getIncremental()) {
            commandLine.add(argIndex++, "-compiler.incremental");
        }

        if (compilerConfig.getShowActionscriptWarnings() != null
                && compilerConfig.getShowActionscriptWarnings()) {
            commandLine.add(argIndex++, "-show-actionscript-warnings");
        }

        if (compilerConfig.getShowBindingWarnings() != null && compilerConfig.getShowBindingWarnings()) {
            commandLine.add(argIndex++, "-show-binding-warnings");
        }

        if (compilerConfig.getShowDeprecationWarnings() != null
                && compilerConfig.getShowDeprecationWarnings()) {
            commandLine.add(argIndex++, "-show-deprecation-warnings");
        }

        for (String arg : this.compilerConfig.getArgs()) {
            commandLine.add(argIndex++, arg);
        }

        commandLine.add(argIndex++, "-compiler.services");
        File xmlGenerateDir = getXMLGenerateDir();
        commandLine.add(argIndex++, new File(xmlGenerateDir, "merged-services-config.xml").getAbsolutePath());

        commandLine.add(argIndex, "-include-sources");
        File clientSideGenerateDir = getClientSideGenerateDir();
        commandLine.add(argIndex + 1, clientSideGenerateDir.getAbsolutePath());

        String swcName = getSwcName();

        if (swcName == null) {
            String label = "enunciate";
            if (getLabel() != null) {
                label = getLabel();
            } else if ((enunciate.getConfig() != null) && (enunciate.getConfig().getLabel() != null)) {
                label = enunciate.getConfig().getLabel();
            }

            swcName = label + "-as3-client.swc";
        }

        File swcCompileDir = getSwcCompileDir();
        swcFile = new File(swcCompileDir, swcName);
        boolean swcUpToDate = swcFile.exists() && enunciate.isUpToDate(xmlGenerateDir, swcCompileDir)
                && enunciate.isUpToDate(clientSideGenerateDir, swcCompileDir);

        if (!swcUpToDate) {
            commandLine.set(compileCommandIndex, compilerConfig.getSwcCompileCommand());
            commandLine.set(outputFileIndex, swcFile.getAbsolutePath());
            debug("Compiling %s for the client-side ActionScript classes...", swcFile.getAbsolutePath());
            if (enunciate.isDebug()) {
                StringBuilder command = new StringBuilder();
                for (String commandPiece : commandLine) {
                    command.append(' ').append(commandPiece);
                }
                debug("Executing SWC compile for client-side actionscript with the command: %s", command);
            }
            compileSwc(commandLine);
        } else {
            info("Skipping compilation of %s as everything appears up-to-date...", swcFile.getAbsolutePath());
        }

        //swc is compiled
        while (commandLine.size() > argIndex) {
            //remove the compc-specific options...
            commandLine.remove(argIndex);
        }

        if (compilerConfig.getProfile() != null && compilerConfig.getProfile()) {
            commandLine.add(argIndex++, "-compiler.profile");
        }

        if (compilerConfig.getWarnings() != null && compilerConfig.getWarnings()) {
            commandLine.add(argIndex++, "-warnings");
        }

        commandLine.add(argIndex++, "-source-path");
        commandLine.add(argIndex++, clientSideGenerateDir.getAbsolutePath());

        commandLine.add(argIndex++, "-source-path");
        sourcePathIndex = argIndex;
        commandLine.add(argIndex++, null);

        commandLine.add(argIndex++, "--");
        mainMxmlPathIndex = argIndex;
        commandLine.add(argIndex++, null);

        commandLine.set(compileCommandIndex, compilerConfig.getFlexCompileCommand());

        File outputDirectory = getSwfCompileDir();
        debug("Creating output directory: " + outputDirectory);
        outputDirectory.mkdirs();

        for (FlexApp flexApp : flexApps) {
            String mainMxmlPath = flexApp.getMainMxmlFile();
            if (mainMxmlPath == null) {
                throw new EnunciateException("A main MXML file for the flex app '" + flexApp.getName()
                        + "' must be supplied with the 'mainMxmlFile' attribute.");
            }

            File mainMxmlFile = enunciate.resolvePath(mainMxmlPath);
            if (!mainMxmlFile.exists()) {
                throw new EnunciateException(
                        "Main MXML file for the flex app '" + flexApp.getName() + "' doesn't exist.");
            }

            File swfDir = outputDirectory;
            if (flexApp.getOutputPath() != null && !"".equals(flexApp.getOutputPath())) {
                swfDir = new File(outputDirectory, flexApp.getOutputPath());
                swfDir.mkdirs();
            }
            File swfFile = new File(swfDir, flexApp.getName() + ".swf");
            File appSrcDir = enunciate.resolvePath(flexApp.getSrcDir());
            String swfFilePath = swfFile.getAbsolutePath();

            boolean swfUpToDate = swfFile.exists() && mainMxmlFile.lastModified() < swfFile.lastModified()
                    && enunciate.isUpToDate(appSrcDir, swfFile);

            if (!swfUpToDate) {
                commandLine.set(outputFileIndex, swfFilePath);
                commandLine.set(mainMxmlPathIndex, mainMxmlFile.getAbsolutePath());
                commandLine.set(sourcePathIndex, appSrcDir.getAbsolutePath());

                debug("Compiling %s ...", swfFilePath);
                if (enunciate.isDebug()) {
                    StringBuilder command = new StringBuilder();
                    for (String commandPiece : commandLine) {
                        command.append(' ').append(commandPiece);
                    }
                    debug("Executing flex compile for module %s with the command: %s", flexApp.getName(),
                            command);
                }

                ProcessBuilder processBuilder = new ProcessBuilder(
                        commandLine.toArray(new String[commandLine.size()]));
                processBuilder.directory(getSwfCompileDir());
                processBuilder.redirectErrorStream(true);
                Process process = processBuilder.start();
                BufferedReader procReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String line = procReader.readLine();
                while (line != null) {
                    info(line);
                    line = procReader.readLine();
                }
                int procCode;
                try {
                    procCode = process.waitFor();
                } catch (InterruptedException e1) {
                    throw new EnunciateException("Unexpected inturruption of the Flex compile process.");
                }

                if (procCode != 0) {
                    throw new EnunciateException("Flex compile failed for module " + flexApp.getName());
                }
            } else {
                info("Skipping compilation of %s as everything appears up-to-date...", swfFilePath);
            }
        }
    }

    if (isAsSourcesDownloadable()) {
        String label = "enunciate";
        if ((enunciate.getConfig() != null) && (enunciate.getConfig().getLabel() != null)) {
            label = enunciate.getConfig().getLabel();
        }

        asSources = new File(new File(getCompileDir(), "src"), label + "-as3-sources.zip");
        enunciate.zip(asSources, getClientSideGenerateDir());
    }

    if (swcFile != null || asSources != null) {
        List<ArtifactDependency> clientDeps = new ArrayList<ArtifactDependency>();
        BaseArtifactDependency as3Dependency = new BaseArtifactDependency();
        as3Dependency.setId("flex-sdk");
        as3Dependency.setArtifactType("zip");
        as3Dependency.setDescription("The flex SDK.");
        as3Dependency.setURL("http://www.adobe.com/products/flex/");
        as3Dependency.setVersion("2.0.1");
        clientDeps.add(as3Dependency);

        ClientLibraryArtifact as3ClientArtifact = new ClientLibraryArtifact(getName(), "as3.client.library",
                "ActionScript 3 Client Library");
        as3ClientArtifact.setPlatform("Adobe Flex");
        //read in the description from file:
        as3ClientArtifact.setDescription(readResource("library_description.fmt"));
        as3ClientArtifact.setDependencies(clientDeps);

        if (swcFile != null) {
            NamedFileArtifact clientArtifact = new NamedFileArtifact(getName(), "as3.client.swc", swcFile);
            clientArtifact.setDescription("The compiled SWC.");
            clientArtifact.setPublic(false);
            clientArtifact.setArtifactType(ArtifactType.binaries);
            as3ClientArtifact.addArtifact(clientArtifact);
            enunciate.addArtifact(clientArtifact);
        }

        if (asSources != null) {
            NamedFileArtifact clientArtifact = new NamedFileArtifact(getName(), "as3.client.sources",
                    asSources);
            clientArtifact.setDescription("The client-side ActionScript sources.");
            clientArtifact.setPublic(false);
            clientArtifact.setArtifactType(ArtifactType.sources);
            as3ClientArtifact.addArtifact(clientArtifact);
            enunciate.addArtifact(clientArtifact);
        }

        enunciate.addArtifact(as3ClientArtifact);
    }
}

From source file:org.apache.cocoon.servlet.CocoonServlet.java

/**
 * Retreives the "extra-classpath" attribute, that needs to be
 * added to the class path./*  w w w .  j a v a2 s  .  c  o m*/
 *
 * @throws ServletException
 */
protected String getExtraClassPath() throws ServletException {
    String extraClassPath = this.getInitParameter("extra-classpath");
    if (extraClassPath != null) {
        StringBuffer sb = new StringBuffer();
        StringTokenizer st = new StringTokenizer(extraClassPath, SystemUtils.PATH_SEPARATOR, false);
        int i = 0;
        while (st.hasMoreTokens()) {
            String s = st.nextToken();
            if (i++ > 0) {
                sb.append(File.pathSeparatorChar);
            }
            if ((s.charAt(0) == File.separatorChar) || (s.charAt(1) == ':')) {
                if (getLogger().isDebugEnabled()) {
                    getLogger().debug("extraClassPath is absolute: " + s);
                }
                sb.append(s);

                addClassLoaderDirectory(s);
            } else {
                if (s.indexOf("${") != -1) {
                    String path = StringUtils.replaceToken(s);
                    sb.append(path);
                    if (getLogger().isDebugEnabled()) {
                        getLogger().debug(
                                "extraClassPath is not absolute replacing using token: [" + s + "] : " + path);
                    }
                    addClassLoaderDirectory(path);
                } else {
                    String path = null;
                    if (this.servletContextPath != null) {
                        path = this.servletContextPath + s;
                        if (getLogger().isDebugEnabled()) {
                            getLogger()
                                    .debug("extraClassPath is not absolute pre-pending context path: " + path);
                        }
                    } else {
                        path = this.workDir.toString() + s;
                        if (getLogger().isDebugEnabled()) {
                            getLogger().debug(
                                    "extraClassPath is not absolute pre-pending work-directory: " + path);
                        }
                    }
                    sb.append(path);
                    addClassLoaderDirectory(path);
                }
            }
        }
        return sb.toString();
    }
    return "";
}

From source file:com.synox.android.ui.activity.FileDisplayActivity.java

private void requestSimpleUpload(Intent data, int resultCode) {
    String filePath = null;/*from w  w w.ja  v a  2 s . c om*/
    String mimeType = null;

    Uri selectedImageUri = data.getData();

    try {
        mimeType = getContentResolver().getType(selectedImageUri);

        String fileManagerString = selectedImageUri.getPath();
        String selectedImagePath = UriUtils.getLocalPath(selectedImageUri, this);

        if (selectedImagePath != null)
            filePath = selectedImagePath;
        else
            filePath = fileManagerString;

    } catch (Exception e) {
        Log_OC.e(TAG, "Unexpected exception when trying to read the result of " + "Intent.ACTION_GET_CONTENT",
                e);

    } finally {
        if (filePath == null) {
            Log_OC.e(TAG, "Couldn't resolve path to file");
            Toast t = Toast.makeText(this, getString(R.string.filedisplay_unexpected_bad_get_content),
                    Toast.LENGTH_LONG);
            t.show();
        }
    }

    Intent i = new Intent(this, FileUploader.class);
    i.putExtra(FileUploader.KEY_ACCOUNT, getAccount());
    OCFile currentDir = getCurrentDir();
    String remotePath = (currentDir != null) ? currentDir.getRemotePath() : OCFile.ROOT_PATH;

    if (filePath != null && filePath.startsWith(UriUtils.URI_CONTENT_SCHEME)) {
        Cursor cursor = getContentResolver().query(Uri.parse(filePath), null, null, null, null);
        try {
            if (cursor != null && cursor.moveToFirst()) {
                String displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                Log_OC.v(TAG, "Display Name: " + displayName);

                displayName.replace(File.separatorChar, '_');
                displayName.replace(File.pathSeparatorChar, '_');
                remotePath += displayName + DisplayUtils.getComposedFileExtension(filePath);

            }
            // and what happens in case of error?; wrong target name for the upload
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

    } else {
        if (filePath != null) {
            remotePath += new File(filePath).getName();
        }
    }

    i.putExtra(FileUploader.KEY_LOCAL_FILE, filePath);
    i.putExtra(FileUploader.KEY_REMOTE_FILE, remotePath);
    i.putExtra(FileUploader.KEY_MIME_TYPE, mimeType);
    i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
    if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
        i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
    startService(i);
}

From source file:org.apache.cocoon.portlet.CocoonPortlet.java

/**
 * Retreives the "extra-classpath" attribute, that needs to be
 * added to the class path./*from  ww w .j a v  a2  s. c o m*/
 *
 * @throws PortletException
 */
protected String getExtraClassPath() throws PortletException {
    String extraClassPath = this.getInitParameter("extra-classpath");
    if (extraClassPath != null) {
        StringBuffer sb = new StringBuffer();
        StringTokenizer st = new StringTokenizer(extraClassPath, SystemUtils.PATH_SEPARATOR, false);
        int i = 0;
        while (st.hasMoreTokens()) {
            String s = st.nextToken();
            if (i++ > 0) {
                sb.append(File.pathSeparatorChar);
            }
            if ((s.charAt(0) == File.separatorChar) || (s.charAt(1) == ':')) {
                if (getLogger().isDebugEnabled()) {
                    getLogger().debug("extraClassPath is absolute: " + s);
                }
                sb.append(s);

                addClassLoaderDirectory(s);
            } else {
                if (s.indexOf("${") != -1) {
                    String path = StringUtils.replaceToken(s);
                    sb.append(path);
                    if (getLogger().isDebugEnabled()) {
                        getLogger().debug(
                                "extraClassPath is not absolute replacing using token: [" + s + "] : " + path);
                    }
                    addClassLoaderDirectory(path);
                } else {
                    String path = null;
                    if (this.portletContextPath != null) {
                        path = this.portletContextPath + s;
                        if (getLogger().isDebugEnabled()) {
                            getLogger()
                                    .debug("extraClassPath is not absolute pre-pending context path: " + path);
                        }
                    } else {
                        path = this.workDir.toString() + s;
                        if (getLogger().isDebugEnabled()) {
                            getLogger().debug(
                                    "extraClassPath is not absolute pre-pending work-directory: " + path);
                        }
                    }
                    sb.append(path);
                    addClassLoaderDirectory(path);
                }
            }
        }
        return sb.toString();
    }
    return "";
}