Example usage for org.hibernate.exception GenericJDBCException getSQLException

List of usage examples for org.hibernate.exception GenericJDBCException getSQLException

Introduction

In this page you can find the example usage for org.hibernate.exception GenericJDBCException getSQLException.

Prototype

public SQLException getSQLException() 

Source Link

Document

Get the underlying SQLException .

Usage

From source file:org.openbravo.materialmgmt.VariantAutomaticGenerationProcess.java

License:Open Source License

@Override
public void execute(ProcessBundle bundle) throws Exception {
    OBError msg = new OBError();
    msg.setType("Success");
    msg.setTitle(OBMessageUtils.messageBD("Success"));

    try {/*  ww w .j a  va2 s  . c  o m*/
        // retrieve standard params
        final String recordID = (String) bundle.getParams().get("M_Product_ID");
        Product product = OBDal.getInstance().get(Product.class, recordID);

        runChecks(product);

        int totalMaxLength = product.getSearchKey().length();
        long variantNumber = 1;
        Map<String, ProductCharacteristicAux> prChUseCode = new HashMap<String, ProductCharacteristicAux>();

        OBCriteria<ProductCharacteristic> prChCrit = OBDal.getInstance()
                .createCriteria(ProductCharacteristic.class);
        prChCrit.add(Restrictions.eq(ProductCharacteristic.PROPERTY_PRODUCT, product));
        prChCrit.add(Restrictions.eq(ProductCharacteristic.PROPERTY_VARIANT, true));
        prChCrit.addOrderBy(ProductCharacteristic.PROPERTY_SEQUENCENUMBER, true);
        List<String> prChs = new ArrayList<String>();
        for (ProductCharacteristic pc : prChCrit.list()) {
            prChs.add(pc.getId());
        }
        int chNumber = prChs.size();
        String[] currentValues = new String[chNumber];

        int i = 0;
        for (ProductCharacteristic prCh : prChCrit.list()) {
            OBCriteria<ProductCharacteristicConf> prChConfCrit = OBDal.getInstance()
                    .createCriteria(ProductCharacteristicConf.class);
            prChConfCrit.add(Restrictions.eq(ProductCharacteristicConf.PROPERTY_CHARACTERISTICOFPRODUCT, prCh));

            List<String> prChConfs = new ArrayList<String>();
            for (ProductCharacteristicConf pcc : prChConfCrit.list()) {
                prChConfs.add(pcc.getId());
            }
            long valuesCount = prChConfs.size();

            boolean useCode = true;
            int maxLength = 0;
            for (String id : prChConfs) {
                ProductCharacteristicConf prChConf = OBDal.getInstance().get(ProductCharacteristicConf.class,
                        id);
                if (StringUtils.isBlank(prChConf.getCode())) {
                    useCode = false;
                    break;
                }
                if (prChConf.getCode().length() > maxLength) {
                    maxLength = prChConf.getCode().length();
                }
            }

            variantNumber = variantNumber * valuesCount;
            if (useCode) {
                totalMaxLength += maxLength;
            }
            ProductCharacteristicAux prChAux = new ProductCharacteristicAux(useCode, prChConfs);
            currentValues[i] = prChAux.getNextValue();
            prChUseCode.put(prCh.getId(), prChAux);
            i++;
        }
        totalMaxLength += Long.toString(variantNumber).length();
        boolean useCodes = totalMaxLength <= searchKeyLength;

        boolean hasNext = true;
        int productNo = 0;
        int k = 0;
        Long start = System.currentTimeMillis();
        boolean multilingualDocs = OBDal.getInstance().get(Client.class, bundle.getContext().getClient())
                .isMultilingualDocuments();
        do {
            k = k + 1;
            // Create variant product
            product = OBDal.getInstance().get(Product.class, recordID);
            Product variant = (Product) DalUtil.copy(product);

            if (multilingualDocs) {
                variant.set(Product.PROPERTY_PRODUCTTRLLIST, null);
            }

            if (product.getImage() != null) {
                Image newPrImage = (Image) DalUtil.copy(product.getImage(), false);
                OBDal.getInstance().save(newPrImage);
                variant.setImage(newPrImage);
            }

            variant.setGenericProduct(product);
            variant.setProductAccountsList(Collections.<ProductAccounts>emptyList());
            variant.setGeneric(false);
            for (ProductCharacteristic prCh : variant.getProductCharacteristicList()) {
                prCh.setProductCharacteristicConfList(Collections.<ProductCharacteristicConf>emptyList());
            }

            String searchKey = product.getSearchKey();
            for (i = 0; i < chNumber; i++) {
                ProductCharacteristicConf prChConf = OBDal.getInstance().get(ProductCharacteristicConf.class,
                        currentValues[i]);
                ProductCharacteristicAux prChConfAux = prChUseCode.get(prChs.get(i));

                if (useCodes && prChConfAux.isUseCode()) {
                    searchKey += prChConf.getCode();
                }
            }
            for (int j = 0; j < (Long.toString(variantNumber).length()
                    - Integer.toString(productNo).length()); j++) {
                searchKey += "0";
            }
            searchKey += productNo;
            variant.setSearchKey(searchKey);
            OBDal.getInstance().save(variant);
            String strChDesc = "";
            for (i = 0; i < chNumber; i++) {
                ProductCharacteristicConf prChConf = OBDal.getInstance().get(ProductCharacteristicConf.class,
                        currentValues[i]);
                ProductCharacteristicValue newPrChValue = OBProvider.getInstance()
                        .get(ProductCharacteristicValue.class);
                newPrChValue.setCharacteristic(prChConf.getCharacteristicOfProduct().getCharacteristic());
                newPrChValue.setCharacteristicValue(prChConf.getCharacteristicValue());
                newPrChValue.setProduct(variant);
                newPrChValue.setOrganization(product.getOrganization());
                if (StringUtils.isNotBlank(strChDesc)) {
                    strChDesc += ", ";
                }
                strChDesc += prChConf.getCharacteristicOfProduct().getCharacteristic().getName() + ":";
                strChDesc += " " + prChConf.getCharacteristicValue().getName();
                OBDal.getInstance().save(newPrChValue);
                if (prChConf.getCharacteristicOfProduct().isDefinesPrice()
                        && prChConf.getNetUnitPrice() != null) {
                    setPrice(variant, prChConf.getNetUnitPrice(),
                            prChConf.getCharacteristicOfProduct().getPriceListType());
                }
                if (prChConf.getCharacteristicOfProduct().isDefinesImage() && prChConf.getImage() != null) {
                    Image newImage = (Image) DalUtil.copy(prChConf.getImage(), false);
                    OBDal.getInstance().save(newImage);
                    variant.setImage(newImage);
                }
            }
            variant.setCharacteristicDescription(strChDesc);
            OBDal.getInstance().save(variant);

            for (i = 0; i < chNumber; i++) {
                ProductCharacteristicAux prChConfAux = prChUseCode.get(prChs.get(i));
                currentValues[i] = prChConfAux.getNextValue();
                if (!prChConfAux.isIteratorReset()) {
                    break;
                } else if (i + 1 == chNumber) {
                    hasNext = false;
                }
            }
            productNo++;

            // Creates variants from 1 to 1000 and shows time spent on it.
            if (k == 1000) {
                OBDal.getInstance().flush();
                OBDal.getInstance().getSession().clear();
                log4j.debug("Variants loop: " + productNo + " : " + ((System.currentTimeMillis()) - (start)));
                k = 0;
                start = System.currentTimeMillis();
            }

        } while (hasNext);

        OBDal.getInstance().flush();
        OBDal.getInstance().getSession().clear();

        String message = OBMessageUtils.messageBD("variantsCreated");
        Map<String, String> map = new HashMap<String, String>();
        map.put("variantNo", Long.toString(productNo));
        msg.setMessage(OBMessageUtils.parseTranslation(message, map));
        bundle.setResult(msg);

        // Postgres wraps the exception into a GenericJDBCException
    } catch (GenericJDBCException ge) {
        log4j.error("Exception processing variant generation", ge);
        msg.setType("Error");
        msg.setTitle(
                OBMessageUtils.messageBD(bundle.getConnection(), "Error", bundle.getContext().getLanguage()));
        msg.setMessage(ge.getSQLException().getMessage());
        bundle.setResult(msg);
        OBDal.getInstance().rollbackAndClose();
        // Oracle wraps the exception into a QueryTimeoutException
    } catch (QueryTimeoutException qte) {
        log4j.error("Exception processing variant generation", qte);
        msg.setType("Error");
        msg.setTitle(
                OBMessageUtils.messageBD(bundle.getConnection(), "Error", bundle.getContext().getLanguage()));
        msg.setMessage(qte.getSQLException().getMessage().split("\n")[0]);
        bundle.setResult(msg);
        OBDal.getInstance().rollbackAndClose();
    } catch (final Exception e) {
        log4j.error("Exception processing variant generation", e);
        msg.setType("Error");
        msg.setTitle(
                OBMessageUtils.messageBD(bundle.getConnection(), "Error", bundle.getContext().getLanguage()));
        msg.setMessage(FIN_Utility.getExceptionMessage(e));
        bundle.setResult(msg);
        OBDal.getInstance().rollbackAndClose();
    }

}

