Example usage for org.springframework.util StringUtils hasLength

List of usage examples for org.springframework.util StringUtils hasLength

Introduction

In this page you can find the example usage for org.springframework.util StringUtils hasLength.

Prototype

public static boolean hasLength(@Nullable String str) 

Source Link

Document

Check that the given String is neither null nor of length 0.

Usage

From source file:com.googlecode.ehcache.annotations.impl.CacheAttributeSourceImpl.java

/**
 * Get the {@link CacheResolverFactory} by name. Returning a default resolver factory if the name is empty or null
 * //  w  ww  . j  a  v  a2s . c om
 * @param resolverFactoryName Name of the resolver factory to retrieve
 * @return The named generator or the default generator if the name was empty or null
 */
protected final CacheResolverFactory getCacheResolverFactory(String resolverFactoryName,
        ResolverFactory resolverFactory) {
    String cacheResolverClassName = resolverFactory.name();
    if (cacheResolverClassName.length() > 0) {
        return this.getOrCreateCacheResolverFactory(resolverFactory);
    }

    if (StringUtils.hasLength(resolverFactoryName)) {
        return this.beanFactory.getBean(resolverFactoryName, CacheResolverFactory.class);
    }

    return this.cacheResolverFactory;
}

From source file:com.googlecode.ehcache.annotations.impl.CacheAttributeSourceImpl.java

/**
 * Get the {@link CacheKeyGenerator} by name. Returning a default generator if the name is empty or null
 * /*  w ww. j  a v a 2s. c om*/
 * @param keyGeneratorName Name of the generator to retrieve
 * @return The named generator or the default generator if the name was empty or null
 */
@SuppressWarnings("unchecked")
protected final CacheKeyGenerator<? extends Serializable> getCacheKeyGenerator(String keyGeneratorName,
        KeyGenerator keyGenerator) {
    String keyGeneratorClassName = keyGenerator.name();
    if (keyGeneratorClassName.length() > 0) {
        return this.getOrCreateCacheKeyGenerator(keyGenerator);
    }

    final CacheKeyGenerator<? extends Serializable> cacheKeyGenerator;
    if (StringUtils.hasLength(keyGeneratorName)) {
        cacheKeyGenerator = this.beanFactory.getBean(keyGeneratorName, CacheKeyGenerator.class);
    } else {
        cacheKeyGenerator = this.defaultCacheKeyGenerator;
    }
    return cacheKeyGenerator;
}

From source file:org.smf4j.spring.RegistryNodeTemplateDefinitionParser.java

protected String createRangeGroup(ParserContext context, Element element) {
    String name = getName(context, element);
    String accumulator = element.getAttribute(ACCUMULATOR_ATTR);
    String units = element.getAttribute(UNITS_ATTR);
    String ranges = element.getAttribute(RANGES_ATTR);
    String suffixes = element.getAttribute(SUFFIXES_ATTR);
    String norm = element.getAttribute(NORMALIZE_ATTR);
    String freq = element.getAttribute(FREQUENCY_ATTR);
    String threshold = element.getAttribute(THRESHOLD_ATTR);
    String format = element.getAttribute(FORMAT_ATTR);

    ManagedList<RuntimeBeanReference> groupings = createGroupings(context, element, ranges, suffixes);
    if (groupings == null) {
        return null;
    }//from   ww  w.j a va 2  s . c  o  m

    boolean normalize = false;
    if (StringUtils.hasLength(norm)) {
        normalize = Boolean.parseBoolean(norm);
    }

    BeanDefinitionBuilder bdb = getBdb(RANGEGROUP_CLASS);
    bdb.addPropertyValue(UNITS_ATTR, units);
    bdb.addPropertyValue(GROUPINGS_ATTR, groupings);
    bdb.addPropertyValue(NORMALIZE_ATTR, normalize);
    Object frequency = getFrequency(context, element, freq);
    bdb.addPropertyValue(FREQUENCY_ATTR, frequency);
    bdb.addPropertyValue(ACCUMULATOR_ATTR, accumulator);
    bdb.addPropertyValue(THRESHOLD_ATTR, threshold);
    bdb.addPropertyValue(FORMATSTRING_ATTR, format);

    String grpId = context.getReaderContext().registerWithGeneratedName(bdb.getBeanDefinition());

    // Create proxy that carries name
    BeanDefinitionBuilder calcProxyBdb = getBdb(RegistryNodeChildProxy.class);
    calcProxyBdb.addPropertyValue(NAME_ATTR, name);
    calcProxyBdb.addPropertyValue(CHILD_ATTR, grpId);
    return context.getReaderContext().registerWithGeneratedName(calcProxyBdb.getBeanDefinition());
}

