Example usage for org.hibernate HibernateException HibernateException

List of usage examples for org.hibernate HibernateException HibernateException

Introduction

In this page you can find the example usage for org.hibernate HibernateException HibernateException.

Prototype

public HibernateException(Throwable cause) 

Source Link

Document

Constructs a HibernateException using the given message and underlying cause.

Usage

From source file:com.blazebit.persistence.integration.hibernate.Hibernate43Access.java

License:Apache License

private String expandParameterList(SessionImplementor session, ParameterMetadata parameterMetadata,
        String query, String name, TypedValue typedList, Map<String, TypedValue> namedParamsCopy) {
    Collection<?> vals = (Collection<?>) typedList.getValue();

    // HHH-1123//w w  w. java 2 s.  c  o  m
    // Some DBs limit number of IN expressions.  For now, warn...
    final Dialect dialect = session.getFactory().getDialect();
    final int inExprLimit = dialect.getInExpressionCountLimit();
    if (inExprLimit > 0 && vals.size() > inExprLimit) {
        LOG.warning(String.format(
                "Dialect [%s] limits the number of elements in an IN predicate to %s entries.  "
                        + "However, the given parameter list [%s] contained %s entries, which will likely cause failures "
                        + "to execute the query in the database",
                dialect.getClass().getName(), inExprLimit, name, vals.size()));
    }

    Type type = typedList.getType();

    boolean isJpaPositionalParam = parameterMetadata.getNamedParameterDescriptor(name).isJpaStyle();
    String paramPrefix = isJpaPositionalParam ? "?" : ParserHelper.HQL_VARIABLE_PREFIX;
    String placeholder = new StringBuilder(paramPrefix.length() + name.length()).append(paramPrefix)
            .append(name).toString();

    if (query == null) {
        return query;
    }
    int loc = query.indexOf(placeholder);

    if (loc < 0) {
        return query;
    }

    String beforePlaceholder = query.substring(0, loc);
    String afterPlaceholder = query.substring(loc + placeholder.length());

    // check if placeholder is already immediately enclosed in parentheses
    // (ignoring whitespace)
    boolean isEnclosedInParens = StringHelper.getLastNonWhitespaceCharacter(beforePlaceholder) == '('
            && StringHelper.getFirstNonWhitespaceCharacter(afterPlaceholder) == ')';

    if (vals.size() == 1 && isEnclosedInParens) {
        // short-circuit for performance when only 1 value and the
        // placeholder is already enclosed in parentheses...
        namedParamsCopy.put(name, new TypedValue(type, vals.iterator().next()));
        return query;
    }

    StringBuilder list = new StringBuilder(16);
    Iterator<?> iter = vals.iterator();
    int i = 0;
    while (iter.hasNext()) {
        // Variable 'name' can represent a number or contain digit at the end. Surrounding it with
        // characters to avoid ambiguous definition after concatenating value of 'i' counter.
        String alias = (isJpaPositionalParam ? 'x' + name : name) + '_' + i++ + '_';
        if (namedParamsCopy.put(alias, new TypedValue(type, iter.next())) != null) {
            throw new HibernateException(
                    "Repeated usage of alias '" + alias + "' while expanding list parameter.");
        }
        list.append(ParserHelper.HQL_VARIABLE_PREFIX).append(alias);
        if (iter.hasNext()) {
            list.append(", ");
        }
    }
    return StringHelper.replace(beforePlaceholder, afterPlaceholder, placeholder.toString(), list.toString(),
            true, true);
}

From source file:com.blogspot.hwellmann.multitenancy.hibernate.SchemaMultiTenantConnectionProvider.java

License:Apache License

@Override
public void injectServices(ServiceRegistryImplementor serviceRegistry) {
    final Object dataSourceConfigValue = serviceRegistry.getService(ConfigurationService.class).getSettings()
            .get(AvailableSettings.DATASOURCE);
    if (dataSourceConfigValue == null || !String.class.isInstance(dataSourceConfigValue)) {
        throw new HibernateException("Improper set up of DataSourceBasedMultiTenantConnectionProviderImpl");
    }/*w ww.  j a va2s.c  om*/
    final String jndiName = (String) dataSourceConfigValue;

    jndiService = serviceRegistry.getService(JndiService.class);
    if (jndiService == null) {
        throw new HibernateException(
                "Could not locate JndiService from DataSourceBasedMultiTenantConnectionProviderImpl");
    }

    final Object namedObject = jndiService.locate(jndiName);
    if (namedObject == null) {
        throw new HibernateException("JNDI name [" + jndiName + "] could not be resolved");
    }

    if (DataSource.class.isInstance(namedObject)) {
        final int loc = jndiName.lastIndexOf("/");
        this.baseJndiNamespace = jndiName.substring(0, loc);
        this.tenantIdentifierForAny = jndiName.substring(loc + 1);
        dataSourceMap().put(tenantIdentifierForAny, (DataSource) namedObject);
    } else if (Context.class.isInstance(namedObject)) {
        this.baseJndiNamespace = jndiName;
        this.tenantIdentifierForAny = (String) serviceRegistry.getService(ConfigurationService.class)
                .getSettings().get(TENANT_IDENTIFIER_TO_USE_FOR_ANY_KEY);
        if (tenantIdentifierForAny == null) {
            throw new HibernateException(
                    "JNDI name named a Context, but tenant identifier to use for ANY was not specified");
        }
    } else {
        throw new HibernateException("Unknown object type [" + namedObject.getClass().getName()
                + "] found in JNDI location [" + jndiName + "]");
    }
}