From source file:org.openbravo.materialmgmt.VariantChDescUpdateProcess.java

License:Open Source License

@Override
public void doExecute(ProcessBundle bundle) throws Exception {
    OBError msg = new OBError();
    msg.setType("Success");
    msg.setTitle(OBMessageUtils.messageBD("Success"));

    try {//from  w w w. j  av a2s  .c o  m
        // retrieve standard params
        String strProductId = (String) bundle.getParams().get("mProductId");
        String strChValueId = (String) bundle.getParams().get("mChValueId");

        update(strProductId, strChValueId);

        bundle.setResult(msg);

        // Postgres wraps the exception into a GenericJDBCException
    } catch (GenericJDBCException ge) {
        log4j.error("Exception processing variant generation", ge);
        msg.setType("Error");
        msg.setTitle(
                OBMessageUtils.messageBD(bundle.getConnection(), "Error", bundle.getContext().getLanguage()));
        msg.setMessage(ge.getSQLException().getMessage());
        bundle.setResult(msg);
        OBDal.getInstance().rollbackAndClose();
        // Oracle wraps the exception into a QueryTimeoutException
    } catch (QueryTimeoutException qte) {
        log4j.error("Exception processing variant generation", qte);
        msg.setType("Error");
        msg.setTitle(
                OBMessageUtils.messageBD(bundle.getConnection(), "Error", bundle.getContext().getLanguage()));
        msg.setMessage(qte.getSQLException().getMessage().split("\n")[0]);
        bundle.setResult(msg);
        OBDal.getInstance().rollbackAndClose();
    } catch (final Exception e) {
        log4j.error("Exception processing variant generation", e);
        msg.setType("Error");
        msg.setTitle(
                OBMessageUtils.messageBD(bundle.getConnection(), "Error", bundle.getContext().getLanguage()));
        msg.setMessage(FIN_Utility.getExceptionMessage(e));
        bundle.setResult(msg);
        OBDal.getInstance().rollbackAndClose();
    }

}

