Example usage for java.lang Boolean equals

List of usage examples for java.lang Boolean equals

Introduction

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

Prototype

public boolean equals(Object obj) 

Source Link

Document

Returns true if and only if the argument is not null and is a Boolean object that represents the same boolean value as this object.

Usage

From source file:org.openbravo.advpaymentmngt.utility.FIN_Utility.java

/**
 * Returns a list of Payment Status. If isConfirmed equals true, then the status returned are
 * confirmed payments. Else they are pending of execution
 * /*from w  ww . j  a v  a2s. c o m*/
 */
private static List<String> getListPaymentConfirmedOrNot(Boolean isConfirmed) {

    List<String> listPaymentConfirmedOrNot = new ArrayList<String>();
    OBContext.setAdminMode(true);
    try {
        final OBCriteria<org.openbravo.model.ad.domain.List> obCriteria = OBDal.getInstance()
                .createCriteria(org.openbravo.model.ad.domain.List.class);
        obCriteria.add(Restrictions.eq(org.openbravo.model.ad.domain.List.PROPERTY_REFERENCE + ".id",
                "575BCB88A4694C27BC013DE9C73E6FE7"));
        List<org.openbravo.model.ad.domain.List> adRefList = obCriteria.list();
        for (org.openbravo.model.ad.domain.List adRef : adRefList) {
            if (isConfirmed.equals(isPaymentConfirmed(adRef.getSearchKey(), null))) {
                listPaymentConfirmedOrNot.add(adRef.getSearchKey());
            }
        }
        return listPaymentConfirmedOrNot;
    } catch (Exception e) {
        log4j.error("Error getting list of confirmed payments", e);
        return null;
    } finally {
        OBContext.restorePreviousMode();
    }
}

From source file:org.hyperic.hq.ui.action.resource.common.inventory.EditConfigPropertiesAction.java

