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.gnieh.blue.launcher.Main.java

/**
 * <p>/*from  w  w  w. ja va  2 s  . co m*/
 * Loads the properties in the system property file associated with the
 * framework installation into <tt>System.setProperty()</tt>. These properties
 * are not directly used by the framework in anyway. By default, the system
 * property file is located in the <tt>conf/</tt> directory of the Felix
 * installation directory and is called "<tt>system.properties</tt>". The
 * installation directory of Felix is assumed to be the parent directory of
 * the <tt>felix.jar</tt> file as found on the system class path property.
 * The precise file from which to load system properties can be set by
 * initializing the "<tt>felix.system.properties</tt>" system property to an
 * arbitrary URL.
 * </p>
**/
public static void loadSystemProperties() {
    // The system properties file is either specified by a system
    // property or it is in the same directory as the Felix JAR file.
    // Try to load it from one of these places.

    // See if the property URL was specified as a property.
    URL propURL = null;
    String custom = System.getProperty(SYSTEM_PROPERTIES_PROP);
    if (custom != null) {
        try {
            propURL = new URL(custom);
        } catch (MalformedURLException ex) {
            System.err.print("Main: " + ex);
            return;
        }
    } else {
        // Determine where the configuration directory is by figuring
        // out where felix.jar is located on the system class path.
        File confDir = null;
        String classpath = System.getProperty("java.class.path");
        int index = classpath.toLowerCase().indexOf("felix.jar");
        int start = classpath.lastIndexOf(File.pathSeparator, index) + 1;
        if (index >= start) {
            // Get the path of the felix.jar file.
            String jarLocation = classpath.substring(start, index);
            // Calculate the conf directory based on the parent
            // directory of the felix.jar directory.
            confDir = new File(new File(new File(jarLocation).getAbsolutePath()).getParent(), CONFIG_DIRECTORY);
        } else {
            // Can't figure it out so use the current directory as default.
            confDir = new File(System.getProperty("user.dir"), CONFIG_DIRECTORY);
        }

        try {
            propURL = new File(confDir, SYSTEM_PROPERTIES_FILE_VALUE).toURI().toURL();
        } catch (MalformedURLException ex) {
            System.err.print("Main: " + ex);
            return;
        }
    }

    // Read the properties file.
    Properties props = new Properties();
    InputStream is = null;
    try {
        is = propURL.openConnection().getInputStream();
        props.load(is);
        is.close();
    } catch (FileNotFoundException ex) {
        // Ignore file not found.
    } catch (Exception ex) {
        System.err.println("Main: Error loading system properties from " + propURL);
        System.err.println("Main: " + ex);
        try {
            if (is != null)
                is.close();
        } catch (IOException ex2) {
            // Nothing we can do.
        }
        return;
    }

    // Perform variable substitution on specified properties.
    for (Enumeration e = props.propertyNames(); e.hasMoreElements();) {
        String name = (String) e.nextElement();
        System.setProperty(name, Util.substVars(props.getProperty(name), name, null, null));
    }
}

From source file:org.apache.hive.hcatalog.templeton.tool.TempletonUtils.java

public static StringBuilder dumpPropMap(String header, Map<String, String> map) {
    StringBuilder sb = new StringBuilder("START").append(header).append(":\n");
    List<String> propKeys = new ArrayList<String>(map.keySet());
    Collections.sort(propKeys);//from  w  w  w .ja v  a2  s  .c om
    for (String propKey : propKeys) {
        if (propKey.toLowerCase().contains("path")) {
            StringTokenizer st = new StringTokenizer(map.get(propKey), File.pathSeparator);
            if (st.countTokens() > 1) {
                sb.append(propKey).append("=\n");
                while (st.hasMoreTokens()) {
                    sb.append("    ").append(st.nextToken()).append(File.pathSeparator).append('\n');
                }
            } else {
                sb.append(propKey).append('=').append(map.get(propKey)).append('\n');
            }
        } else {
            sb.append(propKey).append('=').append(map.get(propKey)).append('\n');
        }
    }
    return sb.append("END").append(header).append('\n');
}

From source file:org.apache.maven.cli.DefaultMavenExecutionRequestBuilder.java

