Example usage for org.apache.commons.lang BooleanUtils toBoolean

List of usage examples for org.apache.commons.lang BooleanUtils toBoolean

Introduction

In this page you can find the example usage for org.apache.commons.lang BooleanUtils toBoolean.

Prototype

public static boolean toBoolean(String str) 

Source Link

Document

Converts a String to a boolean (optimised for performance).

'true', 'on' or 'yes' (case insensitive) will return true.

Usage

From source file:org.cloudifysource.esc.driver.provisioning.openstack.OpenStackCloudifyDriver.java

private void createExternalNetworking(final Network network, final Subnet subnet)
        throws OpenstackException, CloudProvisioningException {

    final Router router;
    if (this.networkHelper.isCreateExternalRouter()) {
        final String publicNetworkId;
        if (this.networkHelper.isExternalNetworkNameSpecified()) {
            publicNetworkId = networkApi.getPublicNetworkId();
        } else {//  w  w w .j a v a2 s  .c o m
            final Network extNetwork = networkApi.getNetworkByName(this.networkHelper.getExternalNetworkName());
            if (extNetwork == null) {
                throw new CloudProvisioningException(
                        "Couldn't find external network '" + this.networkHelper.getExternalNetworkName() + "'");
            }
            if (!BooleanUtils.toBoolean(extNetwork.getRouterExternal())) {
                throw new CloudProvisioningException("The network '"
                        + this.networkHelper.getExternalNetworkName() + "' is not an external network");
            }

            publicNetworkId = extNetwork.getId();
        }
        final Router request = new Router();
        request.setName(this.openstackPrefixes.getPrefix() + MANAGEMENT_PUBLIC_ROUTER_NAME);
        request.setAdminStateUp(true);
        request.setExternalGatewayInfo(new RouterExternalGatewayInfo(publicNetworkId));
        router = networkApi.createRouter(request);
    } else {
        router = networkApi.getRouterByName(this.networkHelper.getExternalRouterName());
        if (router == null) {
            throw new CloudProvisioningException(
                    "Couldn't find external router '" + this.networkHelper.getExternalRouterName() + "'");
        }
    }

    if (subnet == null) {
        throw new CloudProvisioningException("Cannot add router interface because the network '"
                + network.getName() + "' don't have any subnets");
    }

    // Add interface
    networkApi.addRouterInterface(router.getId(), subnet.getId());
}

From source file:org.cloudifysource.esc.driver.provisioning.openstack.OpenStackNetworkConfigurationHelper.java

/***
 * Returns <code>false</code> if the configuration requires to create and to configure a router to an external
 * network.//from   w  w  w .ja  va2 s .com
 * 
 * @return Returns <code>false</code> if the configuration need has specified an external network to use.
 */
public boolean skipExternalNetworking() {
    if (management) {
        final String skipExtNetStr = (String) managementNetworkOptions
                .get(OpenStackCloudifyDriver.OPT_SKIP_EXTERNAL_NETWORKING);
        return BooleanUtils.toBoolean(skipExtNetStr);
    }
    return false;
}

From source file:org.cloudifysource.esc.driver.provisioning.openstack.OpenStackNetworkConfigurationHelper.java

/***
 * Returns <code>true</code> if requires floating IP.
 * //from  ww  w.  jav a2  s.c  o m
 * @return Returns <code>true</code> if requires floating IP.
 */
public boolean associateFloatingIp() {
    if (management && this.managementNetworkConfiguration != null) {
        final String associate = this.managementNetworkConfiguration.getCustom()
                .get(ASSOCIATE_FLOATING_IP_ON_BOOTSTRAP);
        return BooleanUtils.toBoolean(associate);
    } else if (this.applicationNetworkConfiguration != null) {
        final String associate = this.applicationNetworkConfiguration.getCustom()
                .get(ASSOCIATE_FLOATING_IP_ON_BOOTSTRAP);
        return BooleanUtils.toBoolean(associate);
    } else if (!management && this.applicationNetworkConfiguration == null && this.computeNetworks.isEmpty()) {
        // We are using management networks only.
        final String associate = this.managementNetworkConfiguration.getCustom()
                .get(ASSOCIATE_FLOATING_IP_ON_BOOTSTRAP);
        return BooleanUtils.toBoolean(associate);
    }
    return false;
}