/**
 * Edit the resource Configuration properties with
 * <code>ResourceConfigForm</code>.
 *///  w  w  w .  j a va 2 s .  c o m
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    ResourceConfigForm cfgForm = (ResourceConfigForm) form;
    AppdefEntityID aeid = new AppdefEntityID(cfgForm.getType().intValue(), cfgForm.getRid());

    HashMap<String, Object> forwardParams = new HashMap<String, Object>(2);
    forwardParams.put(Constants.ENTITY_ID_PARAM, aeid.getAppdefKey());

    switch (aeid.getType()) {
    case AppdefEntityConstants.APPDEF_TYPE_PLATFORM:
        forwardParams.put(Constants.ACCORDION_PARAM, "5");
        break;
    case AppdefEntityConstants.APPDEF_TYPE_SERVER:
        forwardParams.put(Constants.ACCORDION_PARAM, "3");
        break;
    case AppdefEntityConstants.APPDEF_TYPE_SERVICE:
        forwardParams.put(Constants.ACCORDION_PARAM, "2");
        break;
    }

    ActionForward forward = checkSubmit(request, mapping, form, forwardParams);
    AllConfigResponses allConfigs = new AllConfigResponses();
    AllConfigResponses allConfigsRollback = new AllConfigResponses();
    String prefix;
    if (forward != null) {
        // HACK to redirect back to Problem Resources portlet if the
        // request originated there.
        if (request.getParameter("todash") != null) {
            return mapping.findForward("dash");
        }
        return forward;
    }

    try {

        Integer sessionId = RequestUtils.getSessionId(request);
        int sessionInt = sessionId.intValue();

        String[] cfgTypes = ProductPlugin.CONFIGURABLE_TYPES;
        int i, numConfigs = cfgTypes.length;
        ConfigSchema[] schemas = new ConfigSchema[cfgTypes.length];
        ConfigResponse[] oldConfigs = new ConfigResponse[cfgTypes.length];
        ConfigResponse[] newConfigs = new ConfigResponse[cfgTypes.length];

        // Save the original resource
        allConfigs.setResource(aeid);
        allConfigsRollback.setResource(aeid);

        ConfigResponseDB oldConfig = productBoss.getConfigResponse(sessionInt, aeid);

        // get the configSchemas and existing configs
        for (i = 0; i < numConfigs; i++) {
            try {
                byte[] oldCfgBytes = null;
                if (cfgTypes[i].equals(ProductPlugin.TYPE_PRODUCT)) {
                    oldCfgBytes = oldConfig.getProductResponse();
                } else if (cfgTypes[i].equals(ProductPlugin.TYPE_MEASUREMENT)) {
                    oldCfgBytes = oldConfig.getMeasurementResponse();
                } else if (cfgTypes[i].equals(ProductPlugin.TYPE_CONTROL)) {
                    oldCfgBytes = oldConfig.getControlResponse();
                    if ((aeid.isPlatform()) && (oldCfgBytes == null)) {
                        // in case of platform if there is no control config - control actions are not supported
                        // notice - empty control response is created for server/service (not too good - we rely that in this case getPlugin of control
                        // manager will return no supported - better not to create control plugin - in this case too.) -change for 6.0??
                        blankoutConfig(i, allConfigs, allConfigsRollback);
                        if (log.isDebugEnabled()) {
                            log.debug("Blanking for " + cfgTypes[i] + "->(not supported)");
                        }
                        continue;
                    }
                } else if (cfgTypes[i].equals(ProductPlugin.TYPE_RESPONSE_TIME)) {
                    oldCfgBytes = oldConfig.getResponseTimeResponse();
                }

                if (oldCfgBytes == null) {
                    oldConfigs[i] = new ConfigResponse();
                } else {
                    oldConfigs[i] = ConfigResponse.decode(oldCfgBytes);
                }

                schemas[i] = productBoss.getConfigSchema(sessionInt, aeid, cfgTypes[i], oldConfigs[i]);
                allConfigsRollback.setConfig(i, oldConfigs[i]);
                allConfigsRollback.setSupports(i, true);
                allConfigs.setSupports(i, true);
            } catch (PluginNotFoundException e) {
                // No plugin support for this config type - skip ahead to
                // the next type.
                log.debug(cfgTypes[i] + " PluginNotFound for " + aeid + " : " + e);
                log.debug("Blanking for " + cfgTypes[i] + "->(not supported)");
                blankoutConfig(i, allConfigs, allConfigsRollback);
            }
        }

        AppdefResourceValue updatedResource = appdefBoss.findById(sessionInt, aeid);

        // get the new configs based on UI form fields
        for (i = 0; i < numConfigs; i++) {

            // Don't bother configuring things that aren't supported.
            if (!allConfigs.getSupports(i))
                continue;

            // Load new configs from requestParams
            if (i == ProductPlugin.CFGTYPE_IDX_PRODUCT) {
                prefix = ProductPlugin.TYPE_PRODUCT + ".";
                newConfigs[i] = BizappUtils.buildSaveConfigOptions(prefix, request, new ConfigResponse(),
                        schemas[i], null);
                // Make current form values appear in case of error.
                cfgForm.setResourceConfigOptions(
                        BizappUtils.buildLoadConfigOptions(prefix, schemas[i], newConfigs[i]));
                allConfigs.setShouldConfig(i, true);
                allConfigs.setConfig(i, newConfigs[i]);
                allConfigsRollback.setShouldConfig(i, true);

            } else {
                if (i == ProductPlugin.CFGTYPE_IDX_RESPONSE_TIME) {
                    if (aeid.isServer() || aeid.isPlatform()) {
                        // On servers, RT always gets an empty config
                        allConfigs.setConfig(i, new ConfigResponse());
                        allConfigs.setShouldConfig(i, true);
                        allConfigsRollback.setShouldConfig(i, true);

                    } else if (!aeid.isService() || !allConfigs.supportsMetricConfig()) {
                        // Otherwise, only configure response time for
                        // services, and only if the plugin has metric
                        // support.
                        blankoutConfig(i, allConfigs, allConfigsRollback);
                        continue;
                    }
                }
                if (i == ProductPlugin.CFGTYPE_IDX_CONTROL && !aeid.isService() && !aeid.isServer()
                        && !aeid.isPlatform()) {
                    // Control is only supported on platforms, servers and services
                    blankoutConfig(i, allConfigs, allConfigsRollback);
                    continue;
                }

                newConfigs[i] = new ConfigResponse(schemas[i]);
                allConfigs.setConfig(i, newConfigs[i]);
                prefix = cfgTypes[i] + ".";
                Boolean wereChanges = BizappUtils.populateConfig(request, prefix, schemas[i], newConfigs[i],
                        oldConfigs[i]);
                if (wereChanges == null) {
                    // This means the schema had no options, so the concept
                    // of changes doesn't make much sense. In these cases,
                    // we'll just keep the empty ConfigResponse
                    allConfigs.setShouldConfig(i, true);
                    allConfigsRollback.setShouldConfig(i, true);

                } else if (wereChanges.equals(Boolean.TRUE)) {
                    // There were changes. Cool, we'll keep them.
                    allConfigs.setShouldConfig(i, true);
                    allConfigsRollback.setShouldConfig(i, true);

                } else {
                    // There were no changes. We discard the config
                    // response. This way, when we do the server-side
                    // bizapp stuff, we don't re-configure things that
                    // have not changed.

                    // But AHA! There is a perverted edge case here: if
                    // this is a service and the config prop names for the
                    // service
                    // are the same as those for the server, and the service
                    // has
                    // never been configured, then we won't think anything
                    // has
                    // changed when in fact it has. See bug 8251.
                    boolean reallyWereChanges = false;
                    try {
                        productBoss.getMergedConfigResponse(sessionInt, cfgTypes[i], aeid, true);
                    } catch (ConfigFetchException cfe) {
                        // OK, so there really were changes because the
                        // config doesn't
                        // exist!
                        reallyWereChanges = true;
                        allConfigs.setShouldConfig(i, true);
                        allConfigsRollback.setShouldConfig(i, true);
                    }
                    if (!reallyWereChanges) {
                        allConfigs.setShouldConfig(i, false);
                        allConfigsRollback.setShouldConfig(i, false);
                    }
                }

                switch (i) {
                case ProductPlugin.CFGTYPE_IDX_MEASUREMENT:
                    // If metric config was setup, then setup runtime AI
                    // flag.
                    if ((aeid.isServer() || aeid.isService()) && (allConfigs.getMetricConfig() != null)) {
                        boolean rollback, runtimeAI;
                        if (aeid.isServer()) {
                            rollback = ((ServerValue) updatedResource).getRuntimeAutodiscovery();
                            runtimeAI = cfgForm.getServerBasedAutoInventory();
                        } else {
                            rollback = false;
                            runtimeAI = true; // XXX
                                              // !((ServiceValue)updatedResource).getWasAutodiscovered();
                        }
                        allConfigsRollback.setEnableRuntimeAIScan(rollback);
                        allConfigs.setEnableRuntimeAIScan(runtimeAI);
                    }
                    cfgForm.setMonitorConfigOptions(
                            BizappUtils.buildLoadConfigOptions(prefix, schemas[i], newConfigs[i]));
                    break;

                case ProductPlugin.CFGTYPE_IDX_CONTROL:
                    cfgForm.setControlConfigOptions(
                            BizappUtils.buildLoadConfigOptions(prefix, schemas[i], newConfigs[i]));
                    break;

                case ProductPlugin.CFGTYPE_IDX_RESPONSE_TIME:
                    // enable the RT metrics based on input from ui
                    allConfigs.setEnableServiceRT(cfgForm.getServiceRTEnabled());
                    allConfigs.setEnableEuRT(cfgForm.getEuRTEnabled());
                    cfgForm.setRtConfigOptions(
                            BizappUtils.buildLoadConfigOptions(prefix, schemas[i], newConfigs[i]));
                    break;
                }
            }
        }

        // call the uber setter in the AppdefBoss
        appdefBoss.setAllConfigResponses(sessionInt, allConfigs, allConfigsRollback);

        RequestUtils.setConfirmation(request,
                "resource." + aeid.getTypeName() + ".inventory.confirm.EditConfigProperties",
                updatedResource.getName());

        // HACK to redirect back to Problem Resources portlet if the
        // request originated there.
        if (request.getParameter("todash") != null) {
            return mapping.findForward("dash");
        }
        return returnSuccess(request, mapping, forwardParams);
    } catch (InvalidConfigException e) {
        log.error("Invalid config " + e);
        RequestUtils.setErrorWithNullCheck(request, e, ERR_NOMSG, ERR_CONFIG);
        cfgForm.validationErrors = true;
        return returnFailure(request, mapping);
    } catch (InvalidOptionValueException e) {
        log.error("Invalid config " + e);
        RequestUtils.setErrorWithNullCheck(request, e, ERR_NOMSG, ERR_CONFIG);
        return returnFailure(request, mapping);
    } catch (ConfigFetchException e) {
        log.error("General configuration set error " + e, e);
        RequestUtils.setErrorWithNullCheck(request, e, ERR_NOMSG, ERR_CONFIG);
        cfgForm.validationErrors = true;
        return returnFailure(request, mapping);
    } catch (EncodingException e) {
        log.error("Encoding error " + e);
        RequestUtils.setErrorWithNullCheck(request, e, ERR_NOMSG, ERR_CONFIG);
        cfgForm.validationErrors = true;
        return returnFailure(request, mapping);
    } catch (PluginNotFoundException e) {
        log.error("Plugin not found " + e);
        RequestUtils.setErrorObject(request, "resource.common.inventory.error.PluginNotFound", e.getMessage());
        return returnFailure(request, mapping);
    } catch (PluginException e) {
        log.error("Exception occured in plugin " + e);
        RequestUtils.setErrorObject(request, "resource.common.inventory.error.agentNotReachable",
                e.getMessage());
        cfgForm.validationErrors = true;
        return returnFailure(request, mapping);
    }
}