/**
private PlexusContainer container( CliRequest cliRequest )
throws Exception/*from w w w .  jav  a  2 s.  c o  m*/
{
if ( cliRequest.classWorld == null )
{
    cliRequest.classWorld = new ClassWorld( "plexus.core", Thread.currentThread().getContextClassLoader() );
}
        
DefaultPlexusContainer container = null;
        
ContainerConfiguration cc = new DefaultContainerConfiguration()
    .setClassWorld( cliRequest.classWorld )
    .setRealm( setupContainerRealm( cliRequest ) )
    .setClassPathScanning( PlexusConstants.SCANNING_INDEX )
    .setAutoWiring( true )
    .setName( "maven" );
        
container = new DefaultPlexusContainer( cc, new AbstractModule()
{
    protected void configure()
    {
        bind( ILoggerFactory.class ).toInstance( slf4jLoggerFactory );
    }
} );
        
// NOTE: To avoid inconsistencies, we'll use the TCCL exclusively for lookups
container.setLookupRealm( null );
        
container.setLoggerManager( plexusLoggerManager );
        
customizeContainer( container );
        
container.getLoggerManager().setThresholds( cliRequest.request.getLoggingLevel() );
        
Thread.currentThread().setContextClassLoader( container.getContainerRealm() );
        
eventSpyDispatcher = container.lookup( EventSpyDispatcher.class );
        
DefaultEventSpyContext eventSpyContext = new DefaultEventSpyContext();
Map<String, Object> data = eventSpyContext.getData();
data.put( "plexus", container );
data.put( "workingDirectory", cliRequest.workingDirectory );
data.put( "systemProperties", cliRequest.systemProperties );
data.put( "userProperties", cliRequest.userProperties );
data.put( "versionProperties", CLIReportingUtils.getBuildProperties() );
eventSpyDispatcher.init( eventSpyContext );
        
// refresh logger in case container got customized by spy
slf4jLogger = slf4jLoggerFactory.getLogger( this.getClass().getName() );
        
maven = container.lookup( Maven.class );
        
executionRequestPopulator = container.lookup( MavenExecutionRequestPopulator.class );
        
modelProcessor = createModelProcessor( container );
        
settingsBuilder = container.lookup( SettingsBuilder.class );
        
dispatcher = (DefaultSecDispatcher) container.lookup( SecDispatcher.class, "maven" );
        
return container;
}
**/

// FIXME this must be done!!!
private ClassRealm setupContainerRealm(CliRequest cliRequest) throws Exception {
    ClassRealm containerRealm = null;

    String extClassPath = cliRequest.userProperties.getProperty(EXT_CLASS_PATH);
    if (extClassPath == null) {
        extClassPath = cliRequest.systemProperties.getProperty(EXT_CLASS_PATH);
    }

    if (StringUtils.isNotEmpty(extClassPath)) {
        String[] jars = StringUtils.split(extClassPath, File.pathSeparator);

        if (jars.length > 0) {
            ClassRealm coreRealm = cliRequest.classWorld.getClassRealm("plexus.core");
            if (coreRealm == null) {
                coreRealm = (ClassRealm) cliRequest.classWorld.getRealms().iterator().next();
            }

            ClassRealm extRealm = cliRequest.classWorld.newRealm("maven.ext", null);

            slf4jLogger.debug("Populating class realm " + extRealm.getId());

            for (String jar : jars) {
                File file = resolveFile(new File(jar), cliRequest.workingDirectory);

                slf4jLogger.debug("  Included " + file);

                extRealm.addURL(file.toURI().toURL());
            }

            extRealm.setParentRealm(coreRealm);

            containerRealm = extRealm;
        }
    }

    return containerRealm;
}

From source file:jeplus.RadianceWinTools.java

/**
 * Call DaySim gen_dc to run the simulation
 * @param config Radiance Configuration//  w  w w  .j av  a2 s.c  om
 * @param WorkDir The working directory where the input files are stored and the output files to be generated
 * @param model
 * @param in
 * @param out
 * @param err
 * @param process
 * @return the result code represents the state of execution steps. >=0 means successful
 */
