Example usage for org.hibernate.type StandardBasicTypes STRING

List of usage examples for org.hibernate.type StandardBasicTypes STRING

Introduction

In this page you can find the example usage for org.hibernate.type StandardBasicTypes STRING.

Prototype

StringType STRING

To view the source code for org.hibernate.type StandardBasicTypes STRING.

Click Source Link

Document

The standard Hibernate type for mapping String to JDBC java.sql.Types#VARCHAR VARCHAR .

Usage

From source file:org.openbravo.base.session.OBOracle10gDialect.java

License:Open Source License

public OBOracle10gDialect() {
    super();/*w  w  w  .j ava 2s. co m*/

    registerHibernateType(Types.NUMERIC, StandardBasicTypes.LONG.getName());
    registerHibernateType(Types.NVARCHAR, StandardBasicTypes.STRING.getName());
    registerHibernateType(Types.NCHAR, StandardBasicTypes.STRING.getName());

    registerColumnType(Types.VARCHAR, 4000, "nvarchar2($l)");
    registerColumnType(Types.VARCHAR, 100, "varchar2($l)");
    registerColumnType(Types.VARCHAR, 5, "char($l)");
    registerFunction("to_number", new StandardSQLFunction("to_number", StandardBasicTypes.BIG_DECIMAL));

    log.debug("Created Openbravo specific Oracle DIalect");
}

From source file:org.openbravo.test.dal.IssuesTest.java

License:Open Source License

/**
   * https://issues.openbravo.com/view.php?id=18688
   *//*w w w . ja v  a 2s .c  o  m*/
  @Test
  public void test18688() {
      final Session session = OBDal.getInstance().getSession();
      OBDal.getInstance().registerSQLFunction("ad_column_identifier_std",
              new StandardSQLFunction("ad_column_identifier_std", StandardBasicTypes.STRING));
      final String qryStr = "select bc.id, ad_column_identifier_std('C_BP_Group', bc.id) from "
              + Category.ENTITY_NAME + " bc";
      final Query qry = session.createQuery(qryStr);
      for (Object o : qry.list()) {
          final Object[] os = (Object[]) o;
          assertTrue(os[1] instanceof String && os[1].toString().length() > 0);
      }
  }

From source file:org.openmrs.api.db.hibernate.HibernateContextDAO.java

License:Mozilla Public License

/**
 * @see org.openmrs.api.db.ContextDAO#authenticate(java.lang.String, java.lang.String)
 *//*from  w ww. ja v a  2s. com*/
