Example usage for org.springframework.util ObjectUtils nullSafeEquals

List of usage examples for org.springframework.util ObjectUtils nullSafeEquals

Introduction

In this page you can find the example usage for org.springframework.util ObjectUtils nullSafeEquals.

Prototype

public static boolean nullSafeEquals(@Nullable Object o1, @Nullable Object o2) 

Source Link

Document

Determine if the given objects are equal, returning true if both are null or false if only one is null .

Usage

From source file:org.kuali.kfs.sec.document.SecurityModelMaintainableImpl.java

/**
 * Iterates through the model definition list and assigns the model role to the definition role if necessary or updates the
 * current member assignment//from w  w w  .  ja v a 2s. c om
 *
 * @param oldSecurityModel SecurityModel record before updates
 * @param newSecurityModel SecurityModel whose membership should be updated
 * @param newMaintenanceAction boolean indicating whether this is a new record (old side will not contain data)
 */
protected void assignOrUpdateModelMembershipToDefinitionRoles(Role modelRole, SecurityModel oldSecurityModel,
        SecurityModel newSecurityModel, boolean newMaintenanceAction) {
    RoleService roleService = KimApiServiceLocator.getRoleService();

    if (modelRole == null) {
        LOG.error("Model Role does not exist for SecurityModel: " + newSecurityModel);
        throw new RuntimeException("Model Role does not exist for SecurityModel: " + newSecurityModel);
    }

    for (SecurityModelDefinition securityModelDefinition : newSecurityModel.getModelDefinitions()) {
        SecurityDefinition securityDefinition = securityModelDefinition.getSecurityDefinition();

        Role definitionRole = roleService.getRole(securityDefinition.getRoleId());

        if (definitionRole == null) {
            LOG.error("Definition Role does not exist for SecurityModelDefinition: " + securityDefinition);
            throw new RuntimeException(
                    "Definition Role does not exist for SecurityModelDefinition: " + securityDefinition);
        }

        RoleMember modelRoleMembership = null;
        if (!newMaintenanceAction) {
            SecurityModelDefinition oldSecurityModelDefinition = null;
            for (SecurityModelDefinition modelDefinition : oldSecurityModel.getModelDefinitions()) {
                if (ObjectUtils.nullSafeEquals(modelDefinition.getModelDefinitionId(),
                        securityModelDefinition.getModelDefinitionId())) {
                    oldSecurityModelDefinition = modelDefinition;
                    break;
                }
            }

            if (oldSecurityModelDefinition != null) {
                modelRoleMembership = getRoleMembershipForMemberType(definitionRole.getId(), modelRole.getId(),
                        MemberType.ROLE.getCode(),
                        getRoleQualifiersFromSecurityModelDefinition(oldSecurityModelDefinition));
            }
        }

        // only create membership if model is active and the model definition record is active
        boolean membershipActive = newSecurityModel.isActive() && securityModelDefinition.isActive();

        // if membership already exists, need to remove if the model definition record is now inactive or the qualifications
        // need updated
        if (modelRoleMembership != null) {
            if (!membershipActive) {
                roleService.removeRoleFromRole(modelRoleMembership.getMemberId(),
                        definitionRole.getNamespaceCode(), definitionRole.getName(),
                        modelRoleMembership.getAttributes());
            }
        }

        // create of update role if membership should be active
        if (membershipActive) {
            if (modelRoleMembership == null) {
                modelRoleMembership = roleService.assignRoleToRole(modelRole.getId(),
                        definitionRole.getNamespaceCode(), definitionRole.getName(),
                        getRoleQualifiersFromSecurityModelDefinition(securityModelDefinition));
            } else {
                RoleMember.Builder updatedRoleMember = RoleMember.Builder.create(modelRoleMembership);
                updatedRoleMember.setActiveToDate(null);
                updatedRoleMember
                        .setAttributes(getRoleQualifiersFromSecurityModelDefinition(securityModelDefinition));
                modelRoleMembership = roleService.updateRoleMember(updatedRoleMember.build());
            }
        }
    }
}

From source file:org.openmrs.Concept.java

