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:au.org.emii.portal.composer.MapComposer.java

public void activateLink(String uri, String label, boolean isExternal, String downloadPid) {
    closeExternalContentWindow();//from w  w  w .j  a  v a2 s.c om

    Window externalContentWindow = (Window) Executions.createComponents("WEB-INF/zul/ExternalContent.zul",
            layerControls, null);

    if (isExternal) {
        // change browsers current location
        Clients.evalJavaScript("window.location.href ='" + uri + "';");
    } else {

        Iframe iframe = (Iframe) externalContentWindow.getFellow("externalContentIframe");
        Html html = (Html) externalContentWindow.getFellow("externalContentHTML");

        String newUri = uri;
        if (newUri.charAt(0) == '*') {
            //html content
            newUri = newUri.substring(1);

            //url
            iframe.setHeight("0px");
            iframe.setSrc("");

            String content;

            //is the use logged in ?
            boolean isLoggedIn = Util.isLoggedIn();

            if ("download".equalsIgnoreCase(label)) {

                String orgName = getSettingsSupplementary().getProperty("orgNameLong",
                        "Atlas of Living Australia");
                String termsOfUse = getSettingsSupplementary().getProperty("terms_of_use_url",
                        "http://www.ala.org.au/about-the-atlas/terms-of-use/#TOUusingcontent");
                String loginUrl = getSettingsSupplementary().getProperty("casServerLoginUrl",
                        "https://auth.ala.org.au/cas/login");
                boolean forceLogin = BooleanUtils
                        .toBoolean(getSettingsSupplementary().getProperty("force_login_downloads", "false"));

                if ((forceLogin && isLoggedIn) || (!forceLogin)) {

                    // Added fast download option -
                    // TODO refactor so this can be generated from same code that sets the downloadUrl (uri) in BiocacheQuery.java
                    String fastDownloadUrl = newUri.replaceFirst("/occurrences/download",
                            "/occurrences/index/download");

                    StringBuilder sbContent = new StringBuilder();
                    sbContent.append("<p id='termsOfUseDownload' style='padding:10px; margin-bottom: 0;'>");
                    sbContent.append("By downloading this content you are agreeing to use it in accordance ");
                    sbContent.append("with the ");
                    sbContent.append(orgName);
                    sbContent.append(" <a href='" + termsOfUse + "'>Terms of Use</a>");
                    sbContent.append(" and any Data Provider Terms associated with the data download. ");
                    sbContent.append("<br/><br/>");
                    sbContent.append("Please provide the following details before downloading (* required)");
                    sbContent.append("</p>");
                    sbContent.append(
                            "    <form id='downloadForm' onSubmit='downloadSubmitButtonClick(); return false;' style='padding:10px;'>");
                    sbContent.append("        <input type='hidden' name='url' id='downloadUrl' value='")
                            .append(uri).append("'/>");
                    sbContent.append("        <input type='hidden' name='url' id='fastDownloadUrl' value='")
                            .append(fastDownloadUrl).append("'/>");
                    sbContent.append("        <fieldset>");
                    sbContent.append("            <p><label for='email'>Email</label>");
                    sbContent.append("                <input type='text' name='email' id='email' value='"
                            + Util.getUserEmail() + "' size='100'  readonly='true' />");
                    sbContent.append("            </p>");
                    sbContent.append("            <p><label for='filename'>File Name</label>");
                    sbContent.append(
                            "                <input type='text' name='filename' id='filename' value='data' size='30'  />");
                    sbContent.append("            </p>");

                    sbContent.append(
                            "            <p><label for='reasonTypeId' style='vertical-align: top'>Download Reason *</label>");
                    sbContent.append("            <select name='reasonTypeId' id='reasonTypeId'>");
                    sbContent.append("            <option value=''>-- select a reason --</option>");
                    JSONArray dlreasons = CommonData.getDownloadReasons();
                    for (int i = 0; i < dlreasons.size(); i++) {
                        JSONObject dlr = (JSONObject) dlreasons.get(i);
                        sbContent.append("            <option value='")
                                .append((Long) dlr.get(StringConstants.ID)).append("'>")
                                .append(dlr.get(StringConstants.NAME)).append("</option>");
                    }
                    sbContent.append("            <select></p>");
                    sbContent.append(
                            "            <input style='display:none' type='radio' name='downloadType' value='fast' class='tooltip' checked='checked' title='Faster download but fewer fields are included'>");
                    sbContent.append("            <p><label for='acceptLicense'>Accept licencing *</label>");
                    sbContent.append(
                            "               <input type='checkbox' id='downloadConfirmLicense' name='downloadConfirmLicense'/> I understand and accept that any <a href='https://docs.nbnatlas.org/data-licenses/'>CC-BY-NC</a> licenced records included in the download must not be used for commercial purposes without the permission of the data provider and all data providers will be acknowledged as required. Breach of the licence conditions may result in you being issued with a <a href='https://docs.nbnatlas.org/data-licenses/breach-licence-conditions/'>fixed charge notice</a>.");
                    sbContent.append("            </p>");
                    sbContent.append("            <p style='clear:both;'>&nbsp;</p>");
                    sbContent.append(
                            "            <p style='text-align:center;'><input class='btn' type='submit' value='Download All Records' id='downloadSubmitButton'/></p>");

                    sbContent.append("        </fieldset>");
                    sbContent.append("    </form>");

                    content = sbContent.toString();
                } else {
                    content = "<p><h3>Please register or login to download data from " + orgName + ". </h3>"
                            + "The link below will open a new window to login or register. Please keep this window "
                            + "open  and redo the steps to export a point sample." + "</p>" + "<br/>"
                            + "<p><a target='_blank' class='btn' href='" + loginUrl + "'>Login</a></p>";
                }
            } else {
                content = newUri;
            }

            //content
            html.setContent(content);
            html.setStyle("overflow: scroll;padding: 0 10px;");

            //for the 'reset window' button
            ((ExternalContentComposer) externalContentWindow).setSrc("");

            //update linked button
            externalContentWindow.getFellow(StringConstants.BREAKOUT).setVisible(false);

            externalContentWindow.setContentStyle("overflow:auto");
        } else {
            //url
            iframe.setHeight("100%");
            iframe.setSrc(newUri);

            //content
            html.setContent("");

            //for the 'reset window' button
            ((ExternalContentComposer) externalContentWindow).setSrc(newUri);

            //update linked button
            ((Toolbarbutton) externalContentWindow.getFellow(StringConstants.BREAKOUT)).setHref(newUri);
            externalContentWindow.getFellow(StringConstants.BREAKOUT).setVisible(true);

            externalContentWindow.setContentStyle("overflow:visible");
        }

        if (StringUtils.isNotBlank(downloadPid)) {
            String downloadUrl = CommonData.getSatServer() + "/ws/download/" + downloadPid;
            if (downloadPid.startsWith("http")) {
                downloadUrl = downloadPid;
            }
            ((Toolbarbutton) externalContentWindow.getFellow("download")).setHref(downloadUrl);
            externalContentWindow.getFellow("download").setVisible(true);
        } else {
            ((Toolbarbutton) externalContentWindow.getFellow("download")).setHref("");
            externalContentWindow.getFellow("download").setVisible(false);
        }

        // use the link description as the popup caption
        ((Caption) externalContentWindow.getFellow("caption")).setLabel(label);
        externalContentWindow.setPosition("center");
        try {
            externalContentWindow.setParent(layerControls);
            externalContentWindow.doModal();
        } catch (Exception e) {
            LOGGER.error("error opening information popup", e);
        }
    }
}