From source file:org.openbravo.advpaymentmngt.utility.FIN_Utility.java

/**
 * Returns a list of Payment Status. If isConfirmed equals true, then the status returned are
 * confirmed payments. Else they are pending of execution
 * /*from w w w .  j  a  va2s .  c om*/
 */
private static List<String> getListPaymentConfirmedOrNot(Boolean isConfirmed, FIN_PaymentScheduleDetail psd) {

    List<String> listPaymentConfirmedOrNot = new ArrayList<String>();
    OBContext.setAdminMode(true);
    try {
        final OBCriteria<org.openbravo.model.ad.domain.List> obCriteria = OBDal.getInstance()
                .createCriteria(org.openbravo.model.ad.domain.List.class);
        obCriteria.add(Restrictions.eq(org.openbravo.model.ad.domain.List.PROPERTY_REFERENCE + ".id",
                "575BCB88A4694C27BC013DE9C73E6FE7"));
        List<org.openbravo.model.ad.domain.List> adRefList = obCriteria.list();
        for (org.openbravo.model.ad.domain.List adRef : adRefList) {
            if (isConfirmed.equals(isPaymentConfirmed(adRef.getSearchKey(), psd))) {
                listPaymentConfirmedOrNot.add(adRef.getSearchKey());
            }
        }
        return listPaymentConfirmedOrNot;
    } catch (Exception e) {
        log4j.error("Error building the payment confirmed list", e);
        return null;
    } finally {
        OBContext.restorePreviousMode();
    }
}