/**
 * Returns the name which is explicitly marked as preferred for a given locale.
 * /*  ww  w  .  j  av a2s . c om*/
 * @param forLocale locale for which to return a preferred name
 * @return preferred name for the locale, or null if no preferred name is specified
 * @should return the concept name explicitly marked as locale preferred
 * @should return the fully specified name if no name is explicitly marked as locale preferred
 */
public ConceptName getPreferredName(Locale forLocale) {

    if (log.isDebugEnabled()) {
        log.debug("Getting preferred conceptName for locale: " + forLocale);
    }
    // fail early if this concept has no names defined
    if (getNames(forLocale).size() == 0) {
        if (log.isDebugEnabled()) {
            log.debug("there are no names defined for concept with id: " + conceptId + " in the  locale: "
                    + forLocale);
        }
        return null;
    } else if (forLocale == null) {
        log.warn("Locale cannot be null");
        return null;
    }

    for (ConceptName nameInLocale : getNames(forLocale)) {
        if (ObjectUtils.nullSafeEquals(nameInLocale.isLocalePreferred(), true)) {
            return nameInLocale;
        }
    }

    // look for partially locale match - any language matches takes precedence over country matches.
    ConceptName bestMatch = null;

    for (ConceptName nameInLocale : getPartiallyCompatibleNames(forLocale)) {
        if (ObjectUtils.nullSafeEquals(nameInLocale.isLocalePreferred(), true)) {
            Locale nameLocale = nameInLocale.getLocale();
            if (forLocale.getLanguage().equals(nameLocale.getLanguage())) {
                return nameInLocale;
            } else {
                bestMatch = nameInLocale;
            }

        }
    }

    if (bestMatch != null) {
        return bestMatch;
    }

    return getFullySpecifiedName(forLocale);
}

From source file:org.openmrs.Concept.java

/**
 * Convenience method that returns the fully specified name in the locale
 * /*from  w  w  w.  ja  va 2  s  . c o  m*/
 * @param locale locale from which to look up the fully specified name
 * @return the name explicitly marked as fully specified for the locale
 * @should return the name marked as fully specified for the given locale
 */
public ConceptName getFullySpecifiedName(Locale locale) {
    if (locale != null && getNames(locale).size() > 0) {
        //get the first fully specified name, since every concept must have a fully specified name,
        //then, this loop will have to return a name
        for (ConceptName conceptName : getNames(locale)) {
            if (ObjectUtils.nullSafeEquals(conceptName.isFullySpecifiedName(), true)) {
                return conceptName;
            }
        }

        // look for partially locale match - any language matches takes precedence over country matches.
        ConceptName bestMatch = null;
        for (ConceptName conceptName : getPartiallyCompatibleNames(locale)) {
            if (ObjectUtils.nullSafeEquals(conceptName.isFullySpecifiedName(), true)) {
                Locale nameLocale = conceptName.getLocale();
                if (locale.getLanguage().equals(nameLocale.getLanguage())) {
                    return conceptName;
                }
                bestMatch = conceptName;
            }
        }
        return bestMatch;

    }
    return null;
}

From source file:org.opennms.netmgt.poller.remote.support.ScanReportPollerFrontEnd.java

private static boolean nullSafeEquals(final Object oldValue, final Object newValue) {
    return (oldValue == newValue ? true : ObjectUtils.nullSafeEquals(oldValue, newValue));
}

From source file:org.springframework.aop.aspectj.AspectJExpressionPointcut.java

@Override
public boolean equals(Object other) {
    if (this == other) {
        return true;
    }//w  w w . j a v  a 2  s .  c  o m
    if (!(other instanceof AspectJExpressionPointcut)) {
        return false;
    }
    AspectJExpressionPointcut otherPc = (AspectJExpressionPointcut) other;
    return ObjectUtils.nullSafeEquals(this.getExpression(), otherPc.getExpression())
            && ObjectUtils.nullSafeEquals(this.pointcutDeclarationScope, otherPc.pointcutDeclarationScope)
            && ObjectUtils.nullSafeEquals(this.pointcutParameterNames, otherPc.pointcutParameterNames)
            && ObjectUtils.nullSafeEquals(this.pointcutParameterTypes, otherPc.pointcutParameterTypes);
}

From source file:org.springframework.aop.target.AbstractBeanFactoryBasedTargetSource.java