From source file:info.magnolia.module.admininterface.SaveHandlerImpl.java

/**
 * Get the value for saving in jcr//from w  ww  . ja v  a  2  s .  c o  m
 * @param valueStr string representation of the value
 * @param type type of the value
 * @return the value
 */
public Value getValue(String valueStr, int type) {

    ValueFactory valueFactory = null;

    HierarchyManager hm = MgnlContext.getHierarchyManager(this.getRepository());
    try {
        valueFactory = hm.getWorkspace().getSession().getValueFactory();
    } catch (RepositoryException e) {
        throw new NestableRuntimeException(e);
    }

    Value value = null;
    if (type == PropertyType.STRING) {
        value = valueFactory.createValue(valueStr);
    } else if (type == PropertyType.BOOLEAN) {
        value = valueFactory.createValue(BooleanUtils.toBoolean(valueStr));
    } else if (type == PropertyType.DOUBLE) {
        try {
            value = valueFactory.createValue(Double.parseDouble(valueStr));
        } catch (NumberFormatException e) {
            value = valueFactory.createValue(0d);
        }
    } else if (type == PropertyType.LONG) {
        try {
            value = valueFactory.createValue(Long.parseLong(valueStr));
        } catch (NumberFormatException e) {
            value = valueFactory.createValue(0L);
        }
    } else if (type == PropertyType.DATE) {
        try {
            Calendar date = new GregorianCalendar();
            try {
                String newDateAndTime = valueStr;
                String[] dateAndTimeTokens = newDateAndTime.split("T"); //$NON-NLS-1$
                String newDate = dateAndTimeTokens[0];
                String[] dateTokens = newDate.split("-"); //$NON-NLS-1$
                int hour = 0;
                int minute = 0;
                int second = 0;
                int year = Integer.parseInt(dateTokens[0]);
                int month = Integer.parseInt(dateTokens[1]) - 1;
                int day = Integer.parseInt(dateTokens[2]);
                if (dateAndTimeTokens.length > 1) {
                    String newTime = dateAndTimeTokens[1];
                    String[] timeTokens = newTime.split(":"); //$NON-NLS-1$
                    hour = Integer.parseInt(timeTokens[0]);
                    minute = Integer.parseInt(timeTokens[1]);
                    second = Integer.parseInt(timeTokens[2]);
                }
                date.set(year, month, day, hour, minute, second);
                // this is used in the searching
                date.set(Calendar.MILLISECOND, 0);
                date.setTimeZone(TimeZone.getTimeZone("GMT"));
            }
            // todo time zone??
            catch (Exception e) {
                // ignore, it sets the current date / time
            }
            value = valueFactory.createValue(date);
        } catch (Exception e) {
            if (log.isDebugEnabled())
                log.debug("Exception caught: " + e.getMessage(), e); //$NON-NLS-1$
        }
    } else if (type == PropertyType.REFERENCE) {
        try {
            Node referencedNode = hm.getWorkspace().getSession().getNodeByUUID(valueStr);

            value = valueFactory.createValue(referencedNode);
        } catch (RepositoryException re) {
            if (log.isDebugEnabled())
                log.debug("Cannot retrieve the referenced node by UUID: " + valueStr, re);
        }
    }

    return value;
}

From source file:com.haulmont.ext.web.ui.Call.CallBrowser.java