From source file:org.cloudifysource.esc.driver.provisioning.privateEc2.PrivateEC2CloudifyDriver.java

/**
 * *****************************************************************************************************************
 *//*from w  w w.j a  v  a  2  s  . co m*/

/*
 * (non-Javadoc)
 * 
 * @see
 * org.cloudifysource.esc.driver.provisioning.BaseProvisioningDriver#setConfig(org.cloudifysource.dsl.cloud.Cloud,
 * java.lang.String, boolean, java.lang.String)
 */
@Override
public void setConfig(final Cloud cloud, final String cloudTemplateName, final boolean management,
        final String fullServiceName) {

    logger.fine("Running path : " + System.getProperty("user.dir"));

    this.serviceName = this.getSimpleServiceName(fullServiceName);
    this.cloudTemplateName = cloudTemplateName;
    this.cloudName = cloud.getName();
    super.setConfig(cloud, cloudTemplateName, management, fullServiceName);

    if (logger.isLoggable(Level.FINER)) {
        logger.finer("Service name : " + this.serviceName + "(" + fullServiceName + ")");
    }

    try {
        ComputeTemplate managerTemplate = this.getManagerComputeTemplate();

        // Initialize the ec2 client if the service use the CFN template
        if (management) {
            // TODO - NO VALIDATION!
            managerCfnTemplateFileName = (String) managerTemplate.getCustom().get("cfnManagerTemplate");
        } else {
            this.privateEc2Template = cfnTemplatePerService.get(this.serviceName);
            if (this.privateEc2Template == null) {
                throw new IllegalArgumentException("CFN template not found for service:" + fullServiceName);
            }
        }
        this.ec2 = this.createAmazonEC2();

        // Create s3 client
        String locationId = (String) managerTemplate.getCustom().get("s3LocationId");
        CloudUser user = this.cloud.getUser();
        this.amazonS3Uploader = new AmazonS3Uploader(user.getUser(), user.getApiKey(), locationId);

        // Setup debug console output
        final boolean debug = BooleanUtils.toBoolean((String) managerTemplate.getCustom().get("debugMode"));
        if (debug) {
            this.debugExecutors = Executors.newFixedThreadPool(NB_THREADS_CONSOLE_OUTPUT);
        }

    } catch (final CloudProvisioningException e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:org.cloudifysource.esc.driver.provisioning.privateEc2.PrivateEC2CloudifyDriver.java

private Instance createEC2Instance(final PrivateEc2Template cfnTemplate, final ProvisioningContextImpl ctx,
        final boolean management, final String machineName, final long duration, final TimeUnit unit)
        throws CloudProvisioningException, TimeoutException {

    final ComputeTemplate template = this.getManagerComputeTemplate();
    final InstanceProperties properties = cfnTemplate.getEC2Instance().getProperties();

    final String availabilityZone = properties.getAvailabilityZone() == null ? null
            : properties.getAvailabilityZone().getValue();
    final Placement placement = availabilityZone == null ? null : new Placement(availabilityZone);
    final String imageId = properties.getImageId() == null ? null : properties.getImageId().getValue();
    final String instanceType = properties.getInstanceType() == null ? null
            : properties.getInstanceType().getValue();
    final String keyName = properties.getKeyName() == null ? null : properties.getKeyName().getValue();
    final String privateIpAddress = properties.getPrivateIpAddress() == null ? null
            : properties.getPrivateIpAddress().getValue();
    final List<String> securityGroupIds = properties.getSecurityGroupIdsAsString();
    final List<String> securityGroups = properties.getSecurityGroupsAsString();

    S3Object s3Object = null;
    try {//from  ww  w. ja  v  a  2  s.  c  o m

        String userData = null;
        if (properties.getUserData() != null) {
            // Generate ENV script for the provisioned machine
            final StringBuilder sb = new StringBuilder();
            final String script = management ? this.generateManagementCloudifyEnv(ctx)
                    : this.generateCloudifyEnv(ctx);

            s3Object = this.uploadCloudDir(ctx, script, management);
            final String cloudFileS3 = this.amazonS3Uploader.generatePresignedURL(s3Object);

            String cloudFileDir = (String) template.getRemoteDirectory();
            // Remove '/' from the path if it's the last char.
            if (cloudFileDir.length() > 1 && cloudFileDir.endsWith("/")) {
                cloudFileDir = cloudFileDir.substring(0, cloudFileDir.length() - 1);
            }
            final String endOfLine = " >> /tmp/cloud.txt\n";
            sb.append("#!/bin/bash\n");
            sb.append("export TMP_DIRECTORY=/tmp").append(endOfLine);
            sb.append("export S3_ARCHIVE_FILE='" + cloudFileS3 + "'").append(endOfLine);
            sb.append("wget -q -O $TMP_DIRECTORY/cloudArchive.tar.gz $S3_ARCHIVE_FILE").append(endOfLine);
            sb.append("mkdir -p " + cloudFileDir).append(endOfLine);
            sb.append("tar zxvf $TMP_DIRECTORY/cloudArchive.tar.gz -C " + cloudFileDir).append(endOfLine);
            sb.append("rm -f $TMP_DIRECTORY/cloudArchive.tar.gz").append(endOfLine);
            sb.append("echo ").append(cloudFileDir).append("/").append(CLOUDIFY_ENV_SCRIPT).append(endOfLine);
            sb.append("chmod 755 ").append(cloudFileDir).append("/").append(CLOUDIFY_ENV_SCRIPT)
                    .append(endOfLine);
            sb.append("source ").append(cloudFileDir).append("/").append(CLOUDIFY_ENV_SCRIPT).append(endOfLine);

            sb.append(properties.getUserData().getValue());
            userData = sb.toString();
            logger.fine("Instanciate ec2 with user data:\n" + userData);
            userData = StringUtils.newStringUtf8(Base64.encodeBase64(userData.getBytes()));
        }

        List<BlockDeviceMapping> blockDeviceMappings = null;
        AWSEC2Volume volumeConfig = null;
        if (properties.getVolumes() != null) {
            blockDeviceMappings = new ArrayList<BlockDeviceMapping>(properties.getVolumes().size());
            for (final VolumeMapping volMapping : properties.getVolumes()) {
                volumeConfig = cfnTemplate.getEC2Volume(volMapping.getVolumeId().getValue());
                blockDeviceMappings
                        .add(this.createBlockDeviceMapping(volMapping.getDevice().getValue(), volumeConfig));
            }
        }

        final RunInstancesRequest runInstancesRequest = new RunInstancesRequest();
        runInstancesRequest.withPlacement(placement);
        runInstancesRequest.withImageId(imageId);
        runInstancesRequest.withInstanceType(instanceType);
        runInstancesRequest.withKeyName(keyName);
        runInstancesRequest.withPrivateIpAddress(privateIpAddress);
        runInstancesRequest.withSecurityGroupIds(securityGroupIds);
        runInstancesRequest.withSecurityGroups(securityGroups);
        runInstancesRequest.withMinCount(1);
        runInstancesRequest.withMaxCount(1);
        runInstancesRequest.withBlockDeviceMappings(blockDeviceMappings);
        runInstancesRequest.withUserData(userData);

        if (logger.isLoggable(Level.FINEST)) {
            logger.finest("EC2::Instance request=" + runInstancesRequest);
        }

        final RunInstancesResult runInstances = this.ec2.runInstances(runInstancesRequest);
        if (runInstances.getReservation().getInstances().size() != 1) {
            throw new CloudProvisioningException(
                    "Request runInstace fails (request=" + runInstancesRequest + ").");
        }

        Instance ec2Instance = runInstances.getReservation().getInstances().get(0);
        ec2Instance = this.waitRunningInstance(ec2Instance, duration, unit);
        this.tagEC2Instance(ec2Instance, machineName, cfnTemplate.getEC2Instance());
        this.tagEC2Volumes(ec2Instance.getInstanceId(), cfnTemplate);

        final boolean debug = BooleanUtils.toBoolean((String) template.getCustom().get("debugMode"));
        if (debug) {
            debugExecutors.submit(new EC2Console(ec2Instance.getInstanceId(), ec2Instance.getPublicIpAddress(),
                    DEFAULT_CLOUDIFY_AGENT_PORT));
        }
        this.waitRunningAgent(ec2Instance.getPublicIpAddress(), duration, unit);

        return ec2Instance;
    } finally {
        if (s3Object != null) {
            this.amazonS3Uploader.deleteS3Object(s3Object.getBucketName(), s3Object.getKey());
        }
    }
}

From source file:org.codehaus.groovy.grails.web.pages.GroovyPageParser.java

public GroovyPageParser(String name, String uri, String filename, InputStream in, String encoding,
        String expressionCodecName) throws IOException {
    Map<?, ?> config = Holders.getFlatConfig();

    this.gspEncoding = encoding;
    if (this.gspEncoding == null) {
        if (config != null) {
            Object gspEnc = config.get(GroovyPageParser.CONFIG_PROPERTY_GSP_ENCODING);
            if ((gspEnc != null) && (gspEnc.toString().trim().length() > 0)) {
                this.gspEncoding = gspEnc.toString();
            }/*from  w  w w .ja  v a 2  s  .  c o  m*/
        }
    }

    if (config != null) {
        Object sitemeshPreprocessEnabled = config.get(GroovyPageParser.CONFIG_PROPERTY_GSP_SITEMESH_PREPROCESS);
        if (sitemeshPreprocessEnabled != null) {
            final boolean enableSitemeshPreprocessing = BooleanUtils
                    .toBoolean(String.valueOf(sitemeshPreprocessEnabled).trim());
            setEnableSitemeshPreprocessing(enableSitemeshPreprocessing);
        }
    }

    GrailsPluginInfo pluginInfo = null;
    if (filename != null && BuildSettingsHolder.getSettings() != null) {
        pluginInfo = GrailsPluginUtils.getPluginBuildSettings().getPluginInfoForSource(filename);
        if (pluginInfo != null) {
            pluginAnnotation = "@GrailsPlugin(name='" + pluginInfo.getName() + "', version='"
                    + pluginInfo.getVersion() + "')";
        }
    }

    GroovyPageConfig gspConfig = new GroovyPageConfig(config);

    this.expressionCodecDirectiveValue = expressionCodecName;
    if (expressionCodecDirectiveValue == null) {
        expressionCodecDirectiveValue = gspConfig.getCodecSettings(pluginInfo,
                GroovyPageConfig.EXPRESSION_CODEC_NAME);
    }
    staticCodecDirectiveValue = gspConfig.getCodecSettings(pluginInfo, GroovyPageConfig.STATIC_CODEC_NAME);
    outCodecDirectiveValue = gspConfig.getCodecSettings(pluginInfo, GroovyPageConfig.OUT_CODEC_NAME);
    taglibCodecDirectiveValue = gspConfig.getCodecSettings(pluginInfo, GroovyPageConfig.TAGLIB_CODEC_NAME);

    String gspSource = readStream(in);

    Map<String, String> directives = parseDirectives(gspSource);

    if (isSitemeshPreprocessingEnabled(directives.get(SITEMESH_PREPROCESS_DIRECTIVE))) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Preprocessing " + uri
                    + " for sitemesh. Replacing head, title, meta and body elements with sitemesh:capture*.");
        }
        // GSP preprocessing for direct sitemesh integration: replace head -> g:captureHead, title -> g:captureTitle, meta -> g:captureMeta, body -> g:captureBody
        gspSource = sitemeshPreprocessor.addGspSitemeshCapturing(gspSource);
        sitemeshPreprocessMode = true;
    }
    scan = new GroovyPageScanner(gspSource, uri);
    pageName = uri;
    environment = Environment.getCurrent();
    makeName(name);
    makeSourceName(filename);
}