public static int runGen_DC(RadianceConfig config, String WorkDir, String model, String in, String out,
        String err, ProcessWrapper process) {

    int ExitValue = -99;

    // Manipulate header file
    HashMap<String, String> props = new HashMap<>();
    // props.put("project_name", "");
    props.put("project_directory", "./");
    props.put("bin_directory", config.getResolvedDaySimBinDir());
    props.put("tmp_directory", "./");
    props.put("Template_File", config.getResolvedDaySimBinDir() + "../template/");
    props.put("sensor_file", in);
    try {
        FileUtils.moveFile(new File(WorkDir + File.separator + model),
                new File(WorkDir + File.separator + model + ".ori"));
    } catch (IOException ex) {
        logger.error("Error renaming header file to " + WorkDir + File.separator + model + ".ori", ex);
    }
    DaySimModel.updateHeaderFile(WorkDir + File.separator + model + ".ori", WorkDir + File.separator + model,
            props);

    // Run command
    try {
        StringBuilder buf = new StringBuilder(config.getResolvedDaySimBinDir());
        buf.append(File.separator).append("gen_dc");

        List<String> command = new ArrayList<>();
        command.add(buf.toString());
        command.add(model);
        ProcessBuilder builder = new ProcessBuilder(command);
        builder.directory(new File(WorkDir));
        builder.environment().put("RAYPATH", "." + File.pathSeparator + config.getResolvedDaySimLibDir());
        builder.redirectOutput(new File(WorkDir + File.separator + out));
        if (err == null || out.equals(err)) {
            builder.redirectErrorStream(true);
        } else {
            builder.redirectError(new File(WorkDir + File.separator + err));
        }
        if (in != null) {
            builder.redirectInput(new File(WorkDir + File.separator + in));
        }
        Process proc = builder.start();
        if (process != null) {
            process.setWrappedProc(proc);
        }
        ExitValue = proc.waitFor();
    } catch (IOException | InterruptedException ex) {
        logger.error("Error occoured when executing DaySim gen_dc", ex);
    }

    // Return Radiance exit value
    return ExitValue;
}

From source file:com.igormaznitsa.mvngolang.AbstractGolangMojo.java

@Nonnull
public File findGoPath(final boolean ensureExist) throws IOException {
    LOCKER.lock();// w w  w. ja  v  a2 s  .c o  m
    try {
        final String theGoPath = getGoPath();

        if (theGoPath.contains(File.pathSeparator)) {
            getLog().error(
                    "Detected multiple folder items in the 'goPath' parameter but it must contain only folder!");
            throw new IOException("Detected multiple folder items in the 'goPath'");
        }

        final File result = new File(theGoPath);
        if (ensureExist && !result.isDirectory() && !result.mkdirs()) {
            throw new IOException("Can't create folder : " + theGoPath);
        }
        return result;
    } finally {
        LOCKER.unlock();
    }
}

From source file:nl.mpi.lamus.workspace.upload.implementation.LamusWorkspaceUploadHelperTest.java

@Test
public void assureLinksArchiveExternalPidResourceReference()
        throws URISyntaxException, MalformedURLException, IOException, MetadataException, WorkspaceException {

    final File uploadDirectory = new File("/workspaces/" + workspaceID + "/upload");

    final String parentFilename = "parent.cmdi";
    final URL parentFileURL = new URL(uploadDirectory.toURI() + File.pathSeparator + parentFilename);

    final Collection<WorkspaceNode> nodesToCheck = new ArrayList<>();
    nodesToCheck.add(mockChildNode);/*w w w  .  j  av  a 2s.com*/
    nodesToCheck.add(mockParentNode);

    final Collection<ImportProblem> failedLinks = new ArrayList<>();
    final Map<MetadataDocument, WorkspaceNode> documentsWithInvalidSelfHandles = new HashMap<>();

    context.checking(new Expectations() {
        {

            // loop

            // first iteration - not metadata, so jumps to next iteration
            oneOf(mockNodeUtil).isNodeMetadata(mockChildNode);
            will(returnValue(Boolean.FALSE));

            // second iteration - metadata, so continues in this iteration
            oneOf(mockNodeUtil).isNodeMetadata(mockParentNode);
            will(returnValue(Boolean.TRUE));
            oneOf(mockParentNode).getWorkspaceURL();
            will(returnValue(parentFileURL));
            oneOf(mockMetadataAPI).getMetadataDocument(parentFileURL);
            will(returnValue(mockParentDocument));

            oneOf(mockWorkspaceUploadReferenceHandler).matchReferencesWithNodes(mockWorkpace, nodesToCheck,
                    mockParentNode, mockParentDocument, documentsWithInvalidSelfHandles);
            will(returnValue(failedLinks));
        }
    });

    Collection<ImportProblem> result = workspaceUploadHelper.assureLinksInWorkspace(mockWorkpace, nodesToCheck);

    assertTrue("Result different from expected", result.isEmpty());
}

From source file:org.jenkinsci.plugins.neoload.integration.supporting.PluginUtils.java

public static Run.Artifact findArtifacts(final List<String> paths, final List artifacts,
        final int buildnumber) {
    //To be compatible  with older we try different paths.
    for (String path : paths) {
        path = path.replaceAll("\\$\\{BUILD_NUMBER\\}", Integer.toString(buildnumber));
        //Variable issues ${workspace/toto become /toto and it not found.
        while (path.startsWith(File.pathSeparator)) {
            path = path.substring(1);//from  ww  w. ja  v a2  s.c  o m
        }
        for (Object object : artifacts) {
            Run.Artifact artifact = (Run.Artifact) object;//Because the run and action is little different.
            if (artifact.relativePath.endsWith(path)) {
                return artifact;
            }
        }
    }
    return null;
}