From source file:com.cisco.ca.cstg.pdi.services.ConfigurationServiceImpl.java

@Override
public void cloneProject(Integer sourceProjectId, Integer newProjectId)
        throws IOException, IllegalStateException, JAXBException, DocumentException {
    LOGGER.info("Cloning project id {} to new project id {}", sourceProjectId, newProjectId);
    XmlGenProjectDetails pd = (XmlGenProjectDetails) findById(XmlGenProjectDetails.class, sourceProjectId);

    if (pd != null) {
        Map<String, Object> status = processUcsPdiConfiguration(pd);
        String sourceDataPath = Util
                .getPdiConfDataFolderPath(projectDetailsService.fetchProjectDetails(sourceProjectId));
        String destDataPath = Util
                .getPdiConfDataFolderPath(projectDetailsService.fetchProjectDetails(newProjectId));

        if (status.get(CONF_CREATION).equals(true)) {
            try {
                FileUtils.copyDirectory(new File(sourceDataPath), new File(destDataPath));
                LOGGER.debug("Copied directory from {} to {}", sourceDataPath, destDataPath);

                synchronized (this) {
                    unmarshalUcsXml.unmarshalMetatData(
                            destDataPath + File.separator + Constants.PDI_META_DATA_FILE_NAME, newProjectId);
                    deleteRecords(Toproot.class);
                    unmarshalUcsXml.unmarshalTopRootElement(
                            destDataPath + File.separator + Constants.PDI_CONFIG_FILE_NAME);
                    LOGGER.info("Unmarshalled data to UCS tables successfully.");
                    String errorMessage = executeStoredProcedure(PROC_NAME_FOR_UCS_ADA, newProjectId);
                    if (errorMessage != null && !errorMessage.isEmpty()) {
                        throw new HibernateException(errorMessage);
                    }/*  ww w .ja v  a  2s  .  c o m*/
                    LOGGER.info("Stored Procedure for translating data to ADA tables executed successfully.");
                    unmarshalUcsXml.unmarshalMetatDataMO(
                            destDataPath + File.separator + Constants.PDI_META_DATA_FILE_NAME, newProjectId);

                    // step: call the store procedure to save Chassis count
                    errorMessage = executeStoredProcedure(PROC_NAME_FOR_CHASSIS_COUNT, newProjectId);
                    if (errorMessage != null && !errorMessage.isEmpty()) {
                        throw new HibernateException(errorMessage);
                    }
                }
            } catch (IOException | HibernateException | JAXBException e) {
                LOGGER.error("Error occured while trying to clone the project.", e);
                throw e;
            }
        } else {
            LOGGER.error("Error while generating XML for the source project");
            throw new IllegalStateException("Error while generating XML from source project");
        }
    }
}

From source file:com.cisco.ca.cstg.pdi.services.ConfigurationServiceImpl.java

@Override
public void importXMlToADAProject(Integer newProjectId)
        throws IOException, IllegalStateException, JAXBException, DocumentException {
    LOGGER.info("Import XML to new ADA Project:" + newProjectId);
    boolean metadataExits = false;
    String destinationPath = Util
            .getPdiConfDataFolderPath(projectDetailsService.fetchProjectDetails(newProjectId));
    try {/* w  w w .j  a va2 s  . c o  m*/
        synchronized (this) {
            // step1: check if the folder has meta data folder
            metadataExits = new File(destinationPath, Constants.PDI_META_DATA_FILE_NAME).exists();

            if (metadataExits) {
                LOGGER.info("Meta data file found for projectID:" + newProjectId);
                unmarshalUcsXml.unmarshalMetatData(
                        destinationPath + File.separator + Constants.PDI_META_DATA_FILE_NAME, newProjectId);
            }

            // step2: unmarshal top root element
            deleteRecords(Toproot.class);
            unmarshalUcsXml
                    .unmarshalTopRootElement(destinationPath + File.separator + Constants.PDI_CONFIG_FILE_NAME);
            LOGGER.info("Unmarshalled data to UCS tables successfully.");

            // step3: call the store procedure to save the data to db
            String errorMessage = executeStoredProcedure(PROC_NAME_FOR_UCS_ADA, newProjectId);
            if (errorMessage != null && !errorMessage.isEmpty()) {
                throw new HibernateException(errorMessage);
            }

            // step4: unmarsahall the MO data
            if (metadataExits) {
                unmarshalUcsXml.unmarshalMetatDataMO(
                        destinationPath + File.separator + Constants.PDI_META_DATA_FILE_NAME, newProjectId);
            }
            // step5: call the store procedure to save Chassis count
            errorMessage = executeStoredProcedure(PROC_NAME_FOR_CHASSIS_COUNT, newProjectId);
            if (errorMessage != null && !errorMessage.isEmpty()) {
                throw new HibernateException(errorMessage);
            }
            LOGGER.info("Stored Procedure for translating data to ADA tables executed successfully.");
        }
    } catch (IOException | HibernateException | JAXBException e) {
        LOGGER.error("Error occured when trying to import the project to ADA tool.", e);
        throw e;
    }
    LOGGER.info("Stored Procedure for translating data to ADA tables executed successfully.");
}