From source file:org.codehaus.groovy.grails.web.pages.GroovyPageParser.java

private boolean isSitemeshPreprocessingEnabled(String gspFilePreprocessDirective) {
    if (gspFilePreprocessDirective != null) {
        return BooleanUtils.toBoolean(gspFilePreprocessDirective.trim());
    }//from w  w  w  .  java2 s  .  c  o m
    return enableSitemeshPreprocessing;
}

From source file:org.codehaus.httpcache4j.auth.digest.Digest.java

public Digest(HTTPHost host, AuthScheme scheme) {
    this.scheme = scheme;
    Directives directives = scheme.getDirectives();

    this.host = host;
    this.nonce = directives.get("nonce");
    this.domain = parseDomain(directives.get("domain"));
    this.opaque = directives.get("opaque");
    this.stale = BooleanUtils.toBoolean(directives.get("stale"));
    this.algorithm = Algorithm.getAlgorithm(directives.get("algorithm"));
    this.qop = directives.get("qop");
}

From source file:org.codehaus.mojo.webstart.generator.AbstractGenerator.java

/**
 * Creates a Velocity context and populates it with replacement values
 * for our pre-defined placeholders.//from   w w  w.j a  v  a2  s.c o  m
 *
 * @return Returns a velocity context with system and maven properties added
 */