From source file:lib.JdbcTemplate.java

@Override
public int[] batchUpdate(final String... sql) throws DataAccessException {
    Assert.notEmpty(sql, "SQL array must not be empty");
    if (logger.isDebugEnabled()) {
        logger.debug("Executing SQL batch update of " + sql.length + " statements");
    }// w w  w. j  ava 2  s .  c  om

    class BatchUpdateStatementCallback implements StatementCallback<int[]>, SqlProvider {

        private String currSql;

        @Override
        public int[] doInStatement(Statement stmt) throws SQLException, DataAccessException {
            int[] rowsAffected = new int[sql.length];
            if (JdbcUtils.supportsBatchUpdates(stmt.getConnection())) {
                for (String sqlStmt : sql) {
                    this.currSql = appendSql(this.currSql, sqlStmt);
                    stmt.addBatch(sqlStmt);
                }
                try {
                    rowsAffected = stmt.executeBatch();
                } catch (BatchUpdateException ex) {
                    String batchExceptionSql = null;
                    for (int i = 0; i < ex.getUpdateCounts().length; i++) {
                        if (ex.getUpdateCounts()[i] == Statement.EXECUTE_FAILED) {
                            batchExceptionSql = appendSql(batchExceptionSql, sql[i]);
                        }
                    }
                    if (StringUtils.hasLength(batchExceptionSql)) {
                        this.currSql = batchExceptionSql;
                    }
                    throw ex;
                }
            } else {
                for (int i = 0; i < sql.length; i++) {
                    this.currSql = sql[i];
                    if (!stmt.execute(sql[i])) {
                        rowsAffected[i] = stmt.getUpdateCount();
                    } else {
                        throw new InvalidDataAccessApiUsageException("Invalid batch SQL statement: " + sql[i]);
                    }
                }
            }
            return rowsAffected;
        }

        private String appendSql(String sql, String statement) {
            return (StringUtils.isEmpty(sql) ? statement : sql + "; " + statement);
        }

        @Override
        public String getSql() {
            return this.currSql;
        }
    }

    return execute(new BatchUpdateStatementCallback());
}

From source file:org.smf4j.spring.RegistryNodeTemplateDefinitionParser.java

protected String getName(ParserContext context, Element element) {
    String name = element.getAttribute(NAME_ATTR);
    if (!StringUtils.hasLength(name)) {
        context.getReaderContext().error("'" + element.getTagName() + "' tag requires a 'name'.", element);
    }//www.  j  a  v  a  2  s . com
    return name;
}

From source file:org.smf4j.spring.RegistryNodeTemplateDefinitionParser.java

protected Object getFrequency(ParserContext context, Element element, String freq) {
    Class<Enum> frequencyClass;
    try {/*w w w . ja v a 2s.  co  m*/
        frequencyClass = (Class<Enum>) Class.forName(FREQUENCY_CLASS);
    } catch (ClassNotFoundException e) {
        context.getReaderContext().error("Unable to load Frequency class '" + FREQUENCY_CLASS + "'",
                context.extractSource(element));
        return null;
    }

    Object frequency = null;
    if (StringUtils.hasLength(freq)) {
        try {
            frequency = Enum.valueOf(frequencyClass, freq.toUpperCase());
        } catch (IllegalArgumentException e) {
            context.getReaderContext().error("Unknown frequency '" + freq + "'",
                    context.extractSource(element));
            return null;
        }
    }
    return frequency;
}

From source file:com.inspiresoftware.lib.dto.geda.interceptor.impl.TransferableUtils.java

private static void assertKey(final String method, final String key, final boolean isDto) {
    if (!StringUtils.hasLength(key)) {
        throw new IllegalArgumentException(
                "Key must be specified for " + (isDto ? "DTO" : "Entity") + " in " + method);
    }/* w  w w . ja v  a2 s . co  m*/
}

From source file:org.brekka.stillingar.spring.config.ConfigurationServiceBeanDefinitionParser.java