private void initAfterSetLookup(boolean isLookup) {
    final User user = UserSessionClient.getUserSession().getCurrentOrSubstitutedUser();
    SplitPanel splitPanel = getComponent("split");
    splitPanel.setSplitPosition(100);//from  w ww . ja  v a2 s. c o  m
    splitPanel.setLocked(true);
    if (isLookup) {
        callTable.setMultiSelect(false);
    } else if (!isTemplate) {
        //            final HashMap<UUID, com.vaadin.ui.Component> statesMap = new HashMap<UUID, com.vaadin.ui.Component>();
        final CardService cardService = ServiceLocator.lookup(CardService.NAME);
        addLocStateColumn();

        resolutionsFrame = getComponent("resolutionsFrame");
        resolutionsFrame.init();

        cardTreeFrame = getComponent("cardTreeFrame");
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("card", null);
        cardTreeFrame.init(params);

        showResolutions = getComponent(HIDE_RESOLUTIONS);
        final SplitPanel split = getComponent("split");
        showResolutions.addListener(new ValueListener() {
            public void valueChanged(Object source, String property, Object prevValue, Object value) {
                boolean showResolutionsValue = BooleanUtils.isTrue((Boolean) value);
                int pos = (!showResolutionsValue ? 100 : 60);
                split.setSplitPosition(pos);
                split.setLocked(!showResolutionsValue);

                Card card = (Card) callTable.getSingleSelected();
                if (showResolutionsValue && card != null) {
                    String currentTab = tabsheet.getTab().getName();
                    if (currentTab.equals("resolutionsTab"))
                        resolutionsFrame.setCard(card);
                    if (currentTab.equals("hierarchyTab"))
                        cardTreeFrame.setCard(card);
                }
            }
        });

        String value = getSettings().get(HIDE_RESOLUTIONS).attributeValue("value");
        showResolutions.setValue(value == null ? false : BooleanUtils.toBoolean(value));
    } else {
        SplitPanel split = getComponent("split");
        split.setSplitPosition(100);
        split.setLocked(true);
    }
}

From source file:com.vmware.bdd.cli.commands.ClusterCommands.java

