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:de.hybris.platform.acceleratorstorefrontcommons.security.StorefrontAuthenticationSuccessHandler.java

@Override
protected String determineTargetUrl(final HttpServletRequest request, final HttpServletResponse response) {
    String targetUrl = super.determineTargetUrl(request, response);
    if (CollectionUtils.isNotEmpty(getRestrictedPages())) {
        for (final String restrictedPage : getRestrictedPages()) {
            // When logging in from a restricted page, return user to default target url.
            if (targetUrl.contains(restrictedPage)) {
                targetUrl = super.getDefaultTargetUrl();
            }/*  w ww. j a  va  2 s .c om*/
        }
    }
    /*
     * If the cart has been merged and the user logging in through checkout, redirect to the cart page to display the
     * new cart
     */
    if (StringUtils.equals(targetUrl, CHECKOUT_URL)
            && BooleanUtils.toBoolean((Boolean) request.getAttribute(WebConstants.CART_MERGED))) {
        targetUrl = CART_URL;
    }

    return targetUrl;
}

From source file:com.tesora.dve.sql.CurrentTimestampDefaultValueTest.java

@Test
public void testSimpleQueriesForTimestampVariable() throws Throwable {

    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);

    int i = 0;/*from   w  w  w. j  ava  2  s.c  om*/
    for (Object[] objects : TimestampVariableTestUtils.getTestValues()) {
        String value = (String) objects[0];
        Boolean nullable = BooleanUtils.toBoolean((Integer) objects[1]);
        String defaultValue = (String) objects[2];
        Boolean onUpdate = BooleanUtils.toBoolean((Integer) objects[3]);
        Boolean expectedInsertTSVarSet = BooleanUtils.toBoolean((Integer) objects[4]);
        Boolean expectedUpdateTSVarSet = BooleanUtils.toBoolean((Integer) objects[5]);
        Boolean ignoreTest = BooleanUtils.toBoolean((Integer) objects[6]);

        if (ignoreTest) {
            continue;
        }

        String tableName = "ts" + i;

        String createTableSQL = TimestampVariableTestUtils.buildCreateTableSQL(tableName, nullable,
                defaultValue, onUpdate);
        String insertSQL = TimestampVariableTestUtils.buildInsertTestSQL(tableName, value, 1,
                Integer.toString(i));
        String updateSQL = TimestampVariableTestUtils.buildUpdateTestSQL(tableName, value, 1,
                Integer.toString(i) + Integer.toString(i));

        ++i;

        conn.execute(createTableSQL);

        long preTestTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());

        conn.execute(insertSQL);

        ResourceResponse resp = conn.fetch("select ts from " + tableName + " where id=1");
        List<ResultRow> rows = resp.getResults();
        assertEquals("Expected one row only", 1, rows.size());
        ResultColumn rc = rows.get(0).getResultColumn(1);
        if (expectedInsertTSVarSet) {
            // if we expected to set the timestamp variable then the ts column must contain the current time
            Timestamp ts = (Timestamp) (rc.getColumnValue());
            assertTrue("Inserted time must be >= starting time",
                    preTestTime <= TimeUnit.MILLISECONDS.toSeconds(ts.getTime()));
        } else {
            boolean isNull = rc.isNull();
            if (!isNull) {
                // ts column is not null so let's see if the column value was specified and if it was it should match the ts value
                Timestamp ts = (Timestamp) (rc.getColumnValue());
                if (StringUtils.contains(value, "2000-01-01 01:02:03")) {
                    assertTrue(TimeUnit.MILLISECONDS.toSeconds(ts.getTime()) == TimeUnit.MILLISECONDS
                            .toSeconds(formatter.parse("2000-01-01 01:02:03").getTime()));
                } else if (StringUtils.equals("0", value)) {
                    assertTrue(TimeUnit.MILLISECONDS.toSeconds(ts.getTime()) == TimeUnit.MILLISECONDS
                            .toSeconds(formatter.parse("0000-00-00 00:00:00").getTime()));
                } else if (StringUtils.equals("current_timestamp", value)) {
                    assertTrue("Inserted time must be >= starting time",
                            preTestTime <= TimeUnit.MILLISECONDS.toSeconds(ts.getTime()));
                } else {
                    // if we get here column value is not specified so figure out what default value we need
                    if (StringUtils.contains(defaultValue, "2000-01-01 01:02:03")) {
                        assertTrue(TimeUnit.MILLISECONDS.toSeconds(ts.getTime()) == TimeUnit.MILLISECONDS
                                .toSeconds(formatter.parse("2000-01-01 01:02:03").getTime()));
                    } else if (StringUtils.equals("0", defaultValue)) {
                        assertTrue(TimeUnit.MILLISECONDS.toSeconds(ts.getTime()) == TimeUnit.MILLISECONDS
                                .toSeconds(formatter.parse("0000-00-00 00:00:00").getTime()));
                    } else if (StringUtils.equals("current_timestamp", defaultValue)) {
                        assertTrue("Inserted time must be >= starting time",
                                preTestTime <= TimeUnit.MILLISECONDS.toSeconds(ts.getTime()));
                    }
                }
            } else {
                // column better be nullable
                assertTrue(nullable);
                if (StringUtils.isBlank(value)) {
                    // column not specified better validate the default value
                    assertTrue(StringUtils.equals("null", defaultValue) || StringUtils.isBlank(defaultValue));
                } else {
                    // column value was specified as null
                    assertEquals("null", value);
                }
            }
        }

        long updatePreTestTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());

        conn.execute(updateSQL);
        resp = conn.fetch("select ts from " + tableName + " where id=1");
        rows = resp.getResults();
        assertEquals("Expected one row only", 1, rows.size());
        rc = rows.get(0).getResultColumn(1);
        if (expectedUpdateTSVarSet) {
            // if we expected to set the timestamp variable then the ts column must contain the current time
            Timestamp ts = (Timestamp) (rc.getColumnValue());
            assertTrue("Update time must be >= starting time",
                    updatePreTestTime <= TimeUnit.MILLISECONDS.toSeconds(ts.getTime()));
        } else {
            boolean isNull = rc.isNull();
            if (!isNull) {
                // ts column is not null so let's see if the column value was specified and if it was it should match the ts value
                Timestamp ts = (Timestamp) (rc.getColumnValue());
                if (StringUtils.contains(value, "2000-01-01 01:02:03")) {
                    assertTrue(TimeUnit.MILLISECONDS.toSeconds(ts.getTime()) == TimeUnit.MILLISECONDS
                            .toSeconds(formatter.parse("2000-01-01 01:02:03").getTime()));
                } else if (StringUtils.equals("0", value)) {
                    assertTrue(TimeUnit.MILLISECONDS.toSeconds(ts.getTime()) == TimeUnit.MILLISECONDS
                            .toSeconds(formatter.parse("0000-00-00 00:00:00").getTime()));
                } else if (StringUtils.equals("current_timestamp", value)) {
                    assertTrue("Inserted time must be >= starting time",
                            preTestTime <= TimeUnit.MILLISECONDS.toSeconds(ts.getTime()));
                } else {
                    // if we get here column value is not specified so figure out what default value we need
                    if (StringUtils.contains(defaultValue, "2000-01-01 01:02:03")) {
                        assertTrue(TimeUnit.MILLISECONDS.toSeconds(ts.getTime()) == TimeUnit.MILLISECONDS
                                .toSeconds(formatter.parse("2000-01-01 01:02:03").getTime()));
                    } else if (StringUtils.equals("0", defaultValue)) {
                        assertTrue(TimeUnit.MILLISECONDS.toSeconds(ts.getTime()) == TimeUnit.MILLISECONDS
                                .toSeconds(formatter.parse("0000-00-00 00:00:00").getTime()));
                    } else if (StringUtils.equals("current_timestamp", defaultValue)) {
                        assertTrue("Inserted time must be >= starting time",
                                preTestTime <= TimeUnit.MILLISECONDS.toSeconds(ts.getTime()));
                    }
                }
            } else {
                // column better be nullable
                assertTrue(nullable);
                if (StringUtils.isBlank(value)) {
                    // column not specified better validate the default value
                    // note in one case the default is not specified and no value was specified for the column
                    // then the column value is null so the blank default is ok
                    assertTrue(StringUtils.equals("null", defaultValue) || StringUtils.isBlank(defaultValue));
                } else {
                    // column value was specified as null
                    assertEquals("null", value);
                }
            }
        }

    }
}