From source file:com.clican.pluto.orm.usertype.StringSplitType.java

License:LGPL

public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
    if (value == null) {
        st.setString(index, "");
    } else if (value instanceof String[]) {
        StringBuffer result = new StringBuffer();
        for (String s : ((String[]) value)) {
            result.append(s);//w w  w .j a v  a 2s.  c  o m
            result.append(",");
        }
        if (result.length() == 0) {
            st.setString(index, "");
        } else {
            st.setString(index, result.toString().substring(0, result.length() - 1));
        }
    } else {
        throw new HibernateException("The property must be a comma-split string.");
    }
}

From source file:com.cloudy.common.repository.hibernate.type.HashMapToStringUserType.java

License:Apache License

private Map newMap() {
    try {//ww w.  j  a v a 2  s  .  c o  m
        return HashMap.class.newInstance();
    } catch (Exception e) {
        throw new HibernateException(e);
    }
}

From source file:com.corundumstudio.hibernate.dsc.DynamicQueryCache.java

License:Apache License

private Map<String, Object> extractValues(QueryKey key) {
    try {//from  w w w .j a  va  2s  .  c  o  m
        Map<String, Object> paramValues = (Map<String, Object>) positionalParameterField.get(key);
        Map<String, Object> values = new HashMap<String, Object>(paramValues.size());
        for (Map.Entry<String, Object> entry : paramValues.entrySet()) {
            TypedValue typeValue = (TypedValue) entry.getValue();
            values.put(entry.getKey(), typeValue.getValue());
        }
        return values;
    } catch (Exception e) {
        throw new HibernateException(e);
    }
}

From source file:com.court.controller.HomeFXMLController.java

private Criterion filterByMonthCriterion(final String propertyName) {

    return new Criterion() {

        final int month = new Date().getMonth() + 1;

        @Override//www.j a v a  2  s.  c  o  m
        public String toSqlString(Criteria crtr, CriteriaQuery cq) throws HibernateException {
            String[] columns = cq.getColumns(propertyName, crtr);
            if (columns.length != 1) {
                throw new HibernateException("monthEq may only be used with single-column properties");
            }
            return "month(" + columns[0] + ") = ?";
        }

        @Override
        public TypedValue[] getTypedValues(Criteria crtr, CriteriaQuery cq) throws HibernateException {
            return new TypedValue[] { new TypedValue(IntegerType.INSTANCE, month, EntityMode.POJO) };
        }

        @Override
        public String toString() {
            return "month(" + propertyName + ") = " + month;
        }

    };
}

From source file:com.devnexus.ting.core.hibernate.DevNexusSpringImplicitNamingStrategy.java

License:Apache License

@Override
public Identifier determinePrimaryTableName(ImplicitEntityNameSource source) {
    if (source == null) {
        // should never happen, but to be defensive...
        throw new HibernateException("Entity naming information was not provided.");
    }//from w ww.  j  av a2  s. c o  m

    String tableName = transformEntityName(source.getEntityNaming());

    if (tableName == null) {
        // todo : add info to error message - but how to know what to write since we failed to interpret the naming source
        throw new HibernateException("Could not determine primary table name for entity");
    }

    return toIdentifier(English.plural(tableName), source.getBuildingContext());
}

From source file:com.dz.module.charge.ChargeService.java

/**
 * ???,???/* w  w  w.  j a v a 2s.  c  om*/
 * @param plan
 * @return
 */
public void addChargePlan(ChargePlan plan, Session session) throws HibernateException {
    if (plan == null)
        throw new HibernateException("the plan shouldn't be null");
    plan.setIsClear(false);
    int contractId = plan.getContractId();
    Contract contract = (Contract) session.get(Contract.class, contractId);
    if (contract == null)
        return;
    //??????.
    if (!plan.getFeeType().equals("plan_base_contract"))
        if ((plan.getFeeType().startsWith("add") || plan.getFeeType().startsWith("sub"))) {
            if (!DateUtil.isYearAndMonth(plan.getTime(),
                    clearTimeDao.getCurrent(contract.getBranchFirm(), session)))
                return;
        } else {
            plan.setTime(clearTimeDao.getCurrent(contract.getBranchFirm(), session));
        }
    if (plan.getFee() == null)
        return;
    session.saveOrUpdate(plan);
}