@CliCommand(value = "cluster create", help = "Create a new cluster")
public void createCluster(
        @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name,
        @CliOption(key = {// w  w w  .  j av a 2  s.  com
                "appManager" }, mandatory = false, help = "The application manager name") final String appManager,
        @CliOption(key = {
                "type" }, mandatory = false, help = "The cluster type is Hadoop or HBase") final String type,
        @CliOption(key = { "distro" }, mandatory = false, help = "The distro name") final String distro,
        @CliOption(key = {
                "specFile" }, mandatory = false, help = "The spec file name path") final String specFilePath,
        @CliOption(key = {
                "rpNames" }, mandatory = false, help = "Resource Pools for the cluster: use \",\" among names.") final String rpNames,
        @CliOption(key = {
                "dsNames" }, mandatory = false, help = "Datastores for the cluster: use \",\" among names.") final String dsNames,
        @CliOption(key = {
                "networkName" }, mandatory = false, help = "Network Name used for management") final String networkName,
        @CliOption(key = {
                "hdfsNetworkName" }, mandatory = false, help = "Network Name for HDFS traffic.") final String hdfsNetworkName,
        @CliOption(key = {
                "mapredNetworkName" }, mandatory = false, help = "Network Name for MapReduce traffic") final String mapredNetworkName,
        @CliOption(key = {
                "topology" }, mandatory = false, help = "You must specify the topology type: HVE or RACK_AS_RACK or HOST_AS_RACK") final String topology,
        @CliOption(key = {
                "resume" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "flag to resume cluster creation") final boolean resume,
        @CliOption(key = {
                "skipConfigValidation" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Skip cluster configuration validation. ") final boolean skipConfigValidation,
        @CliOption(key = {
                "yes" }, mandatory = false, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = "Answer 'yes' to all Y/N questions. ") final boolean alwaysAnswerYes,
        @CliOption(key = {
                "password" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "Answer 'yes' to set password for all VMs in this cluster.") final boolean setClusterPassword,
        @CliOption(key = {
                "localRepoURL" }, mandatory = false, help = "Local yum server URL for application managers, ClouderaManager/Ambari.") final String localRepoURL,
        @CliOption(key = {
                "adminGroupName" }, mandatory = false, help = "AD/LDAP Admin Group Name.") final String adminGroupName,
        @CliOption(key = {
                "userGroupName" }, mandatory = false, help = "AD/LDAP User Group Name.") final String userGroupName,
        @CliOption(key = {
                "disableLocalUsers" }, mandatory = false, help = "Disable local users") final Boolean disableLocalUsersFlag,
        @CliOption(key = {
                "skipVcRefresh" }, mandatory = false, help = "flag to skip refreshing VC resources") final Boolean skipVcRefresh,
        @CliOption(key = {
                "template" }, mandatory = false, help = "The node template name") final String templateName) {
    // validate the name
    if (name.indexOf("-") != -1) {
        CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE,
                Constants.OUTPUT_OP_RESULT_FAIL,
                Constants.PARAM_CLUSTER + Constants.PARAM_NOT_CONTAIN_HORIZONTAL_LINE);
        return;
    } else if (name.indexOf(" ") != -1) {
        CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE,
                Constants.OUTPUT_OP_RESULT_FAIL,
                Constants.PARAM_CLUSTER + Constants.PARAM_NOT_CONTAIN_BLANK_SPACE);
        return;
    }

    // process resume
    if (resume && setClusterPassword) {
        CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE,
                Constants.OUTPUT_OP_RESULT_FAIL, Constants.RESUME_DONOT_NEED_SET_PASSWORD);
        return;
    } else if (resume) {
        resumeCreateCluster(name, skipVcRefresh);
        return;
    }

    // build ClusterCreate object
    ClusterCreate clusterCreate = new ClusterCreate();
    clusterCreate.setName(name);

    if (!CommandsUtils.isBlank(appManager) && !Constants.IRONFAN.equalsIgnoreCase(appManager)) {
        AppManagerRead appManagerRead = appManagerRestClient.get(appManager);
        if (appManagerRead == null) {
            CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE,
                    Constants.OUTPUT_OP_RESULT_FAIL,
                    appManager + " cannot be found in the list of application managers.");
            return;
        }
    }

    if (CommandsUtils.isBlank(appManager)) {
        clusterCreate.setAppManager(Constants.IRONFAN);
    } else {
        clusterCreate.setAppManager(appManager);
        // local yum repo url for 3rd party app managers like ClouderaMgr, Ambari etc.
        if (!CommandsUtils.isBlank(localRepoURL)) {
            clusterCreate.setLocalRepoURL(localRepoURL);
        }
    }

    if (setClusterPassword) {
        String password = getPassword();
        //user would like to set password, but failed to enter
        //a valid one, quit cluster create
        if (password == null) {
            return;
        } else {
            clusterCreate.setPassword(password);
        }
    }

    if (type != null) {
        ClusterType clusterType = ClusterType.getByDescription(type);
        if (clusterType == null) {
            CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE,
                    Constants.OUTPUT_OP_RESULT_FAIL, Constants.INVALID_VALUE + " " + "type=" + type);
            return;
        }
        clusterCreate.setType(clusterType);
    } else if (specFilePath == null) {
        // create Hadoop (HDFS + MapReduce) cluster as default
        clusterCreate.setType(ClusterType.HDFS_MAPRED);
    }

    TopologyType policy = null;
    if (topology != null) {
        policy = validateTopologyValue(name, topology);
        if (policy == null) {
            return;
        }
    } else {
        policy = TopologyType.NONE;
    }
    clusterCreate.setTopologyPolicy(policy);

    DistroRead distroRead4Create;
    try {
        if (distro != null) {
            DistroRead[] distroReads = appManagerRestClient.getDistros(clusterCreate.getAppManager());
            distroRead4Create = getDistroByName(distroReads, distro);

            if (distroRead4Create == null) {
                CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE,
                        Constants.OUTPUT_OP_RESULT_FAIL,
                        Constants.PARAM_DISTRO + Constants.PARAM_NOT_SUPPORTED + getDistroNames(distroReads));
                return;
            }
        } else {
            distroRead4Create = appManagerRestClient.getDefaultDistro(clusterCreate.getAppManager());
            if (distroRead4Create == null || CommandsUtils.isBlank(distroRead4Create.getName())) {
                CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE,
                        Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_NO_DEFAULT_DISTRO);
                return;
            }
        }
    } catch (CliRestException e) {
        CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE,
                Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
        return;
    }

    Map<String, Map<String, String>> infraConfigs = new HashMap<String, Map<String, String>>();

    if (StringUtils.isBlank(adminGroupName) && StringUtils.isBlank(userGroupName)) {
        //both adminGroupName and userGroupName are null, supposes no need to enable ldap.
    } else if (!StringUtils.isBlank(adminGroupName) && !StringUtils.isBlank(userGroupName)) {
        if (MapUtils.isEmpty(infraConfigs.get(UserMgmtConstants.LDAP_USER_MANAGEMENT))) {
            initInfraConfigs(infraConfigs, disableLocalUsersFlag);
        }
        Map<String, String> userMgmtConfig = infraConfigs.get(UserMgmtConstants.LDAP_USER_MANAGEMENT);
        userMgmtConfig.put(UserMgmtConstants.ADMIN_GROUP_NAME, adminGroupName);
        userMgmtConfig.put(UserMgmtConstants.USER_GROUP_NAME, userGroupName);
        clusterCreate.setInfrastructure_config(infraConfigs);
    } else {
        CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE,
                Constants.OUTPUT_OP_RESULT_FAIL, "You need to supply both AdminGroupName and UserGroupName.");
        return;
    }

    clusterCreate.setDistro(distroRead4Create.getName());
    clusterCreate.setDistroVendor(distroRead4Create.getVendor());
    clusterCreate.setDistroVersion(distroRead4Create.getVersion());

    clusterCreate.setTemplateName(templateName);

    if (rpNames != null) {
        List<String> rpNamesList = CommandsUtils.inputsConvert(rpNames);
        if (rpNamesList.isEmpty()) {
            CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE,
                    Constants.OUTPUT_OP_RESULT_FAIL,
                    Constants.INPUT_RPNAMES_PARAM + Constants.MULTI_INPUTS_CHECK);
            return;
        } else {
            clusterCreate.setRpNames(rpNamesList);
        }
    }
    if (dsNames != null) {
        List<String> dsNamesList = CommandsUtils.inputsConvert(dsNames);
        if (dsNamesList.isEmpty()) {
            CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE,
                    Constants.OUTPUT_OP_RESULT_FAIL,
                    Constants.INPUT_DSNAMES_PARAM + Constants.MULTI_INPUTS_CHECK);
            return;
        } else {
            clusterCreate.setDsNames(dsNamesList);
        }
    }
    List<String> failedMsgList = new ArrayList<String>();
    List<String> warningMsgList = new ArrayList<String>();
    Set<String> allNetworkNames = new HashSet<String>();
    try {
        if (specFilePath != null) {
            ClusterCreate clusterSpec = CommandsUtils.getObjectByJsonString(ClusterCreate.class,
                    CommandsUtils.dataFromFile(specFilePath));
            clusterCreate.setSpecFile(true);
            clusterCreate.setExternalHDFS(clusterSpec.getExternalHDFS());
            clusterCreate.setExternalMapReduce(clusterSpec.getExternalMapReduce());
            clusterCreate.setExternalNamenode(clusterSpec.getExternalNamenode());
            clusterCreate.setExternalSecondaryNamenode(clusterSpec.getExternalSecondaryNamenode());
            clusterCreate.setExternalDatanodes(clusterSpec.getExternalDatanodes());
            clusterCreate.setNodeGroups(clusterSpec.getNodeGroups());
            clusterCreate.setConfiguration(clusterSpec.getConfiguration());
            // TODO: W'd better merge validateConfiguration with validateClusterSpec to avoid repeated validation.
            if (CommandsUtils.isBlank(appManager) || Constants.IRONFAN.equalsIgnoreCase(appManager)) {
                validateConfiguration(clusterCreate, skipConfigValidation, warningMsgList, failedMsgList);
            }
            clusterCreate.validateNodeGroupNames();
            if (!validateHAInfo(clusterCreate.getNodeGroups())) {
                CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE,
                        Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_CLUSTER_SPEC_HA_ERROR + specFilePath);
                return;
            }

            Map<String, Map<String, String>> specInfraConfigs = clusterSpec.getInfrastructure_config();
            if (!MapUtils.isEmpty(specInfraConfigs)) //spec infra config is not empty
            {
                if (MapUtils.isNotEmpty(infraConfigs)) {
                    System.out.println(
                            "adminGroup and userGroup has been specified as commandline parameters, so the values inside spec file will be ignored.");
                } else {
                    clusterCreate.setInfrastructure_config(specInfraConfigs);
                }
            }
            Map<String, Object> configuration = clusterSpec.getConfiguration();
            if (MapUtils.isNotEmpty(configuration)) {
                Map<String, Map<String, String>> serviceUserConfig = (Map<String, Map<String, String>>) configuration
                        .get(UserMgmtConstants.SERVICE_USER_CONFIG_IN_SPEC_FILE);
                if (MapUtils.isNotEmpty(serviceUserConfig)) {
                    //user didn't specify ldap in command line and specfile, but specfiy ldap user in service user
                    if (hasLdapServiceUser(serviceUserConfig)
                            && (clusterCreate.getInfrastructure_config() == null)) {
                        Map<String, Map<String, String>> infraConfig = new HashMap<>();
                        initInfraConfigs(infraConfig, disableLocalUsersFlag);
                        clusterCreate.setInfrastructure_config(infraConfig);
                    }
                    validateServiceUserConfigs(appManager, clusterSpec, failedMsgList);
                }
            }

        }
        allNetworkNames = getAllNetworkNames();
    } catch (Exception e) {
        CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE,
                Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
        return;
    }

    if (allNetworkNames.isEmpty()) {
        CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE,
                Constants.OUTPUT_OP_RESULT_FAIL, Constants.PARAM_CANNOT_FIND_NETWORK);
        return;
    }

    LinkedHashMap<NetTrafficType, List<String>> networkConfig = new LinkedHashMap<NetTrafficType, List<String>>();
    if (networkName == null) {
        if (allNetworkNames.size() == 1) {
            networkConfig.put(NetTrafficType.MGT_NETWORK, new ArrayList<String>());
            networkConfig.get(NetTrafficType.MGT_NETWORK).addAll(allNetworkNames);
        } else {
            CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE,
                    Constants.OUTPUT_OP_RESULT_FAIL,
                    Constants.PARAM_NETWORK_NAME + Constants.PARAM_NOT_SPECIFIED);
            return;
        }
    } else {
        if (!allNetworkNames.contains(networkName)
                || (hdfsNetworkName != null && !allNetworkNames.contains(hdfsNetworkName))
                || (mapredNetworkName != null && !allNetworkNames.contains(mapredNetworkName))) {
            CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE,
                    Constants.OUTPUT_OP_RESULT_FAIL,
                    Constants.PARAM_NETWORK_NAME + Constants.PARAM_NOT_SUPPORTED + allNetworkNames.toString());
            return;
        }

        networkConfig.put(NetTrafficType.MGT_NETWORK, new ArrayList<String>());
        networkConfig.get(NetTrafficType.MGT_NETWORK).add(networkName);

        if (hdfsNetworkName != null) {
            networkConfig.put(NetTrafficType.HDFS_NETWORK, new ArrayList<String>());
            networkConfig.get(NetTrafficType.HDFS_NETWORK).add(hdfsNetworkName);
        }

        if (mapredNetworkName != null) {
            networkConfig.put(NetTrafficType.MAPRED_NETWORK, new ArrayList<String>());
            networkConfig.get(NetTrafficType.MAPRED_NETWORK).add(mapredNetworkName);
        }
    }
    notifyNetsUsage(networkConfig, warningMsgList);
    clusterCreate.setNetworkConfig(networkConfig);

    clusterCreate.validateCDHVersion(warningMsgList);

    // Validate that the specified file is correct json format and proper value.
    //TODO(qjin): 1, in validateClusterCreate, implement roles check and validation
    //            2, consider use service to validate configuration for different appManager
    if (specFilePath != null) {
        validateClusterSpec(clusterCreate, failedMsgList, warningMsgList);
    }

    // give a warning message if both type and specFilePath are specified
    if (type != null && specFilePath != null) {
        warningMsgList.add(Constants.TYPE_SPECFILE_CONFLICT);
    }

    if (!failedMsgList.isEmpty()) {
        showFailedMsg(clusterCreate.getName(), Constants.OUTPUT_OP_CREATE, failedMsgList);
        return;
    }

    // rest invocation
    try {
        if (!CommandsUtils.showWarningMsg(clusterCreate.getName(), Constants.OUTPUT_OBJECT_CLUSTER,
                Constants.OUTPUT_OP_CREATE, warningMsgList, alwaysAnswerYes, null)) {
            return;
        }
        restClient.create(clusterCreate, BooleanUtils.toBoolean(skipVcRefresh));
        CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_RESULT_CREAT);
    } catch (CliRestException e) {
        CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_CREATE,
                Constants.OUTPUT_OP_RESULT_FAIL, CommandsUtils.getExceptionMessage(e));
        return;
    }

    // check the instant clone type and the HA configuration for node groups
    // currently there are limitations on HA support with instant clone, so we will
    // display a warning message for instant clone with HA function
    ClusterRead cluster = restClient.get(name, false);
    if (cluster != null) {
        String cloneType = cluster.getClusterCloneType();
        String INSTANT_CLONE = com.vmware.bdd.utils.Constants.CLUSTER_CLONE_TYPE_INSTANT_CLONE;
        if (null != cloneType && cloneType.equals(INSTANT_CLONE)) {
            String warningMsg = validateInstantCloneWithHA(specFilePath, clusterCreate);
            if (!CommonUtil.isBlank(warningMsg)) {
                System.out.println(warningMsg);
            }
        }
    }
}