From source file:gr.abiss.calipso.controller.AbstractServiceBasedRestController.java

/**
 * Find all resources matching the given criteria and return a paginated
 * collection<br/>//w  w w .  j a v a 2s.  c  om
 * REST webservice published : GET
 * /search?page=0&size=20&properties=sortPropertyName&direction=asc
 * 
 * @param page
 *            Page number starting from 0 (default)
 * @param size
 *            Number of resources by pages. default to 10
 * @return OK http status code if the request has been correctly processed,
 *         with the a paginated collection of all resource enclosed in the
 *         body.
 */
@Override
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
//@ApiOperation(value = "find (paginated)", notes = "Find all resources matching the given criteria and return a paginated collection", httpMethod = "GET") 
public Page<T> findPaginated(@RequestParam(value = "page", required = false, defaultValue = "0") Integer page,
        @RequestParam(value = "size", required = false, defaultValue = "10") Integer size,
        @RequestParam(value = "properties", required = false, defaultValue = "id") String sort,
        @RequestParam(value = "direction", required = false, defaultValue = "ASC") String direction) {
    boolean applyCurrentPrincipalIdPredicate = true;

    if (BooleanUtils.toBoolean(request.getParameter("skipCurrentPrincipalIdPredicate"))) {
        applyCurrentPrincipalIdPredicate = false;
        LOGGER.debug("Skipping CurrentPrincipalIdPredicate");
    }

    return findPaginated(page, size, sort, direction, request.getParameterMap(),
            applyCurrentPrincipalIdPredicate);
}