From source file:org.openbravo.service.db.DbUtility.java

License:Open Source License

/**
 * This method will take care of finding the real underlying exception. When a jdbc or hibernate
 * exception occurs then the whole stack trace is not available in the log because the exception
 * does not return the underlying exception using the {@link Throwable#getCause()} but using the
 * {@link SQLException#getNextException()}.
 * /*from   w w  w  .j  av  a  2 s  . c o m*/
 * @param throwable
 *          the throwable to analyze
 * @return the underlying sql exception or the original throwable if none found
 */
public static Throwable getUnderlyingSQLException(Throwable throwable) {

    if (throwable.getCause() instanceof BatchUpdateException
            && ((BatchUpdateException) throwable.getCause()).getNextException() != null) {
        final BatchUpdateException bue = (BatchUpdateException) throwable.getCause();
        return bue.getNextException();
    }
    if (throwable.getCause() instanceof org.hibernate.exception.GenericJDBCException
            && ((org.hibernate.exception.GenericJDBCException) throwable.getCause()).getSQLException()
                    .getNextException() != null) {
        final org.hibernate.exception.GenericJDBCException gjdbce = (org.hibernate.exception.GenericJDBCException) throwable
                .getCause();
        return gjdbce.getSQLException().getNextException();
    }
    if (throwable.getCause() instanceof org.hibernate.exception.ConstraintViolationException
            && ((org.hibernate.exception.ConstraintViolationException) throwable.getCause()).getSQLException()
                    .getNextException() != null) {
        final org.hibernate.exception.ConstraintViolationException cve = (org.hibernate.exception.ConstraintViolationException) throwable
                .getCause();
        return cve.getSQLException().getNextException();
    }
    return throwable;
}