From source file:com.wineaccess.winerypermit.WineryPermitHelper.java

private static void validatePermit(List<PermitModel> permit, String wineryId) {
    Map<String, String> permitNumberPOMap = new ConcurrentHashMap<String, String>();
    Set<String> dtcPermitNumberSet = new HashSet<String>();
    /*Map<String,String> permitNumberDOMap = new ConcurrentHashMap<String,String>();
    Set<String> dtcPermitNumberSetDB = new HashSet<String>();*/
    if (permit == null || permit.isEmpty()) {
        response.addError(new WineaccessError(SystemErrorCode.PERMIT_NO_SELECTED_ALT_STATES_ERROR,
                SystemErrorCode.PERMIT_NO_SELECTED_ALT_STATES_ERROR_TEXT));
    } else {//w  ww . j av a2  s  .  c  o  m

        Boolean isValidWineryPermit = false;
        for (PermitModel permitModel : permit) {
            String permitdurationInMonths = permitModel.getPermitDurationInMonths();
            Date permitStartDate = permitModel.getDtcPermitStartDate();
            Date permitEndDate = permitModel.getDtcPermitEndDate();
            String dtcPermitNumber = permitModel.getDtcPermitNumber();
            Long masterDataId = (StringUtils.isNotBlank(permitModel.getMasterDataId()))
                    ? Long.parseLong(permitModel.getMasterDataId())
                    : null;
            if (masterDataId == null) {
                response.addError(new WineaccessError(SystemErrorCode.NO_WINERY_PERMITS_ERROR,
                        SystemErrorCode.NO_WINERY_PERMITS_ERROR_TEXT));

            } else {
                MasterData masterData = MasterDataRepository.getMasterDataById(masterDataId);
                if (masterData == null || !masterData.getMasterDataType().getName()
                        .equals(MasterDataTypeEnum.WineryLicencePermit.name())) {
                    response.addError(new WineaccessError(SystemErrorCode.PERMIT_INVALID_MASTER_DATA,
                            SystemErrorCode.PERMIT_INVALID_MASTER_DATA_TEXT));

                }

            }

            if (StringUtils.isNotBlank(dtcPermitNumber) && StringUtils.isNotBlank(permitdurationInMonths)
                    && BooleanUtils.toBoolean(permitModel.getIsSelected())) {
                isValidWineryPermit = true;

            }
            if (StringUtils.isNotBlank(permitdurationInMonths) && permitStartDate != null
                    && permitEndDate != null) {
                Integer diff = getMonthsDifference(permitStartDate, permitEndDate);
                if (Integer.parseInt(permitdurationInMonths) != diff) {
                    response.addError(new WineaccessError(SystemErrorCode.PERMIT_INVALID_DURATION,
                            SystemErrorCode.PERMIT_INVALID_DURATION_TEXT));

                }
            }
            if (StringUtils.isNotBlank(dtcPermitNumber) && permitModel.getMasterDataId() != null) {
                permitNumberPOMap.put(permitModel.getMasterDataId(), dtcPermitNumber);
                dtcPermitNumberSet.add(dtcPermitNumber);
            }

        }
        if (!permitNumberPOMap.isEmpty()) {
            //Set<String> dtcPermitNumberSet = permitNumberPOMap.

            if (dtcPermitNumberSet.size() != permitNumberPOMap.size()) {
                response.addError(new WineaccessError(SystemErrorCode.PERMIT_DUPLICATE_DTC_PERMIT_NUMBER,
                        SystemErrorCode.PERMIT_DUPLICATE_DTC_PERMIT_NUMBER_TEXT));
            }
            /*else{
                List<Object[]> dtcPermitNumberFromDB = WineryPermitRepository.findDTCPermitNumberByWineryId(Long.valueOf(wineryId));
                if(dtcPermitNumberFromDB!=null && !dtcPermitNumberFromDB.isEmpty()){
               for(Object[] obj:dtcPermitNumberFromDB){
                   permitNumberDOMap.put((String)obj[0], (String)obj[1]);
                   dtcPermitNumberSetDB.add((String)obj[1]);
               }
                }
                    
                    
                if(dtcPermitNumberSetDB!=null && !dtcPermitNumberSetDB.isEmpty()){
               for(String DTCPermitNumber:dtcPermitNumberSetDB)
               {
                   if(Collections.frequency(permitNumberPOMap, DTCPermitNumber)!=0)
                   {
                  response.addError(new WineaccessError(SystemErrorCode.PERMIT_DUPLICATE_DTC_PERMIT_NUMBER,SystemErrorCode.PERMIT_DUPLICATE_DTC_PERMIT_NUMBER_TEXT));
                   }
               }
                }
            }*/
        }

        if (!isValidWineryPermit) {
            response.addError(new WineaccessError(SystemErrorCode.PERMIT_INVALID_PERMIT_DURATION,
                    SystemErrorCode.PERMIT_INVALID_PERMIT_DURATION_TEXT));
        }
    }
}