From source file:com.redhat.winddrop.mdb.WindupExecutionQueueMDB.java

/**
 * Configures and executes Windup./*from  w w w. j  a  v a  2 s . c o m*/
 * 
 * @param packageSignature
 * @param windupInputFile
 * @param windupOutputDirectory
 * @throws IOException
 */
protected void executeWindup(String packageSignature, File windupInputFile, File windupOutputDirectory)
        throws IOException {

    // Map the environment settings from the input arguments.
    WindupEnvironment settings = new WindupEnvironment();
    settings.setPackageSignature(packageSignature);
    // settings.setExcludeSignature("excludePkgs");
    // settings.setTargetPlatform("targetPlatform");
    settings.setFetchRemote("false");

    boolean isSource = false;
    if (BooleanUtils.toBoolean("source")) {
        isSource = true;
    }
    settings.setSource(isSource);

    boolean captureLog = false;
    if (BooleanUtils.toBoolean("captureLog")) {
        captureLog = true;
    }

    String logLevel = StringUtils.trim("logLevel");
    settings.setCaptureLog(captureLog);
    settings.setLogLevel(logLevel);

    LOG.info("captureLog " + captureLog);
    LOG.info("logLevel " + logLevel);
    LOG.info("isSource " + isSource);

    // Run Windup
    new ReportEngine(settings).process(windupInputFile, windupOutputDirectory);

}

From source file:info.magnolia.cms.core.ie.XmlImport.java

private void setPropertyValue(NodeData nodeData, int type, String value)
        throws AccessDeniedException, RepositoryException {
    switch (type) {
    case PropertyType.STRING:
        nodeData.setValue(value);//  w w  w  .  ja va 2s . co  m
        break;
    case PropertyType.LONG:
        nodeData.setValue((new Long(value)).longValue());
        break;
    case PropertyType.DOUBLE:
        nodeData.setValue((new Double(value)).doubleValue());
        break;
    case PropertyType.DATE:
        // todo
        String dateFormat = (String) this.getParameter(DATE_FORMAT);
        if (StringUtils.isEmpty(dateFormat)) {
            dateFormat = DEFAULT_DATE_FORMAT;
        }
        SimpleDateFormat simpleFormat = new SimpleDateFormat(dateFormat);
        try {
            Date date = simpleFormat.parse(value);
            Calendar cal = new GregorianCalendar();
            cal.setTime(date);
            nodeData.setValue(cal);
        } catch (ParseException e) {
            log.error("Failed to parse date with the given format " + dateFormat, e); //$NON-NLS-1$
        }
        break;
    case PropertyType.BOOLEAN:
        nodeData.setValue(BooleanUtils.toBoolean(value));
        break;
    case PropertyType.BINARY:
        nodeData.setValue(new ByteArrayInputStream(Base64.decodeBase64(value.getBytes())));
        break;
    case PropertyType.REFERENCE:
        /**
         * this property must exist before of the same type as REFERENCE
         */
        nodeData.setValue(value);
    }
}