From source file:org.apache.pig.PigServer.java

private void markPredeployedJarsFromProperties() throws ExecException {
    // mark jars as predeployed from properties
    String jar_str = pigContext.getProperties().getProperty("pig.predeployed.jars");

    if (jar_str != null) {
        // Use File.pathSeparator (":" on Linux, ";" on Windows)
        // to correctly handle path aggregates as they are represented
        // on the Operating System.
        for (String jar : jar_str.split(File.pathSeparator)) {
            if (jar.length() > 0) {
                pigContext.markJarAsPredeployed(jar);
            }//  w ww.j  ava  2  s . c o  m
        }
    }
}

From source file:org.apache.maven.cli.CopyOfMavenCli.java

private ClassRealm setupContainerRealm(CliRequest cliRequest) throws Exception {
    ClassRealm containerRealm = null;//from   w ww .ja  v a2  s .  c  o  m

    String extClassPath = cliRequest.userProperties.getProperty(EXT_CLASS_PATH);
    if (extClassPath == null) {
        extClassPath = cliRequest.systemProperties.getProperty(EXT_CLASS_PATH);
    }

    if (StringUtils.isNotEmpty(extClassPath)) {
        String[] jars = StringUtils.split(extClassPath, File.pathSeparator);

        if (jars.length > 0) {
            ClassRealm coreRealm = cliRequest.classWorld.getClassRealm("plexus.core");
            if (coreRealm == null) {
                coreRealm = cliRequest.classWorld.getRealms().iterator().next();
            }

            ClassRealm extRealm = cliRequest.classWorld.newRealm("maven.ext", null);

            slf4jLogger.debug("Populating class realm " + extRealm.getId());

            for (String jar : jars) {
                File file = resolveFile(new File(jar), cliRequest.workingDirectory);

                slf4jLogger.debug("  Included " + file);

                extRealm.addURL(file.toURI().toURL());
            }

            extRealm.setParentRealm(coreRealm);

            containerRealm = extRealm;
        }
    }

    return containerRealm;
}

From source file:org.apache.slider.providers.agent.AgentProviderService.java