/**
 * @param element/*from  w w w  .  j a v a 2s.c  om*/
 * @return
 */
protected void prepareSnapshotEventHandler(Element element, BeanDefinitionBuilder serviceBuilder) {
    Element handlers = selectSingleChildElement(element, "handlers", true);
    if (handlers != null) {
        String eventRef = handlers.getAttribute("event-ref");
        if (StringUtils.hasLength(eventRef)) {
            serviceBuilder.addConstructorArgReference(eventRef);
            return;
        }
    }
    BeanDefinitionBuilder eventBuilder = BeanDefinitionBuilder
            .genericBeanDefinition(LoggingSnapshotEventHandler.class);
    eventBuilder.addConstructorArgValue(getName(element));
    serviceBuilder.addConstructorArgValue(eventBuilder.getBeanDefinition());
}

From source file:org.openmrs.module.personalhr.web.controller.PhrUserFormController.java

/**
 * @should work for an example//  w  w  w.  jav  a 2  s  .  c  om
 */
@RequestMapping(value = "/phr/user.form", method = RequestMethod.POST)
public String handleSubmission(final WebRequest request, final HttpSession httpSession, final ModelMap model,
        @RequestParam(required = false, value = "action") final String action,
        @RequestParam(required = false, value = "userFormPassword") String password,
        @RequestParam(required = false, value = "secretQuestion") final String secretQuestion,
        @RequestParam(required = false, value = "secretAnswer") final String secretAnswer,
        @RequestParam(required = false, value = "confirm") String confirm,
        @RequestParam(required = false, value = "forcePassword") final Boolean forcePassword,
        @RequestParam(required = false, value = "roleStrings") final String[] roles,
        @RequestParam(required = false, value = "createNewPerson") final String createNewPerson,
        @RequestParam(required = false, value = "sharingToken") String sharingToken,
        @ModelAttribute("user") final User user, final BindingResult errors) {

    if (sharingToken == null) {
        sharingToken = (String) model.get("sharingToken");
    }

    log.debug("Entering PhrUserFormController:handleSubmission..." + sharingToken);
    //add temporary privileges
    boolean isTemporary = false;
    boolean isAdministrator = false;
    if (!Context.isAuthenticated()) {
        Context.authenticate("temporary", "Temporary8");
        Context.addProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS);
        Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS);
        Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS);
        Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS);
        Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
        Context.addProxyPrivilege("PHR Restricted Patient Access");
        isTemporary = true;
        log.debug("Added proxy privileges!");
    } else {
        if (PhrService.PhrBasicRole.PHR_ADMINISTRATOR.getValue()
                .equals(PersonalhrUtil.getService().getPhrRole(Context.getAuthenticatedUser()))) {
            isAdministrator = true;
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS);
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS);
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_DELETE_USERS);
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_PURGE_USERS);
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS);
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
        }
    }

    try {
        final UserService us = Context.getUserService();
        final MessageSourceService mss = Context.getMessageSourceService();

        if (mss.getMessage("User.assumeIdentity").equals(action)) {
            Context.becomeUser(user.getSystemId());
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.assumeIdentity.success");
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ARGS, user.getPersonName());
            return "redirect:/phr/index.htm";

        } else if (mss.getMessage("User.delete").equals(action)) {
            try {
                Context.getUserService().purgeUser(user);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.delete.success");
                return "redirect:/phr/user.list";
            } catch (final Exception ex) {
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "User.delete.failure");
                log.error("Failed to delete user", ex);
                return "redirect:/phr/user.form?userId=" + request.getParameter("userId");
            }

        } else if (mss.getMessage("User.retire").equals(action)) {
            final String retireReason = request.getParameter("retireReason");
            if (!(StringUtils.hasText(retireReason))) {
                errors.rejectValue("retireReason", "User.disableReason.empty");
                return showForm(user.getUserId(), createNewPerson, sharingToken, user, model, httpSession);
            } else {
                us.retireUser(user, retireReason);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.retiredMessage");
            }

        } else if (mss.getMessage("User.unRetire").equals(action)) {
            us.unretireUser(user);
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.unRetiredMessage");
        } else {
            // check if username is already in the database
            if (us.hasDuplicateUsername(user)) {
                errors.rejectValue("username", "error.username.taken");
            }

            // check if password and password confirm are identical
            if ((password == null) || password.equals("XXXXXXXXXXXXXXX")) {
                password = "";
            }
            if ((confirm == null) || confirm.equals("XXXXXXXXXXXXXXX")) {
                confirm = "";
            }

            if (!password.equals(confirm)) {
                errors.reject("error.password.match");
            }

            if ((password.length() == 0) && isNewUser(user)) {
                errors.reject("error.password.weak");
            }

            //check password strength
            if (password.length() > 0) {
                try {
                    OpenmrsUtil.validatePassword(user.getUsername(), password, user.getSystemId());
                } catch (final PasswordException e) {
                    errors.reject(e.getMessage());
                }
            }

            final Set<Role> newRoles = new HashSet<Role>();
            if (roles != null) {
                for (final String r : roles) {
                    // Make sure that if we already have a detached instance of this role in the
                    // user's roles, that we don't fetch a second copy of that same role from
                    // the database, or else hibernate will throw a NonUniqueObjectException.
                    Role role = null;
                    if (user.getRoles() != null) {
                        for (final Role test : user.getRoles()) {
                            if (test.getRole().equals(r)) {
                                role = test;
                            }
                        }
                    }
                    if (role == null) {
                        role = us.getRole(r);
                        user.addRole(role);
                    }
                    newRoles.add(role);
                }
            } else {
                final Role role = us.getRole("PHR Restricted User");
                newRoles.add(role);
                user.addRole(role);
                log.debug("Added PHR Restricted User role only: " + role);
            }

            if (user.getRoles() == null) {
                newRoles.clear();
            } else {
                user.getRoles().retainAll(newRoles);
            }

            final String[] keys = request.getParameterValues("property");
            final String[] values = request.getParameterValues("value");

            if ((keys != null) && (values != null)) {
                for (int x = 0; x < keys.length; x++) {
                    final String key = keys[x];
                    final String val = values[x];
                    user.setUserProperty(key, val);
                }
            }

            new UserProperties(user.getUserProperties()).setSupposedToChangePassword(forcePassword);

            final UserValidator uv = new UserValidator();
            uv.validate(user, errors);

            if (errors.hasErrors()) {
                log.debug("errors validating user: " + errors.getErrorCount() + errors.toString());
                return showForm(user.getUserId(), createNewPerson, sharingToken, user, model, httpSession);
            }

            String emailEntered = request.getParameter("9");

            if (isNewUser(user) && !isAdministrator) {
                log.debug("Saving new user " + user.getUsername() + ", sharingToken=" + sharingToken);
                final PhrSharingToken token = Context.getService(PhrSharingTokenService.class)
                        .getSharingToken(sharingToken);

                //check token existence and name matching
                if (token == null || token.getExpireDate().before(new Date())) {
                    httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                            "Failed to register without a valid sharing token");
                    log.error("Failed to register without a valid sharing token");
                    PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_SIGN_UP, new Date(), null,
                            httpSession.getId(), null,
                            "error=Failed to register without a valid sharing token; user_name="
                                    + user.getName());

                    if (isTemporary) {
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS);
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS);
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS);
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS);
                        Context.removeProxyPrivilege("PHR Restricted Patient Access");
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
                        Context.logout();
                        log.debug("Removed proxy privileges!");
                    }
                    return "redirect:/phr/index.htm?noredirect=true";
                } else if ((token != null) && (token.getRelatedPerson() != null)) {
                    httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                            "Failed to register with a used sharing token");
                    log.error("Failed to register with a used sharing token");
                    PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_SIGN_UP, new Date(), null,
                            httpSession.getId(), null,
                            "error=Failed to register with a used sharing token; user_name=" + user.getName()
                                    + "; sharingToken=" + token);
                    if (isTemporary) {
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS);
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS);
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS);
                        Context.removeProxyPrivilege("PHR Restricted Patient Access");
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS);
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
                        Context.logout();
                        log.debug("Removed proxy privileges!");
                    }

                    return "redirect:/phr/index.htm?noredirect=true";
                } else if (emailEntered != null
                        && token.getRelatedPersonEmail().equalsIgnoreCase(emailEntered)) {
                    // look for person attributes (including email entered) in the request and save to user
                    for (final PersonAttributeType type : Context.getPersonService()
                            .getPersonAttributeTypes(PERSON_TYPE.PATIENT, ATTR_VIEW_TYPE.VIEWING)) {
                        final String paramName = type.getPersonAttributeTypeId().toString();
                        final String value = request.getParameter(paramName);

                        this.log.debug("paramName=" + paramName);

                        // if there is an error displaying the attribute, the value will be null
                        if (value != null) {
                            final PersonAttribute attribute = new PersonAttribute(type, value);
                            try {
                                final Object hydratedObject = attribute.getHydratedObject();
                                if ((hydratedObject == null) || "".equals(hydratedObject.toString())) {
                                    // if null is returned, the value should be blanked out
                                    attribute.setValue("");
                                } else if (hydratedObject instanceof Attributable) {
                                    attribute.setValue(((Attributable) hydratedObject).serialize());
                                } else if (!hydratedObject.getClass().getName().equals(type.getFormat())) {
                                    // if the classes doesn't match the format, the hydration failed somehow
                                    // TODO change the PersonAttribute.getHydratedObject() to not swallow all errors?
                                    throw new APIException();
                                }
                            } catch (final APIException e) {
                                errors.rejectValue("attributeMap[" + type.getName() + "]",
                                        "Invalid value for " + type.getName() + ": '" + value + "'");
                                this.log.warn("Got an invalid value: " + value
                                        + " while setting personAttributeType id #" + paramName, e);

                                // setting the value to empty so that the user can reset the value to something else
                                attribute.setValue("");

                            }
                            user.getPerson().addAttribute(attribute);
                        }
                    }

                    //create a new user by self registration
                    us.saveUser(user, password);

                    //update sharing token
                    token.setRelatedPerson(user.getPerson());
                    token.setChangedBy(user);
                    final Date date = new Date();
                    token.setDateChanged(date);
                    token.setActivateDate(date);
                    Context.getService(PhrSharingTokenService.class).savePhrSharingToken(token);
                    httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "personalhr.user.signed.up");
                    log.debug("New self-registered user created: " + user.getUsername());
                    PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_SIGN_UP, new Date(), user,
                            httpSession.getId(), null, "info=New self-registered user created; user_name="
                                    + user.getName() + "; sharingToken=" + token);

                    //save email to messaging service
                    Integer addressId = saveEmail(user.getPerson(), emailEntered);

                    //set default messaging alert address
                    boolean shouldAlert = true;
                    PersonalhrUtil.setMessagingAlertSettings(user.getPerson(), shouldAlert, addressId);

                    //send email notification

                    // TODO get the deployUrl from the request object; also bad to inject /openmrs/ ...
                    final String deployUrl = Context.getRuntimeProperties().getProperty("deployment.url");//"https://65.111.248.164:8443/"; //"172.30.201.24";

                    final String url = deployUrl + "/openmrs/phr/index.htm";
                    final String passwordOption = Context.getAdministrationService()
                            .getGlobalProperty("personalhr.show.password");

                    String notification = NOTIFICATION_TEMPLATE;
                    notification = notification.replaceAll("OPENMRS_PHR_RELATED_PERSON",
                            user.getPerson().getGivenName());
                    notification = notification.replaceAll("OPENMRS_USERNAME", user.getUsername());
                    notification = notification.replaceAll("OPENMRS_PASSWORD",
                            showPassword(password, passwordOption));
                    notification = notification.replaceAll("OPENMRS_URL", url);

                    PersonalhrUtil.sendEmail(emailEntered, notification);
                } else {
                    httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                            "Failed to create new user due to email mismatch: " + emailEntered);
                    log.debug("Failed to create new user due to email mismatch: "
                            + token.getRelatedPersonEmail() + " vs " + emailEntered);
                    PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_SIGN_UP, new Date(), null,
                            httpSession.getId(), null,
                            "info=Failed to create new user due to email mismatch: "
                                    + token.getRelatedPersonEmail() + "vs " + emailEntered + "; sharingToken="
                                    + token);
                }
            } else if (isNewUser(user) && isAdministrator) {
                //create a new user by PHR Administrator
                us.saveUser(user, password);
            } else {
                //modify an exiting user
                us.saveUser(user, null);

                if (!password.equals("") && Context.hasPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS)) {
                    if (log.isDebugEnabled()) {
                        log.debug("calling changePassword for user " + user + " by user "
                                + Context.getAuthenticatedUser());
                    }
                    us.changePassword(user, password);
                }
                log.debug("Existing user " + user.getUsername() + " changed by user "
                        + Context.getAuthenticatedUser().getUsername());
                PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_UPDATE, new Date(),
                        Context.getAuthenticatedUser(), httpSession.getId(), null,
                        "info=Existing user updated; user_name=" + user.getName());
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.saved");
            }

            if (StringUtils.hasLength(secretQuestion) && StringUtils.hasLength(secretAnswer)) {
                us.changeQuestionAnswer(user, secretQuestion, secretAnswer);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.saved");
            }
        }
    } finally {
        //remove temporary privileges
        if (isTemporary) {
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS);
            Context.removeProxyPrivilege("PHR Restricted Patient Access");
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
            Context.logout();
            log.debug("Removed proxy privileges for self registration!");
        } else if (isAdministrator) {
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_DELETE_USERS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_PURGE_USERS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
            log.debug("Removed proxy privileges for PHR Administrator!");
        }
    }
    return "redirect:/phr/index.htm?noredirect=true";
}