From source file:info.magnolia.cms.beans.config.ContentRepository.java

/**
 * Load repository mappings and params using repositories.xml
 * @throws Exception/*from  w w  w. j  a  v a 2  s  . c  om*/
 */
private static void loadRepositories() throws Exception {
    Document document = buildDocument();
    Element root = document.getRootElement();
    loadRepositoryNameMap(root);
    Collection repositoryElements = root.getChildren(ContentRepository.ELEMENT_REPOSITORY);
    Iterator children = repositoryElements.iterator();
    while (children.hasNext()) {
        Element element = (Element) children.next();
        String name = element.getAttributeValue(ATTRIBUTE_NAME);
        String load = element.getAttributeValue(ATTRIBUTE_LOAD_ON_STARTUP);
        String provider = element.getAttributeValue(ATTRIBUTE_PROVIDER);
        RepositoryMapping map = new RepositoryMapping();
        map.setName(name);
        map.setProvider(provider);
        boolean loadOnStartup = BooleanUtils.toBoolean(load);
        map.setLoadOnStartup(loadOnStartup);
        /* load repository parameters */
        Iterator params = element.getChildren(ELEMENT_PARAM).iterator();
        Map parameters = new Hashtable();
        while (params.hasNext()) {
            Element param = (Element) params.next();
            parameters.put(param.getAttributeValue(ATTRIBUTE_NAME), param.getAttributeValue(ATTRIBUTE_VALUE));
        }
        map.setParameters(parameters);
        List workspaces = element.getChildren(ELEMENT_WORKSPACE);
        if (workspaces != null && !workspaces.isEmpty()) {
            Iterator wspIterator = workspaces.iterator();
            while (wspIterator.hasNext()) {
                Element workspace = (Element) wspIterator.next();
                String wspName = workspace.getAttributeValue(ATTRIBUTE_NAME);
                log.info("Loading workspace:" + wspName);
                map.addWorkspace(wspName);
            }
        } else {
            map.addWorkspace(DEFAULT_WORKSPACE);
        }
        ContentRepository.repositoryMapping.put(name, map);
        try {
            loadRepository(map);
        } catch (Exception e) {
            log.error("System : Failed to load JCR \"" + map.getName() + "\" " + e.getMessage(), e); //$NON-NLS-1$ //$NON-NLS-2$
        }
    }
}

From source file:com.redhat.rhn.frontend.action.kickstart.SystemDetailsEditAction.java

private void transferFlagEdits(DynaActionForm form, SystemDetailsCommand command) {
    command.enableConfigManagement(BooleanUtils.toBoolean(form.getString("configManagement")));
    command.enableRemoteCommands(BooleanUtils.toBoolean(form.getString("remoteCommands")));

}

From source file:com.ibm.jaql.lang.Jaql.java