From source file:org.medici.bia.service.admin.AdminServiceImpl.java

/**
 * {@inheritDoc}/*  w  ww .  j a  v  a 2 s  .c  om*/
 */
@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
@Override
public void createAccessLogDailyStatistics(Date dateSelected) throws ApplicationThrowable {

    try {
        Integer statisticsDeleted = getAccessLogStatisticsDAO().deleteStatisticsOnDay(dateSelected);

        logger.info("Removed " + statisticsDeleted + " on date " + dateSelected);

        Boolean status = getAccessLogStatisticsDAO().generateStatisticsOnDay(dateSelected);

        if (status.equals(Boolean.TRUE)) {
            logger.info(" Statistics on date " + dateSelected + " successfully created.");
        } else {
            logger.error(" Statistics on date " + dateSelected + " not created.");
        }
    } catch (Throwable th) {
        logger.error(" Statistics on date " + dateSelected + " not created.");
        throw new ApplicationThrowable(th);
    }

}

From source file:org.apache.sentry.api.service.thrift.SentryPolicyServiceClientDefaultImpl.java

private TSentryGrantOption convertTSentryGrantOption(Boolean grantOption) {
    if (grantOption == null) {
        return TSentryGrantOption.UNSET;
    } else if (grantOption.equals(true)) {
        return TSentryGrantOption.TRUE;
    } else if (grantOption.equals(false)) {
        return TSentryGrantOption.FALSE;
    }/*from   ww w . j  av a  2s  . c o  m*/
    return TSentryGrantOption.FALSE;
}