public User authenticate(String login, String password) throws ContextAuthenticationException {

    String errorMsg = "Invalid username and/or password: " + login;

    Session session = sessionFactory.getCurrentSession();

    User candidateUser = null;

    if (login != null) {
        //if username is blank or white space character(s)
        if (StringUtils.isEmpty(login) || StringUtils.isWhitespace(login)) {
            throw new ContextAuthenticationException(errorMsg);
        }

        // loginWithoutDash is used to compare to the system id
        String loginWithDash = login;
        if (login.matches("\\d{2,}")) {
            loginWithDash = login.substring(0, login.length() - 1) + "-" + login.charAt(login.length() - 1);
        }

        try {
            candidateUser = (User) session.createQuery(
                    "from User u where (u.username = ? or u.systemId = ? or u.systemId = ?) and u.retired = '0'")
                    .setString(0, login).setString(1, login).setString(2, loginWithDash).uniqueResult();
        } catch (HibernateException he) {
            log.error("Got hibernate exception while logging in: '" + login + "'", he);
        } catch (Exception e) {
            log.error("Got regular exception while logging in: '" + login + "'", e);
        }
    }

    // only continue if this is a valid username and a nonempty password
    if (candidateUser != null && password != null) {
        if (log.isDebugEnabled()) {
            log.debug("Candidate user id: " + candidateUser.getUserId());
        }

        String lockoutTimeString = candidateUser
                .getUserProperty(OpenmrsConstants.USER_PROPERTY_LOCKOUT_TIMESTAMP, null);
        Long lockoutTime = null;
        if (lockoutTimeString != null && !lockoutTimeString.equals("0")) {
            try {
                // putting this in a try/catch in case the admin decided to put junk into the property
                lockoutTime = Long.valueOf(lockoutTimeString);
            } catch (NumberFormatException e) {
                log.debug("bad value stored in " + OpenmrsConstants.USER_PROPERTY_LOCKOUT_TIMESTAMP
                        + " user property: " + lockoutTimeString);
            }
        }

        // if they've been locked out, don't continue with the authentication
        if (lockoutTime != null) {
            // unlock them after 5 mins, otherwise reset the timestamp
            // to now and make them wait another 5 mins
            if (System.currentTimeMillis() - lockoutTime > 300000) {
                candidateUser.setUserProperty(OpenmrsConstants.USER_PROPERTY_LOGIN_ATTEMPTS, "0");
                candidateUser.removeUserProperty(OpenmrsConstants.USER_PROPERTY_LOCKOUT_TIMESTAMP);
                saveUserProperties(candidateUser);
            } else {
                candidateUser.setUserProperty(OpenmrsConstants.USER_PROPERTY_LOCKOUT_TIMESTAMP,
                        String.valueOf(System.currentTimeMillis()));
                throw new ContextAuthenticationException(
                        "Invalid number of connection attempts. Please try again later.");
            }
        }

        String passwordOnRecord = (String) session
                .createSQLQuery("select password from users where user_id = ?")
                .addScalar("password", StandardBasicTypes.STRING).setInteger(0, candidateUser.getUserId())
                .uniqueResult();

        String saltOnRecord = (String) session.createSQLQuery("select salt from users where user_id = ?")
                .addScalar("salt", StandardBasicTypes.STRING).setInteger(0, candidateUser.getUserId())
                .uniqueResult();

        // if the username and password match, hydrate the user and return it
        if (passwordOnRecord != null && Security.hashMatches(passwordOnRecord, password + saltOnRecord)) {
            // hydrate the user object
            candidateUser.getAllRoles().size();
            candidateUser.getUserProperties().size();
            candidateUser.getPrivileges().size();

            // only clean up if the were some login failures, otherwise all should be clean
            Integer attempts = getUsersLoginAttempts(candidateUser);
            if (attempts > 0) {
                candidateUser.setUserProperty(OpenmrsConstants.USER_PROPERTY_LOGIN_ATTEMPTS, "0");
                candidateUser.removeUserProperty(OpenmrsConstants.USER_PROPERTY_LOCKOUT_TIMESTAMP);
                saveUserProperties(candidateUser);
            }

            // skip out of the method early (instead of throwing the exception)
            // to indicate that this is the valid user
            return candidateUser;
        } else {
            // the user failed the username/password, increment their
            // attempts here and set the "lockout" timestamp if necessary
            Integer attempts = getUsersLoginAttempts(candidateUser);

            attempts++;

            Integer allowedFailedLoginCount = 7;

            try {
                allowedFailedLoginCount = Integer.valueOf(Context.getAdministrationService()
                        .getGlobalProperty(OpenmrsConstants.GP_ALLOWED_FAILED_LOGINS_BEFORE_LOCKOUT).trim());
            } catch (Exception ex) {
                log.error("Unable to convert the global property "
                        + OpenmrsConstants.GP_ALLOWED_FAILED_LOGINS_BEFORE_LOCKOUT
                        + "to a valid integer. Using default value of 7");
            }

            if (attempts > allowedFailedLoginCount) {
                // set the user as locked out at this exact time
                candidateUser.setUserProperty(OpenmrsConstants.USER_PROPERTY_LOCKOUT_TIMESTAMP,
                        String.valueOf(System.currentTimeMillis()));
            } else {
                candidateUser.setUserProperty(OpenmrsConstants.USER_PROPERTY_LOGIN_ATTEMPTS,
                        String.valueOf(attempts));
            }

            saveUserProperties(candidateUser);
        }
    }

    // throw this exception only once in the same place with the same
    // message regardless of username/pw combo entered
    log.info("Failed login attempt (login=" + login + ") - " + errorMsg);
    throw new ContextAuthenticationException(errorMsg);

}

From source file:org.openmrs.hl7.db.hibernate.HibernateHL7DAO.java

License:Mozilla Public License

/**
 * @see org.openmrs.hl7.db.HL7DAO#getHL7InArchiveByUuid(java.lang.String)
 *///from   w  ww. ja v  a2 s  .c  o m
public HL7InArchive getHL7InArchiveByUuid(String uuid) throws DAOException {
    Query query = sessionFactory.getCurrentSession().createQuery("from HL7InArchive where uuid = ?")
            .setParameter(0, uuid, StandardBasicTypes.STRING);
    Object record = query.uniqueResult();
    if (record == null) {
        return null;
    }
    return (HL7InArchive) record;
}

From source file:org.openmrs.module.idcards.db.hibernate.HibernateIdcardsDAO.java

License:Open Source License

/**
 * @see org.openmrs.module.idcards.db.IdcardsDAO#getPatientsByIdentifier(java.util.List)
 *//*from w ww  .jav a2s .c o  m*/