public void setProperty(String name, String value) {
    if (name.equalsIgnoreCase("enableRewrite")) {
        doRewrite = BooleanUtils.toBoolean(value);
    } else if (name.equalsIgnoreCase("stopOnException")) {
        stopOnException = BooleanUtils.toBoolean(value);
    } else if (name.equalsIgnoreCase("JaqlPrinter")) {
        try {/*  w w  w . ja  v  a 2  s . co m*/
            printer = (JaqlPrinter) Class.forName(value).newInstance();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

From source file:mitm.application.djigzo.james.mailets.SMIMESign.java

@Override
final public void initMailet() {
    getLogger().info("Initializing mailet: " + getMailetName());

    String param = getInitParameter(Parameter.ALGORITHM.name);

    if (param != null) {
        signingAlgorithm = SMIMESigningAlgorithm.fromName(param);

        if (signingAlgorithm == null) {
            throw new IllegalArgumentException(param + " is not a valid signing algorithm.");
        }/*from  ww  w. j  av  a2  s.com*/
    }

    signingAlgorithmAttribute = getInitParameter(Parameter.ALGORITHM_ATTRIBUTE.name);

    param = getInitParameter(Parameter.SIGN_MODE.name);

    if (param != null) {
        signMode = SMIMESignMode.fromName(param);

        if (signMode == null) {
            throw new IllegalArgumentException(param + " is not a valid SMIME sign mode.");
        }
    }

    param = getInitParameter(Parameter.ADD_ROOT.name);

    if (param != null) {
        addRoot = BooleanUtils.toBoolean(param);
    }

    param = getInitParameter(Parameter.RETAIN_MESSAGE_ID.name);

    if (param != null) {
        retainMessageID = BooleanUtils.toBoolean(param);
    }

    param = getInitParameter(Parameter.USE_DEPRECATED_CONTENT_TYPES.name);

    if (param != null) {
        useDeprecatedContentTypes = BooleanUtils.toBoolean(param);
    }

    initProtectedHeaders();

    StrBuilder sb = new StrBuilder();

    sb.append("Signing algorithm: ");
    sb.append(signingAlgorithm);
    sb.appendSeparator("; ");
    sb.append("Algorithm attribute: ");
    sb.append(signingAlgorithmAttribute);
    sb.appendSeparator("; ");
    sb.append("Sign mode: ");
    sb.append(signMode);
    sb.appendSeparator("; ");
    sb.append("Add root: ");
    sb.append(addRoot);
    sb.appendSeparator("; ");
    sb.append("Use deprecated content-type's: ");
    sb.append(useDeprecatedContentTypes);
    sb.appendSeparator("; ");
    sb.append("Retain Message-ID: ");
    sb.append(retainMessageID);
    sb.appendSeparator("; ");
    sb.append("Protected headers: ");
    sb.append(StringUtils.join(protectedHeaders, ","));

    getLogger().info(sb.toString());

    sessionManager = SystemServices.getSessionManager();

    actionExecutor = DatabaseActionExecutorBuilder.createDatabaseActionExecutor(sessionManager);

    assert (actionExecutor != null);

    messageOriginatorIdentifier = SystemServices.getMessageOriginatorIdentifier();

    userWorkflow = SystemServices.getUserWorkflow();

    certificatePathBuilderFactory = SystemServices.getCertificatePathBuilderFactory();
}

From source file:mitm.application.djigzo.james.mailets.SMIMEEncrypt.java

@Override
final public void initMailet() {
    getLogger().info("Initializing mailet: " + getMailetName());

    String param = getInitParameter(Parameter.ALGORITHM.name);

    if (param != null) {
        encryptionAlgorithm = SMIMEEncryptionAlgorithm.fromName(param);

        if (encryptionAlgorithm == null) {
            throw new IllegalArgumentException(param + " is not a valid encryption algorithm.");
        }/* w ww  . jav  a  2 s. co  m*/
    }

    encryptionAlgorithmAttribute = getInitParameter(Parameter.ALGORITHM_ATTRIBUTE.name);

    param = getInitParameter(Parameter.KEY_SIZE.name);

    if (param != null) {
        keySize = Integer.valueOf(param);

        if (keySize <= 0) {
            throw new IllegalArgumentException("KeySize must be > 0");
        }
    }

    param = getInitParameter(Parameter.RECIPIENT_MODE.name);

    if (param != null) {
        recipientMode = SMIMERecipientMode.fromName(param);

        if (recipientMode == null) {
            throw new IllegalArgumentException(recipientMode + " is not a valid SMIMERecipientMode.");
        }
    }

    param = getInitParameter(Parameter.USE_DEPRECATED_CONTENT_TYPES.name);

    if (param != null) {
        useDeprecatedContentTypes = BooleanUtils.toBoolean(param);
    }

    param = getInitParameter(Parameter.RETAIN_MESSAGE_ID.name);

    if (param != null) {
        retainMessageID = BooleanUtils.toBoolean(param);
    }

    initProtectedHeaders();

    StrBuilder sb = new StrBuilder();

    sb.append("Algorithm: ");
    sb.append(encryptionAlgorithm);
    sb.appendSeparator("; ");
    sb.append("Algorithm attribute: ");
    sb.append(encryptionAlgorithmAttribute);
    sb.appendSeparator("; ");
    sb.append("KeySize: ");
    sb.append(keySize);
    sb.appendSeparator("; ");
    sb.append("Recipient Mode: ");
    sb.append(recipientMode);
    sb.appendSeparator("; ");
    sb.append("Use deprecated content-type's: ");
    sb.append(useDeprecatedContentTypes);
    sb.appendSeparator("; ");
    sb.append("Retain Message-ID: ");
    sb.append(retainMessageID);
    sb.appendSeparator("; ");
    sb.append("Protected headers: ");
    sb.append(StringUtils.join(protectedHeaders, ","));

    getLogger().info(sb.toString());
}