From source file:org.apache.roller.weblogger.business.jpa.JPAWeblogManagerImpl.java

/**
 * Return website specified by handle./*from  w w  w .j  av a  2s . c  om*/
 */
public Weblog getWeblogByHandle(String handle, Boolean enabled) throws WebloggerException {

    if (handle == null)
        throw new WebloggerException("Handle cannot be null");

    // check cache first
    // NOTE: if we ever allow changing handles then this needs updating
    if (this.weblogHandleToIdMap.containsKey(handle)) {

        Weblog weblog = this.getWeblog((String) this.weblogHandleToIdMap.get(handle));
        if (weblog != null) {
            // only return weblog if enabled status matches
            if (enabled == null || enabled.equals(weblog.getEnabled())) {
                log.debug("weblogHandleToId CACHE HIT - " + handle);
                return weblog;
            }
        } else {
            // mapping hit with lookup miss?  mapping must be old, remove it
            this.weblogHandleToIdMap.remove(handle);
        }
    }

    Query query = strategy.getNamedQuery("Weblog.getByHandle");
    query.setParameter(1, handle);
    Weblog website = null;
    try {
        website = (Weblog) query.getSingleResult();
    } catch (NoResultException e) {
        website = null;
    }

    // add mapping to cache
    if (website != null) {
        log.debug("weblogHandleToId CACHE MISS - " + handle);
        this.weblogHandleToIdMap.put(website.getHandle(), website.getId());
    }

    if (website != null && (enabled == null || enabled.equals(website.getEnabled()))) {
        return website;
    } else {
        return null;
    }
}

From source file:org.forgerock.openam.authentication.modules.impersonation.ImpersonationModule.java

/**
 * {@inheritDoc}//from w w w.  j  a  v a2  s  .  co  m
 */