@Override
public boolean equals(Object other) {
    if (this == other) {
        return true;
    }/*from w  w  w  .jav a 2s  .  c om*/
    if (other == null || getClass() != other.getClass()) {
        return false;
    }
    AbstractBeanFactoryBasedTargetSource otherTargetSource = (AbstractBeanFactoryBasedTargetSource) other;
    return (ObjectUtils.nullSafeEquals(this.beanFactory, otherTargetSource.beanFactory)
            && ObjectUtils.nullSafeEquals(this.targetBeanName, otherTargetSource.targetBeanName));
}

From source file:org.springframework.cache.interceptor.NameMatchCacheOperationSource.java

@Override
public boolean equals(Object other) {
    if (this == other) {
        return true;
    }/*from www . ja va  2 s.  c  o m*/
    if (!(other instanceof NameMatchCacheOperationSource)) {
        return false;
    }
    NameMatchCacheOperationSource otherTas = (NameMatchCacheOperationSource) other;
    return ObjectUtils.nullSafeEquals(this.nameMap, otherTas.nameMap);
}

From source file:org.springframework.cloud.deployer.spi.yarn.YarnAppDeployer.java

@Override
public String deploy(AppDeploymentRequest request) {
    logger.info("Deploy request for {}", request);
    final AppDefinition definition = request.getDefinition();
    Map<String, String> definitionParameters = definition.getProperties();
    Map<String, String> deploymentProperties = request.getDeploymentProperties();
    logger.info("Deploying request for definition {}", definition);
    logger.info("Parameters for definition {}", definitionParameters);
    logger.info("Deployment properties for request {}", deploymentProperties);

    int count = 1;
    String countString = request.getDeploymentProperties().get(AppDeployer.COUNT_PROPERTY_KEY);
    if (StringUtils.hasText(countString)) {
        count = Integer.parseInt(countString);
    }//from  w w w . ja  va  2  s . com
    final String group = request.getDeploymentProperties().get(AppDeployer.GROUP_PROPERTY_KEY);
    Resource resource = request.getResource();
    final String clusterId = group + ":" + definition.getName();

    // contextRunArgs are passed to boot app ran to control yarn apps
    ArrayList<String> contextRunArgs = new ArrayList<String>();
    contextRunArgs.add("--spring.yarn.appName=scdstream:app:" + group);

    // deployment properties override servers.yml which overrides application.yml
    for (Entry<String, String> entry : deploymentProperties.entrySet()) {
        if (entry.getKey().startsWith("spring.cloud.deployer.yarn.app.streamappmaster")) {
            contextRunArgs.add("--" + entry.getKey() + "=" + entry.getValue());
        } else if (entry.getKey().startsWith("spring.cloud.deployer.yarn.app.streamcontainer")) {
            // weird format with '--' is just straight pass to appmaster
            contextRunArgs.add("--spring.yarn.client.launchcontext.arguments.--" + entry.getKey() + "='"
                    + entry.getValue() + "'");
        }
    }

    String baseDir = yarnDeployerProperties.getBaseDir();
    if (!baseDir.endsWith("/")) {
        baseDir = baseDir + "/";
    }

    String artifactPath = isHdfsResource(resource) ? getHdfsArtifactPath(resource)
            : baseDir + "/artifacts/cache/";
    contextRunArgs
            .add("--spring.yarn.client.launchcontext.arguments.--spring.cloud.deployer.yarn.appmaster.artifact="
                    + artifactPath);

    // TODO: using default app name "app" until we start to customise
    //       via deploymentProperties
    final Message<String> message = MessageBuilder.withPayload(AppDeployerStateMachine.EVENT_DEPLOY)
            .setHeader(AppDeployerStateMachine.HEADER_APP_VERSION, "app")
            .setHeader(AppDeployerStateMachine.HEADER_CLUSTER_ID, clusterId)
            .setHeader(AppDeployerStateMachine.HEADER_GROUP_ID, group)
            .setHeader(AppDeployerStateMachine.HEADER_COUNT, count)
            .setHeader(AppDeployerStateMachine.HEADER_ARTIFACT, resource)
            .setHeader(AppDeployerStateMachine.HEADER_ARTIFACT_DIR, artifactPath)
            .setHeader(AppDeployerStateMachine.HEADER_DEFINITION_PARAMETERS, definitionParameters)
            .setHeader(AppDeployerStateMachine.HEADER_CONTEXT_RUN_ARGS, contextRunArgs).build();

    // Use of future here is to set id when it becomes available from machine
    final SettableListenableFuture<String> id = new SettableListenableFuture<>();
    final StateMachineListener<String, String> listener = new StateMachineListenerAdapter<String, String>() {

        @Override
        public void stateContext(StateContext<String, String> stateContext) {
            if (stateContext.getStage() == Stage.STATE_ENTRY
                    && stateContext.getTarget().getId().equals(AppDeployerStateMachine.STATE_READY)) {
                if (ObjectUtils.nullSafeEquals(message.getHeaders().getId().toString(), stateContext
                        .getExtendedState().get(AppDeployerStateMachine.VAR_MESSAGE_ID, String.class))) {
                    Exception exception = stateContext.getExtendedState().get(AppDeployerStateMachine.VAR_ERROR,
                            Exception.class);
                    if (exception != null) {
                        id.setException(exception);
                    } else {
                        String applicationId = stateContext.getStateMachine().getExtendedState()
                                .get(AppDeployerStateMachine.VAR_APPLICATION_ID, String.class);
                        DeploymentKey key = new DeploymentKey(group, definition.getName(), applicationId);
                        id.set(key.toString());
                    }
                }
            }
        }
    };
    stateMachine.addStateListener(listener);
    id.addCallback(new ListenableFutureCallback<String>() {

        @Override
        public void onSuccess(String result) {
            stateMachine.removeStateListener(listener);
        }

        @Override
        public void onFailure(Throwable ex) {
            stateMachine.removeStateListener(listener);
        }
    });

    stateMachine.sendEvent(message);
    // we need to block here until SPI supports
    // returning id asynchronously
    try {
        return id.get(2, TimeUnit.MINUTES);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.springframework.cloud.deployer.spi.yarn.YarnAppDeployer.java

@Override
public AppStatus status(String id) {
    logger.info("Checking status of {}", id);
    DeploymentKey key = new DeploymentKey(id);
    Builder builder = AppStatus.of(id);/*from w  w  w .  ja va  2s  .  c o  m*/
    for (Entry<String, ClustersInfoReportData> entry : yarnCloudAppService.getClustersStates(key.applicationId)
            .entrySet()) {
        if (ObjectUtils.nullSafeEquals(entry.getKey(), key.getClusterId())) {
            ClustersInfoReportData data = entry.getValue();
            for (int i = 0; i < data.getProjectionAny(); i++) {
                InstanceStatus instanceStatus = new InstanceStatus(key.getClusterId() + "-" + i,
                        i < data.getCount(), null);
                builder.with(instanceStatus);
            }
            break;
        }
    }
    return builder.build();
}

From source file:org.springframework.cloud.deployer.spi.yarn.YarnTaskLauncher.java

@Override
public String launch(AppDeploymentRequest request) {
    logger.info("Deploy request for {}", request);
    logger.info("Deploy request deployment properties {}", request.getDeploymentProperties());
    logger.info("Deploy definition {}", request.getDefinition());
    Resource resource = request.getResource();
    AppDefinition definition = request.getDefinition();

    String artifact = resource.getFilename();

    final String name = definition.getName();
    Map<String, String> definitionParameters = definition.getProperties();
    Map<String, String> deploymentProperties = request.getDeploymentProperties();
    List<String> commandlineArguments = request.getCommandlineArguments();
    String appName = "scdtask:" + name;

    // contextRunArgs are passed to boot app ran to control yarn apps
    // we pass needed args to control module coordinates and params,
    // weird format with '--' is just straight pass to container
    ArrayList<String> contextRunArgs = new ArrayList<String>();

    contextRunArgs.add("--spring.yarn.appName=" + appName);
    for (Entry<String, String> entry : definitionParameters.entrySet()) {
        if (StringUtils.hasText(entry.getValue())) {
            contextRunArgs.add(/*from   www  . j  a va 2s .c o  m*/
                    "--spring.yarn.client.launchcontext.arguments.--spring.cloud.deployer.yarn.appmaster.parameters."
                            + entry.getKey() + ".='" + entry.getValue() + "'");
        }
    }

    int index = 0;
    for (String commandlineArgument : commandlineArguments) {
        contextRunArgs.add("--spring.yarn.client.launchcontext.argumentsList[" + index
                + "]='--spring.cloud.deployer.yarn.appmaster.commandlineArguments[" + index + "]="
                + commandlineArgument + "'");
        index++;
    }

    String baseDir = yarnDeployerProperties.getBaseDir();
    if (!baseDir.endsWith("/")) {
        baseDir = baseDir + "/";
    }
    String artifactPath = isHdfsResource(resource) ? getHdfsArtifactPath(resource)
            : baseDir + "/artifacts/cache/";

    contextRunArgs.add(
            "--spring.yarn.client.launchcontext.arguments.--spring.yarn.appmaster.launchcontext.archiveFile="
                    + artifact);
    contextRunArgs
            .add("--spring.yarn.client.launchcontext.arguments.--spring.cloud.deployer.yarn.appmaster.artifact="
                    + artifactPath + artifact);

    // deployment properties override servers.yml which overrides application.yml
    for (Entry<String, String> entry : deploymentProperties.entrySet()) {
        if (StringUtils.hasText(entry.getValue())) {
            if (entry.getKey().startsWith("spring.cloud.deployer.yarn.app.taskcontainer")) {
                contextRunArgs.add("--spring.yarn.client.launchcontext.arguments.--" + entry.getKey() + "='"
                        + entry.getValue() + "'");
            } else if (entry.getKey().startsWith("spring.cloud.deployer.yarn.app.taskappmaster")) {
                contextRunArgs.add("--" + entry.getKey() + "=" + entry.getValue());
            }
        }
    }

    final Message<String> message = MessageBuilder.withPayload(TaskLauncherStateMachine.EVENT_LAUNCH)
            .setHeader(TaskLauncherStateMachine.HEADER_APP_VERSION, "app")
            .setHeader(TaskLauncherStateMachine.HEADER_ARTIFACT, resource)
            .setHeader(TaskLauncherStateMachine.HEADER_ARTIFACT_DIR, artifactPath)
            .setHeader(TaskLauncherStateMachine.HEADER_DEFINITION_PARAMETERS, definitionParameters)
            .setHeader(TaskLauncherStateMachine.HEADER_CONTEXT_RUN_ARGS, contextRunArgs).build();

    // setup future, listen event from machine and finally unregister listener,
    // and set future value
    final SettableListenableFuture<String> id = new SettableListenableFuture<>();
    final StateMachineListener<String, String> listener = new StateMachineListenerAdapter<String, String>() {

        @Override
        public void stateContext(StateContext<String, String> stateContext) {
            if (stateContext.getStage() == Stage.STATE_ENTRY
                    && stateContext.getTarget().getId().equals(TaskLauncherStateMachine.STATE_READY)) {
                if (ObjectUtils.nullSafeEquals(message.getHeaders().getId().toString(), stateContext
                        .getExtendedState().get(TaskLauncherStateMachine.VAR_MESSAGE_ID, String.class))) {
                    Exception exception = stateContext.getExtendedState()
                            .get(TaskLauncherStateMachine.VAR_ERROR, Exception.class);
                    if (exception != null) {
                        id.setException(exception);
                    } else {
                        String applicationId = stateContext.getStateMachine().getExtendedState()
                                .get(TaskLauncherStateMachine.VAR_APPLICATION_ID, String.class);
                        DeploymentKey key = new DeploymentKey(name, applicationId);
                        id.set(key.toString());
                    }
                }
            }
        }
    };

    stateMachine.addStateListener(listener);
    id.addCallback(new ListenableFutureCallback<String>() {

        @Override
        public void onSuccess(String result) {
            stateMachine.removeStateListener(listener);
        }

        @Override
        public void onFailure(Throwable ex) {
            stateMachine.removeStateListener(listener);
        }
    });

    stateMachine.sendEvent(message);
    // we need to block here until SPI supports
    // returning id asynchronously
    try {
        return id.get(2, TimeUnit.MINUTES);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}