From source file:com.wineaccess.winepermit.WinePermitHelper.java

private static void populateNoPermitData(WinePermitPO winePermitPO, WineModel wineModel) {
    Boolean optionSelectedNoPermit = BooleanUtils
            .toBooleanObject(winePermitPO.getSellInAltStates().getIsSelectedNoPermit());
    Map<Long, Long> noPermitIdsMap = new ConcurrentHashMap<Long, Long>();
    List<Object[]> noPermitIdsList = WinePermitRepository.findWineNoPermitIdByWineId(wineModel.getId());
    for (Object[] ids : noPermitIdsList) {
        noPermitIdsMap.put((Long) ids[0], (Long) ids[1]);
    }/*from w w w. j  a  va  2 s .  co m*/

    List<OptionSelectedNoPermit> noPermitList = winePermitPO.getSellInAltStates().getOptionSelectedNoPermit();
    if (CollectionUtils.isNotEmpty(noPermitList)) {

        for (OptionSelectedNoPermit noPermitModel : noPermitList) {
            WineLicenseNoPermit wineLicenseNoPermit = new WineLicenseNoPermit();
            Long masterDataId = Long.valueOf(noPermitModel.getMasterDataId());
            wineLicenseNoPermit.setWineNoPermit(MasterDataRepository.getMasterDataById(masterDataId));
            wineLicenseNoPermit.setProductId(wineModel);
            wineLicenseNoPermit.setId(noPermitIdsMap.get(masterDataId));
            if (BooleanUtils.isTrue(optionSelectedNoPermit)) {
                wineModel.setOptionSelectedAltstates(
                        EnumTypes.OptionSelectedAltStatesEnum.NO_PERMIT_FOR_ALT_STATES
                                .getOptionSelectedaltStates());
                wineLicenseNoPermit.setIsSelected(BooleanUtils.toBoolean(noPermitModel.getIsSelected()));
                wineLicenseNoPermit.setPriceFiled(noPermitModel.getNoPermitdate());
                wineLicenseNoPermit.setStatus(noPermitModel.getSc3TStatus());
            } else {
                wineLicenseNoPermit.setIsSelected(false);
                wineLicenseNoPermit.setPriceFiled(null);
                wineLicenseNoPermit.setStatus(null);
            }

            WinePermitRepository.saveWineLicenseNoPermit(wineLicenseNoPermit);

        }
    }
}