@Override
public int process(Callback[] callbacks, int state) throws LoginException {

    System.out.println("INSIDE process of ImpersonationModule, state: " + state);

    if (debug.messageEnabled()) {
        debug.message("ImpersonationModule::process state: " + state);
    }
    int nextState = ISAuthConstants.LOGIN_SUCCEED;
    switch (state) {
    case 4:
        System.out.println("state 4");
        // error condition, show page
        throw new AuthLoginException("Incorrect authorization!");
    case 1:
        substituteUIStrings();
        //nextState = ISAuthConstants.LOGIN_SUCCEED;
        nextState = 2;
        break;
    case 3:
        userName = ((NameCallback) callbacks[0]).getName();
        String userPassword = String.valueOf(((PasswordCallback) callbacks[1]).getPassword());
        if (userPassword == null || userPassword.length() == 0) {
            if (debug.messageEnabled()) {
                debug.message("Impersonation.process: Password is null/empty");
            }
            throw new InvalidPasswordException("amAuth", "invalidPasswd", null);
        }
        //store username password both in success and failure case
        storeUsernamePasswd(userName, userPassword);

        AMIdentityRepository idrepo = getAMIdentityRepository(getRequestOrg());
        Callback[] idCallbacks = new Callback[2];
        try {
            idCallbacks = callbacks;
            boolean success = idrepo.authenticate(idCallbacks);
            // proceed if admin authenticated
            if (success) {

                validatedUserID = null;
                // 1. Search for group membership
                if (checkGroupMembership.equalsIgnoreCase("true")) {

                    AMIdentity amIdentity = getGroupIdentity(groupName);
                    Set<String> attr = (Set<String>) amIdentity.getAttribute("uniqueMember");
                    Iterator<String> i = attr.iterator();
                    // check if sign on user is memberof group 
                    while (i.hasNext()) {
                        try {
                            String member = (String) i.next();
                            System.out.println("value of attribute: " + member);
                            // check previously authenticated user is a memberof
                            userName = (String) sharedState.get(getUserKey());
                            System.out.println("userName to check: " + userName);
                            if (member.indexOf(userName) != -1) {
                                System.out.println("match found! admin: " + userName
                                        + " allowed to impersonate user: " + userResponse);

                                // for sanity, ensure the supplied userid is a valid one
                                try {
                                    validatedUserID = userResponse; // create session for the userid provided by admin 
                                    AMIdentity impersonatedId = getIdentity(validatedUserID);
                                    // optionally, we default to LOGIN_SUCCEED
                                    //nextState = ISAuthConstants.LOGIN_SUCCEED;

                                } catch (Exception ex) {
                                    System.out.println("Exception thrown validating impersonated userid " + ex);
                                    throw new AuthLoginException(
                                            "EImpersonationModule: Exception thrown validating impersonated userid");
                                }
                                break;
                            }
                        } catch (Exception e) {
                            System.out.println("Cannot parse json. " + e);
                            throw new AuthLoginException(
                                    "Cannot parse json..unable to read attribtue value using amIdentity");
                        }
                    }
                    if (checkGroupMembership.equalsIgnoreCase("true") && validatedUserID == null) {
                        // Admin was not authorized to impersonate other users
                        nextState = 4;
                        throw new AuthLoginException("Admin was not authorized to impersonate other users");
                    }
                }

                // 2. Check for policy evaluation
                // get the ssoToken first, for use with the REST call
                String url = openamServer + "/json/" + authnRealm + "/authenticate";
                HttpClient httpClient = HttpClientBuilder.create().build();
                HttpPost postRequest = new HttpPost(url);
                String cookie = "";
                try {

                    System.out.println("BEFORE policy1 eval...");

                    postRequest.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");

                    // TBD: replace with admin provided username and password- stick this code into the impersonate auth module
                    postRequest.setHeader("X-OpenAM-Username", userName);
                    postRequest.setHeader("X-OpenAM-Password", userPassword);

                    StringEntity input = new StringEntity("{}");
                    input.setContentType("application/json");
                    postRequest.setEntity(input);

                    HttpResponse response = httpClient.execute(postRequest);

                    String json = EntityUtils.toString(response.getEntity(), "UTF-8");
                    System.out.println("json/" + authnRealm + "/authenticate response-> " + json);
                    try {
                        JSONParser parser = new JSONParser();
                        Object resultObject = parser.parse(json);

                        if (resultObject instanceof JSONArray) {
                            JSONArray array = (JSONArray) resultObject;
                            for (Object object : array) {
                                JSONObject obj = (JSONObject) object;
                                System.out.println("jsonarray-> " + obj);
                            }

                        } else if (resultObject instanceof JSONObject) {
                            JSONObject obj = (JSONObject) resultObject;
                            System.out.println("tokenId-> " + obj.get("tokenId"));
                            cookie = (String) obj.get("tokenId");
                        }

                    } catch (Exception e) {
                        // TODO: handle exception
                        nextState = 4;
                    }
                    System.out.println("AFTER policy1 eval...");
                    // Headers
                    org.apache.http.Header[] headers = response.getAllHeaders();
                    for (int j = 0; j < headers.length; j++) {
                        System.out.println(headers[j]);
                    }

                } catch (Exception e) {
                    System.err.println("Fatal  error: " + e.getMessage());
                    e.printStackTrace();
                    nextState = 4;
                }

                System.out.println("BEFORE policy2 eval...");

                /*Cookie[] cookies = getHttpServletRequest().getCookies();
                        
                        
                if (cookies != null) {
                  for (int m = 0; m < cookies.length; m++) {
                     System.out.println(cookies[m].getName() +":"+cookies[m].getValue());
                    if (cookies[m].getName().equalsIgnoreCase("iPlanetDirectoryPro")) {
                      cookie = cookies[m].getValue();
                      break;
                    }
                  }
                }*/
                url = openamServer + "/json/" + policyRealm + "/policies?_action=evaluate";
                //httpClient = HttpClientBuilder.create().build();
                postRequest = new HttpPost(url);
                try {

                    postRequest.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
                    postRequest.setHeader("iPlanetDirectoryPro", cookie);

                    StringEntity input = new StringEntity(
                            "{\"resources\": [\"" + new URL(resourceSet) + "\"],\"application\":\"" + policySet
                                    + "\", \"subject\": {\"ssoToken\":\"" + cookie + "\"}}");

                    System.out.println("stringentity-> " + getStringFromInputStream(input.getContent()));
                    input.setContentType("application/json");
                    postRequest.setEntity(input);

                    HttpResponse response = httpClient.execute(postRequest);

                    String json = EntityUtils.toString(response.getEntity(), "UTF-8");
                    System.out.println("json/" + policyRealm + "/policies?_action=evaluate response-> " + json);
                    try {
                        JSONParser parser = new JSONParser();
                        Object resultObject = parser.parse(json);

                        if (resultObject instanceof JSONArray) {
                            JSONArray array = (JSONArray) resultObject;
                            for (Object object : array) {
                                JSONObject obj = (JSONObject) object;
                                System.out.println("jsonarray-> " + obj);

                                JSONObject actions = (JSONObject) obj.get("actions");
                                Boolean actionGet = (Boolean) actions.get("GET");
                                Boolean actionPost = (Boolean) actions.get("POST");
                                System.out.println("actionGet : " + actionGet);
                                System.out.println("actionPost : " + actionPost);

                                if (actionGet != null && actionGet.equals(true) && actionPost != null
                                        && actionPost.equals(true)) {
                                    nextState = ISAuthConstants.LOGIN_SUCCEED;
                                } else {
                                    System.out.println("actionget and actionpost are not true");
                                    nextState = 4;
                                }
                            }

                        } else {
                            // something went wrong!
                            System.out.println("resultObject is not a JSONArray");
                            nextState = 4;
                        }

                    } catch (Exception e) {
                        // TODO: handle exception
                        nextState = 4;
                        System.out.println("exception invoking json parsing routine");
                        e.printStackTrace();
                    }
                    System.out.println("AFTER policy2 eval...");
                    // Headers
                    org.apache.http.Header[] headers = response.getAllHeaders();
                    for (int j = 0; j < headers.length; j++) {
                        System.out.println(headers[j]);
                    }

                    // logout the administrator
                    url = openamServer + "/json/" + authnRealm + "/sessions/?_action=logout";
                    System.out.println("destroying admin session: " + url);
                    postRequest = new HttpPost(url);
                    try {
                        postRequest.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
                        postRequest.setHeader("iPlanetDirectoryPro", cookie);
                        response = httpClient.execute(postRequest);
                        try {
                            JSONParser parser = new JSONParser();
                            Object resultObject = parser.parse(json);
                            if (resultObject instanceof JSONArray) {
                                JSONArray array = (JSONArray) resultObject;
                                for (Object object : array) {
                                    JSONObject obj = (JSONObject) object;
                                    System.out.println("logout response-array-> " + obj);
                                }
                            } else {
                                JSONObject obj = (JSONObject) resultObject;
                                System.out.println("logout response-> " + obj);
                            }
                        } catch (Exception e) {
                            System.out.println("unable to read logout json response");
                            e.printStackTrace();
                        }

                    } catch (Exception e) {
                        System.out.println(
                                "Issue destroying administrator's session, still proceeding with impersonation");
                        e.printStackTrace();

                    }

                } catch (Exception e) {
                    System.err.println("Fatal  error: " + e.getMessage());
                    e.printStackTrace();
                    nextState = 4;
                }

                // else of admin successful login   
            } else {
                System.out.println("username:password read from callback: " + userName + " : " + userPassword);
                nextState = 4;
                throw new AuthLoginException(amAuthImpersonation, "authFailed", null);
            }
        } catch (com.sun.identity.idm.IdRepoException idrepox) {
            System.out.println("IdRepoException thrown " + idrepox);
            nextState = 4;
            throw new AuthLoginException("IdRepoException thrown from Impersonation module");
        } catch (SSOException ssoe) {
            System.out.println("SSOException thrown " + ssoe);
            nextState = 4;
            throw new AuthLoginException("SSOException thrown from ImpersonationModule module");
        }

        break;
    case 2:
        javax.security.auth.callback.NameCallback response = (javax.security.auth.callback.NameCallback) callbacks[0];
        userResponse = new String(response.getName());
        // check the response against OpenDJ
        System.out.println("user to impersonate : state 2: " + userResponse);

        nextState = 3;

        break;
    default:
        throw new AuthLoginException("invalid state");

    }
    return nextState;
}