protected VelocityContext createAndPopulateContext() {
    VelocityContext context = new VelocityContext();

    context.put("dependencies", getDependenciesText());

    // Note: properties that contain dots will not be properly parsed by Velocity. 
    // Should we replace dots with underscores ?        
    addPropertiesToContext(System.getProperties(), context);

    MavenProject mavenProject = config.getMavenProject();
    String encoding = config.getEncoding();

    addPropertiesToContext(mavenProject.getProperties(), context);
    addPropertiesToContext(extraConfig.getProperties(), context);

    context.put("project", mavenProject.getModel());
    context.put("jnlpCodebase", extraConfig.getJnlpCodeBase());

    // aliases named after the JNLP file structure
    context.put("informationTitle", mavenProject.getModel().getName());
    context.put("informationDescription", mavenProject.getModel().getDescription());
    if (mavenProject.getModel().getOrganization() != null) {
        context.put("informationVendor", mavenProject.getModel().getOrganization().getName());
        context.put("informationHomepage", mavenProject.getModel().getOrganization().getUrl());
    }

    // explicit timestamps in local and and UTC time zones
    Date timestamp = new Date();
    context.put("explicitTimestamp", dateToExplicitTimestamp(timestamp));
    context.put("explicitTimestampUTC", dateToExplicitTimestampUTC(timestamp));

    context.put("outputFile", config.getOutputFile().getName());
    context.put("mainClass", config.getMainClass());

    context.put("encoding", encoding);
    context.put("input.encoding", encoding);
    context.put("output.encoding", encoding);

    // TODO make this more extensible
    context.put("allPermissions", BooleanUtils.toBoolean(extraConfig.getAllPermissions()));
    context.put("offlineAllowed", BooleanUtils.toBoolean(extraConfig.getOfflineAllowed()));
    context.put("jnlpspec", extraConfig.getJnlpSpec());
    context.put("j2seVersion", extraConfig.getJ2seVersion());

    return context;
}

From source file:org.datacite.mds.service.userdetails.UserDetailsServiceImpl.java

@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
    log4j.debug("trying to find user name " + username);
    AllocatorOrDatacentre user = DomainUtils.findAllocatorOrDatacentreBySymbol(username);

    if (user == null)
        throw new UsernameNotFoundException("user not found");

    String symbol = user.getSymbol();
    String password = user.getPassword();
    String role = user.getRoleName();
    boolean isActive = BooleanUtils.toBoolean(user.getIsActive());
    log4j.debug("found " + symbol + " (" + role + ")");

    boolean credentialsNonExpired = true;
    if (StringUtils.isEmpty(password)) {
        password = "password must not be empty";
        credentialsNonExpired = false;/*from  w ww.  j  a v  a2s. c o m*/
    }

    Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    authorities.add(new GrantedAuthorityImpl(role));

    for (String experiment : user.getExperiments()) {
        String experiment_role = ROLE_EXPERIMENT_PREFIX + experiment.toUpperCase();
        authorities.add(new GrantedAuthorityImpl(experiment_role));
    }

    return new User(symbol, password, isActive, // 
            true, /* account not expired */
            credentialsNonExpired, true, /* account not locked */
            authorities);

}