From source file:com.edgenius.wiki.webapp.servlet.InstallServlet.java

private void createDatabase(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    boolean confirmed = BooleanUtils.toBoolean(request.getParameter("confirmed"));
    String dbType = request.getParameter("dbType");
    String rootUser = request.getParameter("rootUser");
    String rootpass = request.getParameter("rootPassword");
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    String dbname = request.getParameter("dbname");
    String dbSchema = request.getParameter("dbschema");
    String host = request.getParameter("host");
    String adminDBUrl = request.getParameter("adminDBUrl");
    boolean urlEdited = BooleanUtils.toBoolean(request.getParameter("urlEdited"));

    //echo back value
    request.setAttribute("dbType", dbType);
    request.setAttribute("rootUser", rootUser);
    request.setAttribute("rootPassword", rootpass);
    request.setAttribute("host", host);
    request.setAttribute("dbname", dbname);
    request.setAttribute("dbschema", dbSchema);
    request.setAttribute("adminDBUrl", adminDBUrl);
    request.setAttribute("username", username);
    request.setAttribute("password", password);
    request.setAttribute("urlEdited", urlEdited);

    if (Server.DBTYPE_MYSQL.equalsIgnoreCase(dbType)) {
        DBLoader loader = new DBLoader();
        ConnectionProxy con = null;//  ww  w . j  a v  a  2 s.  co  m
        try {
            log.info("Creating DB {} for user {}", dbname, username);
            if (confirmed || !loader.isDBExist(dbType, host, dbname, dbSchema, rootUser, rootpass)) {
                if (!urlEdited) {
                    adminDBUrl = loader.getURL(dbType, null, host, dbname, true);
                }
                con = loader.getConnection(dbType, adminDBUrl, dbSchema, rootUser, rootpass);
                log.info("DB {} is going to create or reset", dbname);
                //at moment, only MySQL allows to create DB, and its schema is null.
                loader.resetDB(dbType, con, dbname, username, password);

                //into session and file if current server is not jndi...
                Server server = (Server) request.getSession().getAttribute("server");
                if (StringUtils.isBlank(server.getDbJNDI())) {
                    updateServerPropertiesJDBC(request, dbType, null, loader.getDriver(dbType, null), username,
                            password, loader.getURL(dbType, null, host, dbname, false));
                } else {
                    updateServerPropertiesJNDI(request, dbType, server.getDbJNDI());
                }
                //success init DB
                response.sendRedirect("install?step=tables");
            } else {
                log.info("DB {} is existed", dbname);
                //return message, need user confirm
                request.setAttribute("existed", true);
                request.setAttribute("message", "Database already exist, do you want to reset it?");
                request.getRequestDispatcher("/WEB-INF/pages/install/createdb.jsp").forward(request, response);
            }
        } catch (DriverNotFoundException e) {
            log.error("DB driver not found", e);
            request.setAttribute("error",
                    "No suitable database driver found. Please copy corresponding driver to your web server library directory.");
            request.getRequestDispatcher("/WEB-INF/pages/install/createdb.jsp").forward(request, response);
        } catch (SQLException e) {
            log.error("SQL error", e.getNextException());
            request.setAttribute("error", "Exception:" + e.toString());
            request.getRequestDispatcher("/WEB-INF/pages/install/createdb.jsp").forward(request, response);
        } catch (Exception e) {
            log.error("Unable complete database initialize task", e);
            request.setAttribute("error", "Unable create database, please create manually.");
            request.getRequestDispatcher("/WEB-INF/pages/install/createdb.jsp").forward(request, response);
        } finally {
            if (con != null)
                con.close();
        }
    } else {
        //into session and file if current server is not jndi...
        Server server = (Server) request.getSession().getAttribute("server");
        if (!dbType.equalsIgnoreCase(server.getDbType())) {
            //this case is, server.xml is there,  but user change database type, keep DB type, connect Type to JDBC, and clear all other DB attributes
            updateServerPropertiesJDBC(request, dbType, null, null, null, null, null);
        }
        //for Oracle and DB2, only DBA create DB and table...
        response.sendRedirect("install?step=tables");
    }

}

From source file:com.wineaccess.winepermit.WinePermitHelper.java

/**
 * @param wineryPermitPO/*www  .  jav  a  2  s .  co m*/
 */
