Example usage for java.lang Boolean toString

List of usage examples for java.lang Boolean toString

Introduction

In this page you can find the example usage for java.lang Boolean toString.

Prototype

public String toString() 

Source Link

Document

Returns a String object representing this Boolean's value.

Usage

From source file:api.Client.java

public Request<CategorySearchResult> listCategoryService(Number storeId, String token, Number parent,
        Boolean hidden_categories, Boolean productIds, Number limit, Number offset) {
    try {// w  w  w . ja  v a  2 s  . com
        URIBuilder builder = new URIBuilder(url + "/" + storeId + "/categories");
        if (token != null)
            builder.setParameter("token", token.toString());
        if (parent != null)
            builder.setParameter("parent", parent.toString());
        if (hidden_categories != null)
            builder.setParameter("hidden_categories", hidden_categories.toString());
        if (productIds != null)
            builder.setParameter("productIds", productIds.toString());
        if (limit != null)
            builder.setParameter("limit", limit.toString());
        if (offset != null)
            builder.setParameter("offset", offset.toString());

        if (storeId == null)
            throw new IllegalArgumentException("No parameter storeId is set");

        return new Request<CategorySearchResult>(getRequestExecutor(), builder.build()) {
            @Override
            public CategorySearchResult execute(RequestExecutor executor) throws IOException, JSONException {
                HttpGet method = new HttpGet(uri);
                try {
                    HttpResponse response = executor.execute(method);
                    if (response.getStatusLine().getStatusCode() >= 400) {
                        throw new IOException("Unexpected HTTP status: " + response.getStatusLine());
                    }
                    HttpEntity entity = response.getEntity();
                    if (entity == null)
                        throw new JSONException("No response. Expected JSON object.");
                    return new CategorySearchResult(new JSONObject(EntityUtils.toString(entity)));

                } finally {
                    method.releaseConnection();
                }
            }
        };
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:api.Client.java

public Request<ProductSearchResult> searchProductApiService(Number storeId, String keyword, Number priceFrom,
        Number priceTo, Number category, Boolean withSubcategories, String sortBy, Number offset, Number limit,
        String createdFrom, String createdTo, String updatedFrom, String updatedTo, Boolean enabled,
        Boolean inStock, String token) {
    try {//  www.ja  va2 s. c  o  m
        URIBuilder builder = new URIBuilder(url + "/" + storeId + "/products");
        if (keyword != null)
            builder.setParameter("keyword", keyword.toString());
        if (priceFrom != null)
            builder.setParameter("priceFrom", priceFrom.toString());
        if (priceTo != null)
            builder.setParameter("priceTo", priceTo.toString());
        if (category != null)
            builder.setParameter("category", category.toString());
        if (withSubcategories != null)
            builder.setParameter("withSubcategories", withSubcategories.toString());
        if (sortBy != null)
            builder.setParameter("sortBy", sortBy.toString());
        if (offset != null)
            builder.setParameter("offset", offset.toString());
        if (limit != null)
            builder.setParameter("limit", limit.toString());
        if (createdFrom != null)
            builder.setParameter("createdFrom", createdFrom.toString());
        if (createdTo != null)
            builder.setParameter("createdTo", createdTo.toString());
        if (updatedFrom != null)
            builder.setParameter("updatedFrom", updatedFrom.toString());
        if (updatedTo != null)
            builder.setParameter("updatedTo", updatedTo.toString());
        if (enabled != null)
            builder.setParameter("enabled", enabled.toString());
        if (inStock != null)
            builder.setParameter("inStock", inStock.toString());
        if (token != null)
            builder.setParameter("token", token.toString());

        if (storeId == null)
            throw new IllegalArgumentException("No parameter storeId is set");

        return new Request<ProductSearchResult>(getRequestExecutor(), builder.build()) {
            @Override
            public ProductSearchResult execute(RequestExecutor executor) throws IOException, JSONException {
                HttpGet method = new HttpGet(uri);
                try {
                    HttpResponse response = executor.execute(method);
                    if (response.getStatusLine().getStatusCode() >= 400) {
                        throw new IOException("Unexpected HTTP status: " + response.getStatusLine());
                    }
                    HttpEntity entity = response.getEntity();
                    if (entity == null)
                        throw new JSONException("No response. Expected JSON object.");
                    return new ProductSearchResult(new JSONObject(EntityUtils.toString(entity)));

                } finally {
                    method.releaseConnection();
                }
            }
        };
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:org.gvnix.web.menu.roo.addon.MenuEntryOperationsImpl.java

/**
 * {@inheritDoc}//  ww w . j  av  a 2 s .  c  o m
 * <p>
 * Update the entry ID could change entry type because category entry starts
 * with 'c_' prefix, item entry starts with 'i_' prefix, so to change a
 * category entry to item entry you have to set a new ID that starts with
 * 'i_'.
 */
public void updateEntry(JavaSymbolName pageId, JavaSymbolName nid, String label, String messageCode,
        String destination, String roles, Boolean hidden, boolean writeProps) {
    Document document = getMenuDocument();

    // Properties to be writen
    Map<String, String> properties = new HashMap<String, String>();

    // make the root element of the menu the one with the menu identifier
    // allowing for different decorations of menu
    Element rootElement = XmlUtils.findFirstElement(ID_MENU_EXP, (Element) document.getFirstChild());

    if (!rootElement.getNodeName().equals(GVNIX_MENU)) {
        throw new IllegalArgumentException(INVALID_XML);
    }

    // check for existence of menu category by looking for the identifier
    // provided
    Element pageElement = XmlUtils.findFirstElement(ID_EXP.concat(pageId.getSymbolName()).concat("']"),
            rootElement);

    // exit if menu entry doesn't exist
    Validate.notNull(pageElement, "Menu entry '".concat(pageId.getSymbolName()).concat(NOT_FOUND));

    if (nid != null) {
        pageElement.setAttribute("id", nid.getSymbolName());

        // TODO: if Element has children, children IDs should be
        // recalculated too
        // TODO: label code should change too (as addMenuItem does)
    }

    if (StringUtils.isNotBlank(label)) {
        String itemLabelCode = pageElement.getAttribute(LABEL_CODE);
        properties.put(itemLabelCode, label);
    }

    if (writeProps) {
        propFileOperations.addProperties(LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""),
                "/WEB-INF/i18n/application.properties", properties, true, true);
    }

    if (StringUtils.isNotBlank(messageCode)) {
        pageElement.setAttribute(MESSAGE_CODE, messageCode);
    }

    if (StringUtils.isNotBlank(destination)) {
        pageElement.setAttribute(URL, destination);
    }

    if (StringUtils.isNotBlank(roles)) {
        pageElement.setAttribute("roles", roles);
    }

    if (hidden != null) {
        pageElement.setAttribute(HIDDEN, hidden.toString());
    }

    writeXMLConfigIfNeeded(document);
}

From source file:com.cloud.network.element.BigSwitchBcfElement.java

@Override
@DB//  w  ww . j a va2  s . c o m
public BigSwitchBcfDeviceVO addBigSwitchBcfDevice(AddBigSwitchBcfDeviceCmd cmd) {
    BigSwitchBcfDeviceVO newBcfDevice;

    bcfUtilsInit();

    ServerResource resource = new BigSwitchBcfResource();

    final String deviceName = BcfConstants.BIG_SWITCH_BCF.getName();
    NetworkDevice networkDevice = NetworkDevice.getNetworkDevice(deviceName);
    final Long physicalNetworkId = cmd.getPhysicalNetworkId();
    final String hostname = cmd.getHost();
    final String username = cmd.getUsername();
    final String password = cmd.getPassword();
    final Boolean nat = cmd.getNat();

    PhysicalNetworkVO physicalNetwork = _physicalNetworkDao.findById(physicalNetworkId);
    if (physicalNetwork == null) {
        throw new InvalidParameterValueException(
                "Could not find phyical network with ID: " + physicalNetworkId);
    }
    long zoneId = physicalNetwork.getDataCenterId();

    final PhysicalNetworkServiceProviderVO ntwkSvcProvider = _physicalNetworkServiceProviderDao
            .findByServiceProvider(physicalNetwork.getId(), networkDevice.getNetworkServiceProvder());
    if (ntwkSvcProvider == null) {
        throw new CloudRuntimeException("Network Service Provider: " + networkDevice.getNetworkServiceProvder()
                + " is not enabled in the physical network: " + physicalNetworkId + "to add this device");
    } else if (ntwkSvcProvider.getState() == PhysicalNetworkServiceProvider.State.Shutdown) {
        throw new CloudRuntimeException("Network Service Provider: " + ntwkSvcProvider.getProviderName()
                + " is in shutdown state in the physical network: " + physicalNetworkId + "to add this device");
    }
    ntwkSvcProvider.setFirewallServiceProvided(true);
    ntwkSvcProvider.setGatewayServiceProvided(true);
    ntwkSvcProvider.setNetworkAclServiceProvided(true);
    ntwkSvcProvider.setSourcenatServiceProvided(true);
    ntwkSvcProvider.setStaticnatServiceProvided(true);

    if (_bigswitchBcfDao.listByPhysicalNetwork(physicalNetworkId).size() > 1) {
        throw new CloudRuntimeException("At most two BCF controllers can be configured");
    }

    DataCenterVO zone = _zoneDao.findById(physicalNetwork.getDataCenterId());
    String zoneName;
    if (zone != null) {
        zoneName = zone.getName();
    } else {
        zoneName = String.valueOf(zoneId);
    }

    Boolean natNow = _bcfUtils.isNatEnabled();
    if (!nat && natNow) {
        throw new CloudRuntimeException(
                "NAT is enabled in existing controller. Enable NAT for new controller or remove existing controller first.");
    } else if (nat && !natNow) {
        throw new CloudRuntimeException(
                "NAT is disabled in existing controller. Disable NAT for new controller or remove existing controller first.");
    }

    Map<String, String> params = new HashMap<String, String>();
    params.put("guid", UUID.randomUUID().toString());
    params.put("zoneId", zoneName);
    params.put("physicalNetworkId", String.valueOf(physicalNetwork.getId()));
    params.put("name", "BigSwitch Controller - " + cmd.getHost());
    params.put("hostname", cmd.getHost());
    params.put("username", username);
    params.put("password", password);
    params.put("nat", nat.toString());

    // FIXME What to do with multiple isolation types
    params.put("transportzoneisotype", physicalNetwork.getIsolationMethods().get(0).toLowerCase());
    Map<String, Object> hostdetails = new HashMap<String, Object>();
    hostdetails.putAll(params);

    try {
        resource.configure(cmd.getHost(), hostdetails);

        // store current topology in bcf resource
        TopologyData topo = _bcfUtils.getTopology(physicalNetwork.getId());
        ((BigSwitchBcfResource) resource).setTopology(topo);

        final Host host = _resourceMgr.addHost(zoneId, resource, Host.Type.L2Networking, params);
        if (host != null) {
            newBcfDevice = Transaction.execute(new TransactionCallback<BigSwitchBcfDeviceVO>() {
                @Override
                public BigSwitchBcfDeviceVO doInTransaction(TransactionStatus status) {
                    BigSwitchBcfDeviceVO bigswitchBcfDevice = new BigSwitchBcfDeviceVO(host.getId(),
                            physicalNetworkId, ntwkSvcProvider.getProviderName(), deviceName, hostname,
                            username, password, nat, BigSwitchBcfApi.HASH_IGNORE);
                    _bigswitchBcfDao.persist(bigswitchBcfDevice);

                    DetailVO detail = new DetailVO(host.getId(), "bigswitchbcfdeviceid",
                            String.valueOf(bigswitchBcfDevice.getId()));
                    _hostDetailsDao.persist(detail);

                    return bigswitchBcfDevice;
                }
            });
        } else {
            throw new CloudRuntimeException(
                    "Failed to add BigSwitch BCF Controller Device due to internal error.");
        }
    } catch (ConfigurationException e) {
        throw new CloudRuntimeException(e.getMessage());
    }

    // initial topology sync to newly added BCF controller
    HostVO bigswitchBcfHost = _hostDao.findById(newBcfDevice.getHostId());
    _bcfUtils.syncTopologyToBcfHost(bigswitchBcfHost, nat);

    return newBcfDevice;
}

From source file:edu.mit.isda.permitws.permit.java

@SuppressWarnings("unchecked")

public StringBuffer createAuthorizationXML(StringBuffer xml, String category, String functionName,
        String functionDesc, String qualifierType, String qualifierName, String qualifierCode,
        String kerberosName, String firstName, String lastName, Long authId, Date effDate, Date expDate,
        Boolean isActive, Character doFunction, String grantAuthorization, String modifiedBy, Date modifiedDate,
        String proxyUserName, boolean isEditable) throws Exception {
    xml.append("\r\n{\"category\":\"" + category.trim() + "\",");
    xml.append("\"functionName\":\"" + functionName.trim() + "\",");
    if (functionDesc != null) {
        xml.append("\"functionDesc\":\"" + functionDesc.trim() + "\",");
    } else {/*www . java 2 s.com*/
        xml.append("\"functionDesc\":\"\",");
    }
    xml.append("\"qualifierType\":\"" + qualifierType.trim() + "\",");
    String qName = qualifierName.trim().replaceAll("[\"]", "'");
    xml.append("\"qualifierName\":\"" + qName + "\",");
    if (qualifierCode != null)
        xml.append("\"qualifierCode\":\"" + qualifierCode.trim() + "\",");
    else
        xml.append("\"qualifierCode\":\"null\",");
    xml.append("\"kerberosName\":\"" + kerberosName.trim() + "\",");
    xml.append("\"firstName\":\"" + firstName.trim() + "\",");
    xml.append("\"lastName\":\"" + lastName.trim() + "\",");
    xml.append("\"authorizationID\":\"" + authId.toString() + "\",");

    SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
    xml.append("\"effectiveDate\":\"" + formatter.format(effDate) + "\",");
    if (null == expDate) {
        xml.append("\"expirationDate\":\"\",");
    } else {
        xml.append("\"expirationDate\":\"" + formatter.format(expDate) + "\",");
    }
    if (null != isActive) {
        xml.append("\"active\":\"" + isActive.toString() + "\",");
    }

    xml.append("\"doFunction\":\"" + doFunction.toString() + "\",");
    xml.append("\"grantAuthorization\":\"" + grantAuthorization + "\",");
    xml.append("\"modifiedBy\":\"" + modifiedBy + "\",");
    xml.append("\"modifiedDate\":\"" + formatter.format(modifiedDate) + "\",");
    xml.append("\"proxyUser\":\"" + proxyUserName + "\",");
    xml.append("\"isEditable\":\"" + new Boolean(isEditable).toString() + "\"},");

    return (xml);
}

From source file:gov.nih.nci.evs.browser.utils.DataUtils.java

public static HashMap getRelatedConceptsHashMap(String codingSchemeName, String vers, String code,
        String source, int resolveCodedEntryDepth) {
    HashMap hmap = new HashMap();
    try {/*from   ww  w.j  a v  a2  s .c o  m*/
        LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService();
        if (lbSvc == null)
            return null;
        LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc
                .getGenericExtension("LexBIGServiceConvenienceMethods");
        lbscm.setLexBIGService(lbSvc);
        /*
                    if (lbSvc == null) {
        Debug.println("lbSvc == null???");
        return hmap;
                    }
        */
        CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag();
        if (vers != null)
            versionOrTag.setVersion(vers);
        CodedNodeGraph cng = lbSvc.getNodeGraph(codingSchemeName, null, null);

        if (source != null) {
            cng = cng.restrictToAssociations(Constructors.createNameAndValueList(META_ASSOCIATIONS),
                    Constructors.createNameAndValueList("source", source));
        }

        CodedNodeSet.PropertyType[] propertyTypes = new CodedNodeSet.PropertyType[1];
        propertyTypes[0] = PropertyType.PRESENTATION;

        ResolvedConceptReferenceList matches = cng.resolveAsList(
                Constructors.createConceptReference(code, codingSchemeName), true, true, resolveCodedEntryDepth,
                1, null, propertyTypes, null, -1);

        if (matches != null) {
            java.lang.Boolean incomplete = matches.getIncomplete();
            // _logger.debug("(*) Number of matches: " +
            // matches.getResolvedConceptReferenceCount());
            // _logger.debug("(*) Incomplete? " + incomplete);
            hmap.put(INCOMPLETE, incomplete.toString());
        } else {
            return null;
        }

        if (matches.getResolvedConceptReferenceCount() > 0) {
            Enumeration<ResolvedConceptReference> refEnum = (Enumeration<ResolvedConceptReference>) matches
                    .enumerateResolvedConceptReference();

            while (refEnum.hasMoreElements()) {
                ResolvedConceptReference ref = refEnum.nextElement();
                AssociationList sourceof = ref.getSourceOf();
                if (sourceof != null) {
                    Association[] associations = sourceof.getAssociation();
                    if (associations != null) {
                        for (int i = 0; i < associations.length; i++) {
                            Association assoc = associations[i];
                            String associationName = lbscm.getAssociationNameFromAssociationCode(
                                    codingSchemeName, versionOrTag, assoc.getAssociationName());
                            String associationName0 = associationName;

                            String directionalLabel = associationName;
                            boolean navigatedFwd = true;
                            try {
                                directionalLabel = getDirectionalLabel(lbscm, codingSchemeName, versionOrTag,
                                        assoc, navigatedFwd);
                            } catch (Exception e) {
                                Debug.println("(*) getDirectionalLabel throws exceptions: " + directionalLabel);
                            }

                            //Vector v = new Vector();
                            AssociatedConcept[] acl = assoc.getAssociatedConcepts().getAssociatedConcept();
                            for (int j = 0; j < acl.length; j++) {
                                AssociatedConcept ac = acl[j];
                                String asso_label = associationName;
                                String qualifier_name = null;
                                String qualifier_value = null;
                                if (associationName.compareToIgnoreCase("equivalentClass") != 0) {
                                    for (NameAndValue qual : ac.getAssociationQualifiers().getNameAndValue()) {
                                        qualifier_name = qual.getName();
                                        qualifier_value = qual.getContent();
                                        if (qualifier_name.compareToIgnoreCase("rela") == 0) {
                                            asso_label = qualifier_value; // replace
                                            // associationName
                                            // by
                                            // Rela
                                            // value
                                            break;
                                        }
                                    }
                                    Vector w = null;
                                    String asso_key = directionalLabel + "|" + asso_label;
                                    if (hmap.containsKey(asso_key)) {
                                        w = (Vector) hmap.get(asso_key);
                                    } else {
                                        w = new Vector();
                                    }
                                    w.add(ac);
                                    hmap.put(asso_key, w);
                                }
                            }
                        }
                    }
                }

                sourceof = ref.getTargetOf();
                if (sourceof != null) {
                    Association[] associations = sourceof.getAssociation();
                    if (associations != null) {
                        for (int i = 0; i < associations.length; i++) {
                            Association assoc = associations[i];
                            String associationName = lbscm.getAssociationNameFromAssociationCode(
                                    codingSchemeName, versionOrTag, assoc.getAssociationName());
                            String associationName0 = associationName;

                            if (associationName.compareTo("CHD") == 0 || associationName.compareTo("RB") == 0) {

                                String directionalLabel = associationName;
                                boolean navigatedFwd = false;
                                try {
                                    directionalLabel = getDirectionalLabel(lbscm, codingSchemeName,
                                            versionOrTag, assoc, navigatedFwd);
                                    // Debug.println("(**) directionalLabel: associationName "
                                    // + associationName +
                                    // "   directionalLabel: " +
                                    // directionalLabel);
                                } catch (Exception e) {
                                    Debug.println(
                                            "(**) getDirectionalLabel throws exceptions: " + directionalLabel);
                                }

                                //Vector v = new Vector();
                                AssociatedConcept[] acl = assoc.getAssociatedConcepts().getAssociatedConcept();
                                for (int j = 0; j < acl.length; j++) {
                                    AssociatedConcept ac = acl[j];
                                    String asso_label = associationName;
                                    String qualifier_name = null;
                                    String qualifier_value = null;
                                    if (associationName.compareToIgnoreCase("equivalentClass") != 0) {
                                        for (NameAndValue qual : ac.getAssociationQualifiers()
                                                .getNameAndValue()) {
                                            qualifier_name = qual.getName();
                                            qualifier_value = qual.getContent();

                                            if (qualifier_name.compareToIgnoreCase("rela") == 0) {
                                                // associationName =
                                                // qualifier_value; //
                                                // replace associationName
                                                // by Rela value
                                                asso_label = qualifier_value;
                                                break;
                                            }
                                        }

                                        Vector w = null;
                                        String asso_key = directionalLabel + "|" + asso_label;
                                        if (hmap.containsKey(asso_key)) {
                                            w = (Vector) hmap.get(asso_key);
                                        } else {
                                            w = new Vector();
                                        }
                                        w.add(ac);
                                        hmap.put(asso_key, w);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return hmap;
}

From source file:de.escidoc.core.test.EscidocTestBase.java

/**
 * Get task param XML for add/remove members methods (see members-task-param.xsd)
 * //from  w w w. ja v  a  2 s . c o m
 * @param ids
 *            member id parameter
 * @param sync
 * @return task param XML (assign-pid-task-param.xsd)
 */
public static String getDeleteObjectsTaskParam(final Set<String> ids, final Boolean sync) {

    // FIXME Namespace wrong but the real is'nt defined yet (INFR-1466)
    StringBuilder xml = new StringBuilder(de.escidoc.core.test.Constants.XML_HEADER);
    xml.append("<param xmlns=\"http://www.escidoc.org/schemas/delete-objects-task-param/0.1\">\n");

    for (String id : ids) {
        xml.append("<id>").append(id).append("</id>\n");
    }
    if (sync != null) {
        xml.append("<sync>").append(sync.toString()).append("</sync>\n");
    }
    xml.append("</param>\n");

    return xml.toString();
}

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

@CliCommand(value = "cluster resize", help = "Resize a cluster")
public void resizeCluster(
        @CliOption(key = { "name" }, mandatory = true, help = "The cluster name") final String name,
        @CliOption(key = {/*from w w  w .  j  av  a 2  s . c  om*/
                "nodeGroup" }, mandatory = true, help = "The node group name") final String nodeGroup,
        @CliOption(key = {
                "instanceNum" }, mandatory = false, unspecifiedDefaultValue = "0", help = "The new instance number, should be larger than 0") final int instanceNum,
        @CliOption(key = {
                "cpuNumPerNode" }, mandatory = false, unspecifiedDefaultValue = "0", help = "The number of vCPU for the nodes in this group") final int cpuNumber,
        @CliOption(key = {
                "memCapacityMbPerNode" }, mandatory = false, unspecifiedDefaultValue = "0", help = "The number of memory size in Mb for the nodes in this group") final long memory,
        @CliOption(key = {
                "force" }, mandatory = false, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = "Ignore errors during resizing cluster") final Boolean force,
        @CliOption(key = {
                "skipVcRefresh" }, mandatory = false, help = "flag to skip refreshing VC resources") final Boolean skipVcRefresh) {

    if ((instanceNum > 0 && cpuNumber == 0 && memory == 0)
            || (instanceNum == 0 && (cpuNumber > 0 || memory > 0))) {
        try {
            ClusterRead cluster = restClient.get(name, false);
            if (cluster == null) {
                CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_RESIZE,
                        Constants.OUTPUT_OP_RESULT_FAIL, "cluster " + name + " does not exist.");
                return;
            }
            // disallow scale out zookeeper node group.
            List<NodeGroupRead> ngs = cluster.getNodeGroups();
            boolean found = false;
            for (NodeGroupRead ng : ngs) {
                if (ng.getName().equals(nodeGroup)) {
                    found = true;
                    /*if (ng.getRoles() != null
                          && ng.getRoles().contains(
                      HadoopRole.ZOOKEEPER_ROLE.toString())
                          && instanceNum > 1) {
                       CommandsUtils.printCmdFailure(
                             Constants.OUTPUT_OBJECT_CLUSTER, name,
                             Constants.OUTPUT_OP_RESIZE,
                             Constants.OUTPUT_OP_RESULT_FAIL,
                             Constants.ZOOKEEPER_NOT_RESIZE);
                       return;
                    }*/// TODO emma: do not check as client do not know who is Zookeeper
                    break;
                }
            }

            if (!found) {
                CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_RESIZE,
                        Constants.OUTPUT_OP_RESULT_FAIL, "node group " + nodeGroup + " does not exist.");
                return;
            }
            TaskRead taskRead = null;
            if (instanceNum > 0) {
                Map<String, String> queryStrings = new HashMap<String, String>();
                queryStrings.put(Constants.FORCE_CLUSTER_OPERATION_KEY, force.toString());
                queryStrings.put(Constants.REST_PARAM_SKIP_REFRESH_VC,
                        Boolean.toString(BooleanUtils.toBoolean(skipVcRefresh)));
                restClient.resize(name, nodeGroup, instanceNum, queryStrings);
            } else if (cpuNumber > 0 || memory > 0) {
                if (!cluster.getStatus().isActiveServiceStatus()) {
                    CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_RESIZE,
                            Constants.OUTPUT_OP_RESULT_FAIL,
                            "Cluster must be in 'RUNNING' state to scale up/down");
                    return;
                }
                ResourceScale resScale = new ResourceScale(name, nodeGroup, cpuNumber, memory);
                taskRead = restClient.scale(resScale);
            }
            CommandsUtils.printCmdSuccess(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_RESULT_RESIZE);
            if (taskRead != null) {
                System.out.println();
                printScaleReport(taskRead, name, nodeGroup);
            }
        } catch (CliRestException e) {
            CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_RESIZE,
                    Constants.OUTPUT_OP_RESULT_FAIL, e.getMessage());
        }
    } else {
        if (instanceNum > 0 && (cpuNumber > 0 || memory > 0)) {
            CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_RESIZE,
                    Constants.OUTPUT_OP_RESULT_FAIL,
                    "Can not scale out/in and scale up/down at the same time, you have to run those commands separately");
        } else if (instanceNum == 0 && cpuNumber == 0 && memory == 0) {
            CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_RESIZE,
                    Constants.OUTPUT_OP_RESULT_FAIL,
                    "You must specify one positive value for instanceNum/cpuNumPerNode/memCapacityMbPerNode");

        } else {
            List<String> invalidParams = new ArrayList<String>();
            if (instanceNum < 0) {
                invalidParams.add("instanceNum=" + instanceNum);
            }
            if (cpuNumber < 0) {
                invalidParams.add("cpuNumPerNode=" + cpuNumber);
            }
            if (memory < 0) {
                invalidParams.add("memCapacityMbPerNode=" + memory);
            }
            CommandsUtils.printCmdFailure(Constants.OUTPUT_OBJECT_CLUSTER, Constants.OUTPUT_OP_RESIZE,
                    Constants.OUTPUT_OP_RESULT_FAIL,
                    Constants.INVALID_VALUE + " " + StringUtils.join(invalidParams, ", "));
        }
    }
}

From source file:org.wso2.carbon.apimgt.hostobjects.APIProviderHostObject.java

public static String jsFunction_isContextExist(Context cx, Scriptable thisObj, Object[] args, Function funObj)
        throws APIManagementException {
    Boolean contextExist = false;
    if (args != null && isStringValues(args)) {
        String context = (String) args[0];
        String oldContext = (String) args[1];

        if (context.equals(oldContext)) {
            return contextExist.toString();
        }//from  w  ww .j a  v  a 2 s.co m
        APIProvider apiProvider = getAPIProvider(thisObj);
        try {
            contextExist = apiProvider.isDuplicateContextTemplate(context);
        } catch (APIManagementException e) {
            handleException("Error while checking whether context exists", e);
        }
    } else {
        handleException("Input context value is null");
    }
    return contextExist.toString();
}

From source file:com.redsqirl.CanvasBean.java

public String[] getPositions(DataFlow df, String workflowName, String selecteds) {

    try {//from   w  w w . j  a  v a 2s  .c o m

        Map<String, String> elements = getReverseIdMap(workflowName);

        JSONArray jsonElements = new JSONArray();
        JSONArray jsonLinks = new JSONArray();
        String voronoiPolygonTitle = null;

        if (df != null && df.getElement() != null) {

            for (DataFlowElement e : df.getElement()) {
                String compId = e.getComponentId();
                String privilege = null;
                Boolean privilegeObj;

                try {
                    privilegeObj = null;
                    privilegeObj = ((SuperElement) e).getPrivilege();
                } catch (Exception epriv) {
                    privilegeObj = null;
                }

                if (privilegeObj != null) {
                    privilege = privilegeObj.toString().toLowerCase();
                }

                logger.info(compId + " privilege " + privilege);
                String elementName = e.getName();

                //voronoi polygon
                voronoiPolygonTitle = e.getCoordinatorName();

                jsonElements.put(new Object[] { elements.get(compId),
                        elementName.startsWith(">") ? elementName.substring(elementName.lastIndexOf(">") + 1)
                                : elementName,
                        LocalFileSystem.relativize(getCurrentPage(), e.getImage()), e.getX(), e.getY(), compId,
                        privilege, elementName, voronoiPolygonTitle });

            }

            for (DataFlowElement outEl : df.getElement()) {
                String outElId = outEl.getComponentId();
                Map<String, Map<String, String>> inputsPerOutputs = outEl.getInputNamePerOutput();
                Iterator<String> outputNameIt = inputsPerOutputs.keySet().iterator();
                while (outputNameIt.hasNext()) {
                    String outputNameCur = outputNameIt.next();
                    Iterator<String> elInIdIt = inputsPerOutputs.get(outputNameCur).keySet().iterator();
                    while (elInIdIt.hasNext()) {
                        String inElId = elInIdIt.next();
                        jsonLinks.put(new Object[] { elements.get(outElId), outputNameCur, elements.get(inElId),
                                inputsPerOutputs.get(outputNameCur).get(inElId) });
                    }
                }
            }

        } else {
            logger.warn("Error getPositions getDf NULL or empty");
        }

        logger.warn("getPositions getNameWorkflow " + workflowName);
        logger.warn("getPositions getPath " + df.getPath());
        logger.warn("getPositions jsonElements.toString " + jsonElements.toString());
        logger.warn("getPositions jsonLinks.toString " + jsonLinks.toString());
        logger.warn("getPositions getWorkflowType " + getMapWorkflowType().get(workflowName));

        return new String[] { workflowName, df.getPath(), jsonElements.toString(), jsonLinks.toString(),
                selecteds, getMapWorkflowType().get(workflowName), getVoronoi()[0] };

    } catch (Exception e) {
        logger.warn("Error " + e + " - " + e.getMessage());
        MessageUseful.addErrorMessage(getMessageResources("msg_error_oops"));
        HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
                .getRequest();
        request.setAttribute("msnError", "msnError");
    }

    logger.warn("getPositions empty ");

    return new String[] {};
}