From source file:sernet.gs.ui.rcp.main.ExceptionUtil.java

License:Open Source License

public static void log(Throwable e, final String msg) {
    // log the error with log4j
    LOG.error("An error occured: " + msg, e);

    if (e instanceof StaleObjectStateException) {
        Display.getDefault().syncExec(new Runnable() {
            public void run() {
                MessageDialog.openError(Display.getDefault().getActiveShell(), Messages.ExceptionUtil_0,
                        Messages.ExceptionUtil_1);
            }/*from  w  w w. ja  va  2s .c  o  m*/
        });
        return;
    }

    if (e instanceof SecurityException) {
        Display.getDefault().syncExec(new Runnable() {
            public void run() {
                MessageDialog.openError(Display.getDefault().getActiveShell(), Messages.ExceptionUtil_2,
                        Messages.ExceptionUtil_3);
            }
        });
        return;
    }

    if (e instanceof CommandException && e.getCause() != null) {
        try {
            e = e.getCause();
        } catch (Exception castException) {
            // keep original exception
        }
    }

    String text = e.getLocalizedMessage() != null ? e.getLocalizedMessage() : Messages.ExceptionUtil_4;

    if (Activator.getDefault() == null) {
        // RCP not initialized
        return;
    }

    final MultiStatus errorStatus = new MultiStatus(Activator.getDefault().getBundle().getSymbolicName(),
            IStatus.ERROR, text, e);

    Status status;
    if (e instanceof GenericJDBCException) {
        GenericJDBCException jdbcEx = (GenericJDBCException) e;
        status = new Status(IStatus.ERROR, Activator.getDefault().getBundle().getSymbolicName(), IStatus.ERROR,
                jdbcEx.getSQLException().getMessage(), e);

    } else if (e.getStackTrace() != null) {
        status = new Status(IStatus.ERROR, Activator.getDefault().getBundle().getSymbolicName(), IStatus.ERROR,
                stackTraceToString(e), e);

    } else {
        status = new Status(IStatus.ERROR, Activator.getDefault().getBundle().getSymbolicName(), IStatus.ERROR,
                e.getMessage(), e);

    }

    errorStatus.add(status);
    Activator.getDefault().getLog().log(status);

    if (Activator.getDefault().getPluginPreferences().getBoolean(PreferenceConstants.ERRORPOPUPS)) {
        Display.getDefault().syncExec(new Runnable() {
            public void run() {
                ErrorDialog.openError(Display.getDefault().getActiveShell(), Messages.ExceptionUtil_5, msg,
                        errorStatus);
            }
        });
    }
}