From source file:org.openmrs.module.sync.SyncUtil.java

/**
 * Uses the generic hibernate API to perform the save with the following exceptions.<br/>
 * Remarks: <br/>/*from w w  w.  jav a  2 s. c  o m*/
 * Obs: if an obs comes through with a non-null voidReason, make sure we change it back to using
 * a PK. SyncSubclassStub: this is a 'special' utility object that sync uses to compensate for
 * presence of the prepare stmt in HibernatePatientDAO.insertPatientStubIfNeeded() that
 * by-passes normal hibernate interceptor behavior. For full description of how this works read
 * class comments for {@link SyncSubclassStub}.
 * 
 * @param o object to save
 * @param className type
 * @param uuid unique id of the object that is being saved
 */
public static synchronized void updateOpenmrsObject(OpenmrsObject o, String className, String uuid) {

    if (o == null) {
        log.warn("Will not update OpenMRS object that is NULL");
        return;
    }
    if ("org.openmrs.Obs".equals(className)) {
        // if an obs comes through with a non-null voidReason, make sure we change it back to using a PK
        Obs obs = (Obs) o;
        String voidReason = obs.getVoidReason();
        if (StringUtils.hasLength(voidReason)) {
            int start = voidReason.lastIndexOf(" ") + 1; // assumes uuids don't have spaces 
            int end = voidReason.length() - 1;
            try {
                String otherObsUuid = voidReason.substring(start, end);
                OpenmrsObject openmrsObject = getOpenmrsObj("org.openmrs.Obs", otherObsUuid);
                Integer obsId = openmrsObject.getId();
                obs.setVoidReason(voidReason.substring(0, start) + obsId + ")");
            } catch (Exception e) {
                log.trace("unable to get a uuid from obs voidReason. obs uuid: " + uuid, e);
            }
        }
    } else if ("org.openmrs.api.db.LoginCredential".equals(className)) {
        LoginCredential login = (LoginCredential) o;
        OpenmrsObject openmrsObject = getOpenmrsObj("org.openmrs.User", login.getUuid());
        Integer userId = openmrsObject.getId();
        login.setUserId(userId);
    }
    //DT:  may 24 2011: I think matching by conceptId is a dead issue now that MetadataSharing is the standard for sharing objects   
    //this never worked anyway...  SYNC-160
    //       else if (o instanceof org.openmrs.Concept) {
    //          Concept concept = (Concept)o;
    //          if (!Context.getService(SyncIngestService.class)
    //                .isConceptIdValidForUuid(concept.getConceptId(), concept.getUuid())) {
    //             
    //             String msg = "Data inconsistency in concepts detected."
    //                + "Concept with conflicting pair of values (id-uuid) already exists in the database."
    //                + "\n Concept id: " + concept.getConceptId() + " and uuid: " + concept.getUuid();
    //             throw new SyncException(msg);
    //          }
    //          
    //       }

    //now do the save; see method comments to see why SyncSubclassStub is handled differently
    if ("org.openmrs.module.sync.SyncSubclassStub".equals(className)) {
        SyncSubclassStub stub = (SyncSubclassStub) o;
        Context.getService(SyncIngestService.class).processSyncSubclassStub(stub);
    } else {
        Context.getService(SyncService.class).saveOrUpdate(o);
    }
    return;
}