@Override
public void buildContainerLaunchContext(ContainerLauncher launcher, AggregateConf instanceDefinition,
        Container container, String role, SliderFileSystem fileSystem, Path generatedConfPath,
        MapOperations resourceComponent, MapOperations appComponent, Path containerTmpDirPath)
        throws IOException, SliderException {

    String appDef = instanceDefinition.getAppConfOperations().getGlobalOptions()
            .getMandatoryOption(AgentKeys.APP_DEF);

    initializeApplicationConfiguration(instanceDefinition, fileSystem);

    log.info("Build launch context for Agent");
    log.debug(instanceDefinition.toString());

    // Set the environment
    launcher.putEnv(SliderUtils.buildEnvMap(appComponent));

    String workDir = ApplicationConstants.Environment.PWD.$();
    launcher.setEnv("AGENT_WORK_ROOT", workDir);
    log.info("AGENT_WORK_ROOT set to {}", workDir);
    String logDir = ApplicationConstants.LOG_DIR_EXPANSION_VAR;
    launcher.setEnv("AGENT_LOG_ROOT", logDir);
    log.info("AGENT_LOG_ROOT set to {}", logDir);
    if (System.getenv(HADOOP_USER_NAME) != null) {
        launcher.setEnv(HADOOP_USER_NAME, System.getenv(HADOOP_USER_NAME));
    }// w w  w  . j av  a 2 s  . co  m
    // for 2-Way SSL
    launcher.setEnv(SLIDER_PASSPHRASE, instanceDefinition.getPassphrase());

    //local resources

    // TODO: Should agent need to support App Home
    String scriptPath = new File(AgentKeys.AGENT_MAIN_SCRIPT_ROOT, AgentKeys.AGENT_MAIN_SCRIPT).getPath();
    String appHome = instanceDefinition.getAppConfOperations().getGlobalOptions().get(AgentKeys.PACKAGE_PATH);
    if (SliderUtils.isSet(appHome)) {
        scriptPath = new File(appHome, AgentKeys.AGENT_MAIN_SCRIPT).getPath();
    }

    // set PYTHONPATH
    List<String> pythonPaths = new ArrayList<String>();
    pythonPaths.add(AgentKeys.AGENT_MAIN_SCRIPT_ROOT);
    String pythonPath = StringUtils.join(File.pathSeparator, pythonPaths);
    launcher.setEnv(PYTHONPATH, pythonPath);
    log.info("PYTHONPATH set to {}", pythonPath);

    Path agentImagePath = null;
    String agentImage = instanceDefinition.getInternalOperations()
            .get(InternalKeys.INTERNAL_APPLICATION_IMAGE_PATH);
    if (SliderUtils.isUnset(agentImage)) {
        agentImagePath = new Path(new Path(
                new Path(instanceDefinition.getInternalOperations().get(InternalKeys.INTERNAL_TMP_DIR),
                        container.getId().getApplicationAttemptId().getApplicationId().toString()),
                AgentKeys.PROVIDER_AGENT), SliderKeys.AGENT_TAR);
    } else {
        agentImagePath = new Path(agentImage);
    }

    // TODO: throw exception when agent tarball is not available

    if (fileSystem.getFileSystem().exists(agentImagePath)) {
        LocalResource agentImageRes = fileSystem.createAmResource(agentImagePath, LocalResourceType.ARCHIVE);
        launcher.addLocalResource(AgentKeys.AGENT_INSTALL_DIR, agentImageRes);
    } else {
        log.error("Required agent image slider-agent.tar.gz is unavailable.");
    }

    log.info("Using {} for agent.", scriptPath);
    LocalResource appDefRes = fileSystem.createAmResource(
            fileSystem.getFileSystem().resolvePath(new Path(appDef)), LocalResourceType.ARCHIVE);
    launcher.addLocalResource(AgentKeys.APP_DEFINITION_DIR, appDefRes);

    String agentConf = instanceDefinition.getAppConfOperations().getGlobalOptions()
            .getOption(AgentKeys.AGENT_CONF, "");
    if (SliderUtils.isSet(agentConf)) {
        LocalResource agentConfRes = fileSystem.createAmResource(
                fileSystem.getFileSystem().resolvePath(new Path(agentConf)), LocalResourceType.FILE);
        launcher.addLocalResource(AgentKeys.AGENT_CONFIG_FILE, agentConfRes);
    }

    String agentVer = instanceDefinition.getAppConfOperations().getGlobalOptions()
            .getOption(AgentKeys.AGENT_VERSION, null);
    if (agentVer != null) {
        LocalResource agentVerRes = fileSystem.createAmResource(
                fileSystem.getFileSystem().resolvePath(new Path(agentVer)), LocalResourceType.FILE);
        launcher.addLocalResource(AgentKeys.AGENT_VERSION_FILE, agentVerRes);
    }

    if (SliderUtils.isHadoopClusterSecure(getConfig())) {
        localizeServiceKeytabs(launcher, instanceDefinition, fileSystem);
    }

    MapOperations amComponent = instanceDefinition.getAppConfOperations().getComponent(SliderKeys.COMPONENT_AM);
    boolean twoWayEnabled = amComponent != null
            ? Boolean.valueOf(amComponent.getOptionBool(AgentKeys.KEY_AGENT_TWO_WAY_SSL_ENABLED, false))
            : false;
    if (twoWayEnabled) {
        localizeContainerSSLResources(launcher, container, fileSystem);
    }

    //add the configuration resources
    launcher.addLocalResources(
            fileSystem.submitDirectory(generatedConfPath, SliderKeys.PROPAGATED_CONF_DIR_NAME));

    String label = getContainerLabel(container, role);
    CommandLineBuilder operation = new CommandLineBuilder();

    String pythonExec = instanceDefinition.getAppConfOperations().getGlobalOptions()
            .getOption(SliderXmlConfKeys.PYTHON_EXECUTABLE_PATH, AgentKeys.PYTHON_EXE);

    operation.add(pythonExec);

    operation.add(scriptPath);
    operation.add(ARG_LABEL, label);
    operation.add(ARG_ZOOKEEPER_QUORUM);
    operation.add(getClusterOptionPropertyValue(OptionKeys.ZOOKEEPER_QUORUM));
    operation.add(ARG_ZOOKEEPER_REGISTRY_PATH);
    operation.add(getZkRegistryPath());

    String debugCmd = agentLaunchParameter.getNextLaunchParameter(role);
    if (SliderUtils.isSet(debugCmd)) {
        operation.add(ARG_DEBUG);
        operation.add(debugCmd);
    }

    operation.add("> " + ApplicationConstants.LOG_DIR_EXPANSION_VAR + "/" + AgentKeys.AGENT_OUT_FILE + " 2>&1");

    launcher.addCommand(operation.build());

    // initialize the component instance state
    getComponentStatuses().put(label, new ComponentInstanceState(role, container.getId(),
            getClusterInfoPropertyValue(OptionKeys.APPLICATION_NAME)));
}