From source file:com.clustercontrol.repository.factory.FacilitySelector.java

/**
 * ???ID?/??????<BR>// www. j  av  a  2s .  co m
 * parentFacilityId??????ID?
 * parentFacilityId??????ArrayList?
 * 
 * @param parentFacilityId ?ID
 * @param ownerRoleId ID
 * @param level ??
 * @param sort ID???true, ?????false
 * @param validFlg /?
 * @return ID??
 * @throws FacilityNotFound
 */
public static ArrayList<String> getNodeFacilityIdList(String parentFacilityId, String ownerRoleId, int level,
        boolean sort, Boolean validFlg) {
    /**  */
    ArrayList<String> facilityIdList = null;
    ArrayList<FacilityInfo> facilityList = null;

    /** ? */
    facilityList = getFacilityList(parentFacilityId, ownerRoleId, level, false);

    facilityIdList = new ArrayList<String>();
    if (facilityList != null) {
        for (FacilityInfo facility : facilityList) {
            if (facility.getFacilityType() == FacilityConstant.TYPE_NODE) {
                if (validFlg == null || validFlg.equals(facility.getValid())) {
                    facilityIdList.add(facility.getFacilityId());
                }
            }
        }
    }

    if (sort) {
        Collections.sort(facilityIdList);
    }

    return facilityIdList;
}