private void validateWinePermitPO(WinePermitPO wineryPermitPO) {
    response = new FailureResponse();

    Boolean isSellInMainStates = BooleanUtils.toBoolean(wineryPermitPO.getIsSellInMainStates());
    SellInAltStatesModel isSellInAltStates = wineryPermitPO.getSellInAltStates();

    if (BooleanUtils.isNotTrue(isSellInMainStates) && isSellInAltStates == null) {
        response.addError(new WineaccessError(SystemErrorCode.PERMIT_NO_OPTION_SELECTED_ERROR_WINE,
                SystemErrorCode.PERMIT_NO_OPTION_SELECTED_ERROR_WINE_TEXT));
    }
    if (BooleanUtils.isNotTrue(isSellInMainStates) && isSellInAltStates != null
            && !BooleanUtils.toBoolean(isSellInAltStates.getIsSelected())) {
        response.addError(new WineaccessError(SystemErrorCode.PERMIT_NO_OPTION_SELECTED_ERROR_WINE,
                SystemErrorCode.PERMIT_NO_OPTION_SELECTED_ERROR_WINE_TEXT));
    } else if (isSellInAltStates != null) {
        validateSellInAltModel(isSellInAltStates, wineryPermitPO.getProductId());
    }

}

From source file:com.haulmont.ext.web.ui.CauseGIBDD.CauseGIBDDBrowser.java

private void initAfterSetLookup(boolean isLookup) {
    final User user = UserSessionClient.getUserSession().getCurrentOrSubstitutedUser();
    SplitPanel splitPanel = getComponent("split");
    splitPanel.setSplitPosition(100);//from   w  w w  .  ja  v a 2s  .c o  m
    splitPanel.setLocked(true);
    if (isLookup) {
        docsTable.setMultiSelect(false);
    } else if (!isTemplate) {
        //            final HashMap<UUID, com.vaadin.ui.Component> statesMap = new HashMap<UUID, com.vaadin.ui.Component>();
        final CardService cardService = ServiceLocator.lookup(CardService.NAME);
        addLocStateColumn();

        resolutionsFrame = getComponent("resolutionsFrame");
        resolutionsFrame.init();

        cardTreeFrame = getComponent("cardTreeFrame");
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("card", null);
        cardTreeFrame.init(params);

        showResolutions = getComponent(HIDE_RESOLUTIONS);
        final SplitPanel split = getComponent("split");
        showResolutions.addListener(new ValueListener() {
            public void valueChanged(Object source, String property, Object prevValue, Object value) {
                boolean showResolutionsValue = BooleanUtils.isTrue((Boolean) value);
                int pos = (!showResolutionsValue ? 100 : 60);
                split.setSplitPosition(pos);
                split.setLocked(!showResolutionsValue);

                Card card = (Card) docsTable.getSingleSelected();
                if (showResolutionsValue && card != null) {
                    String currentTab = tabsheet.getTab().getName();
                    if (currentTab.equals("resolutionsTab"))
                        resolutionsFrame.setCard(card);
                    if (currentTab.equals("hierarchyTab"))
                        cardTreeFrame.setCard(card);
                }
            }
        });

        String value = getSettings().get(HIDE_RESOLUTIONS).attributeValue("value");
        showResolutions.setValue(value == null ? false : BooleanUtils.toBoolean(value));
    } else {
        SplitPanel split = getComponent("split");
        split.setSplitPosition(100);
        split.setLocked(true);
    }
}

From source file:com.wineaccess.winepermit.WinePermitHelper.java

/**
 * @param sellInAltStatesModel//from   ww w.ja  v  a  2s . c  om
 * @param string 
 */
private void validateSellInAltModel(SellInAltStatesModel sellInAltStatesModel, String wineId) {

    Boolean isOptionSelectedKachinaAlt = BooleanUtils
            .toBoolean(sellInAltStatesModel.getIsOptionSelectedKachinaAlt());
    OptionSelectedAltStates optionSelectedAltStates = sellInAltStatesModel.getOptionSelectedAltStates();
    Boolean isOptionSelectedNoPermit = BooleanUtils.toBoolean(sellInAltStatesModel.getIsSelectedNoPermit());
    Boolean isSelectedAltStates = BooleanUtils.toBoolean(sellInAltStatesModel.getIsSelected());

    if (BooleanUtils.isTrue(isSelectedAltStates) && BooleanUtils.isNotTrue(isOptionSelectedKachinaAlt)
            && optionSelectedAltStates == null && BooleanUtils.isNotTrue(isOptionSelectedNoPermit)) {
        response.addError(
                new WineaccessError(SystemErrorCode.PERMIT_NO_OPTION_SELECTED_WINE_LICENCES_ERROR_WINE,
                        SystemErrorCode.PERMIT_NO_OPTION_SELECTED_WINE_LICENCES_ERROR_WINE_TEXT));
    } else if ((BooleanUtils.isTrue(isOptionSelectedKachinaAlt) && optionSelectedAltStates != null)
            || BooleanUtils.isTrue(isOptionSelectedKachinaAlt) && BooleanUtils.isTrue(isOptionSelectedNoPermit)
            || BooleanUtils.isTrue(isOptionSelectedNoPermit) && optionSelectedAltStates != null) {
        response.addError(new WineaccessError(SystemErrorCode.PERMIT_MORE_THAN_ONE_OPTION_SELECTED_ERROR_WINE,
                SystemErrorCode.PERMIT_MORE_THAN_ONE_OPTION_SELECTED_ERROR_WINE_TEXT));
    } else {
        if (optionSelectedAltStates != null) {
            validateoptionSelectedAltstates(optionSelectedAltStates, wineId);
        } else if (sellInAltStatesModel.getOptionSelectedNoPermit() != null)
            validateoptionSelectedNoPermit(isOptionSelectedNoPermit,
                    sellInAltStatesModel.getOptionSelectedNoPermit(), wineId);
        else {
            if (BooleanUtils.isTrue(isOptionSelectedNoPermit))
                response.addError(new WineaccessError(SystemErrorCode.WINE_PERMIT_SELECT_VALUE_NO_PERMIT,
                        SystemErrorCode.WINE_PERMIT_SELECT_VALUE_NO_PERMIT_TEXT));
        }
    }

}