public List<Patient> getPatientsByIdentifier(List<String> identifiers) throws DAOException {
    String tmp1 = identifiers.toString();
    String tmp2 = tmp1.replaceAll(", ", "\\$|\\^");
    String tmp3 = tmp2.replaceAll(" ", "\\[ ]?");
    String tmp4 = tmp3.replaceAll("\\-", "\\[\\-\\]?");
    String regex = "^" + tmp4.substring(1, tmp4.length() - 1) + "$";
    Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Patient.class);
    criteria.createAlias("identifiers", "ids");
    criteria.add(Restrictions.sqlRestriction("identifier rlike ?", regex, StandardBasicTypes.STRING));
    log.debug("Patient identifier regex" + regex);
    log.debug("StandardBasicTypes.STRING: " + StandardBasicTypes.STRING.toString());
    return criteria.list();
}

From source file:org.openwms.common.units.PieceUserType.java

License:Open Source License

/**
 * {@inheritDoc}//www . j ava 2  s.  c  o m
 */
@Override
public Type[] getPropertyTypes() {
    return new Type[] { StandardBasicTypes.STRING, StandardBasicTypes.BIG_DECIMAL };
}

From source file:org.openwms.common.units.PieceUserType.java

License:Open Source License

/**
 * {@inheritDoc}/*from   w  w  w  .  j a  v  a  2 s .  c  o  m*/
 *
 * @throws SQLException
 *             in case of database errors
 */
@Override
public void nullSafeSet(PreparedStatement preparedStatement, Object o, int i,
        SessionImplementor sessionImplementor) throws HibernateException, SQLException {
    if (o == null) {
        preparedStatement.setNull(i, StandardBasicTypes.STRING.sqlType());
        preparedStatement.setNull(i + 1, StandardBasicTypes.BIG_DECIMAL.sqlType());
    } else {
        Piece piece = (Piece) o;
        String unitType = piece.getUnitType().toString();
        preparedStatement.setString(i, unitType);
        preparedStatement.setBigDecimal(i + 1, piece.getMagnitude());
    }
}

From source file:org.openwms.common.units.UnitUserType.java

License:Open Source License

/**
 * {@inheritDoc}/*from   ww  w  .  jav  a2s . c  om*/
 * <p>
 * We're going to persist both fields as Strings.
 */
@Override
public Type[] getPropertyTypes() {
    return new Type[] { StandardBasicTypes.STRING, StandardBasicTypes.STRING };
}

From source file:org.openwms.common.units.UnitUserType.java

License:Open Source License

/**
 * {@inheritDoc}// www  .j a  v  a2  s. c  om
 * <p>
 * We've to store the concrete classname as well.
 *
 * @throws SQLException in case of database errors
 */
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor sessionImplementor)
        throws HibernateException, SQLException {
    if (value == null) {
        st.setNull(index, StandardBasicTypes.STRING.sqlType());
        st.setNull(index + 1, StandardBasicTypes.STRING.sqlType());
    } else {
        if (value instanceof Piece) {
            Piece piece = (Piece) value;
            st.setString(index, piece.getUnitType().toString() + "@" + Piece.class.getCanonicalName());
            st.setString(index + 1, piece.getMagnitude().toPlainString());
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Binding '" + piece.getUnitType().toString() + "@" + Piece.class.getCanonicalName()
                        + "' to parameter: " + index);
                LOGGER.trace(
                        "Binding '" + piece.getMagnitude().toPlainString() + "' to parameter: " + (index + 1));
            }
        } else if (value instanceof Weight) {
            Weight weight = (Weight) value;
            st.setString(index, weight.getUnitType().toString() + "@" + Weight.class.getCanonicalName());
            st.setString(index + 1, weight.getMagnitude().toPlainString());
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Binding '" + weight.getUnitType().toString() + "@"
                        + Weight.class.getCanonicalName() + "' to parameter: " + index);
                LOGGER.trace(
                        "Binding '" + weight.getMagnitude().toPlainString() + "' to parameter: " + index + 1);
            }
        } else {
            throw new TypeMismatchException("Incompatible type: " + value.getClass().getCanonicalName());
        }
    }
}

From source file:org.openwms.persistence.ext.hibernate.PieceUserType.java

License:Open Source License

/**
 * {@inheritDoc}/* w  w w .j a  v a  2 s . c o m*/
 * 
 * @throws SQLException
 *             in case of database errors
 */
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session)
        throws SQLException {
    if (value == null) {
        st.setNull(index, StandardBasicTypes.STRING.sqlType());
        st.setNull(index + 1, StandardBasicTypes.BIG_DECIMAL.sqlType());
    } else {
        Piece piece = (Piece) value;
        String unitType = piece.getUnitType().toString();
        st.setString(index, unitType);
        st.setBigDecimal(index + 1, piece.getMagnitude());
    }
}