From source file:org.apache.roller.weblogger.business.jpa.JPAUserManagerImpl.java

public User getUserByUserName(String userName, Boolean enabled) throws WebloggerException {

    if (userName == null)
        throw new WebloggerException("userName cannot be null");

    // check cache first
    // NOTE: if we ever allow changing usernames then this needs updating
    if (this.userNameToIdMap.containsKey(userName)) {

        User user = this.getUser((String) this.userNameToIdMap.get(userName));
        if (user != null) {
            // only return the user if the enabled status matches
            if (enabled == null || enabled.equals(user.getEnabled())) {
                log.debug("userNameToIdMap CACHE HIT - " + userName);
                return user;
            }//from  w  ww. j av a  2 s.  co m
        } else {
            // mapping hit with lookup miss?  mapping must be old, remove it
            this.userNameToIdMap.remove(userName);
        }
    }

    // cache failed, do lookup
    Query query;
    Object[] params;
    if (enabled != null) {
        query = strategy.getNamedQuery("User.getByUserName&Enabled");
        params = new Object[] { userName, enabled };
    } else {
        query = strategy.getNamedQuery("User.getByUserName");
        params = new Object[] { userName };
    }
    for (int i = 0; i < params.length; i++) {
        query.setParameter(i + 1, params[i]);
    }
    User user = null;
    try {
        user = (User) query.getSingleResult();
    } catch (NoResultException e) {
        user = null;
    }

    // add mapping to cache
    if (user != null) {
        log.debug("userNameToIdMap CACHE MISS - " + userName);
        this.userNameToIdMap.put(user.getUserName(), user.getId());
    }

    return user;
}

From source file:no.abmu.questionnaire.service.QuestionnaireServiceHelperH3Impl.java

private void boolFromSubReportDataToJasperReport(Map<String, Object> m, SubSchemaData subSchemaData,
        int startIndex, int stopIndex) {

    String fieldName;/*  w  w  w . j  a v a 2 s  . c  om*/
    BooleanFieldData booleanFieldData;
    Boolean booleanFieldDataValue;
    Boolean yes = true;
    Boolean no = false;

    for (int i = startIndex; i <= stopIndex; i++) {
        fieldName = intTo2DigitString(i);
        booleanFieldData = (BooleanFieldData) subSchemaData.getFieldData(fieldName);

        if (booleanFieldData != null) {
            booleanFieldDataValue = booleanFieldData.getValue();
            if (booleanFieldDataValue != null) {
                if (booleanFieldDataValue.equals(yes)) {
                    m.put(fieldName, "Ja");
                } else if (booleanFieldDataValue.equals(no)) {
                    m.put(fieldName, "Nei");
                }
            }
        }
    }
}