Example usage for org.hibernate SQLQuery setString

List of usage examples for org.hibernate SQLQuery setString

Introduction

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

Prototype

@Deprecated
@SuppressWarnings("unchecked")
default Query<R> setString(int position, String val) 

Source Link

Document

Bind a positional String-valued parameter.

Usage

From source file:com.cms.dao.AppParamsDAO.java

License:Open Source License

public List<AppParamsDTO> getListProviderFromMineName(String mineName, Map<String, String> map) {
    List<AppParamsDTO> listAppParams = null;
    String taxAuthority = map.get("taxAuthority");
    String startFromDate = map.get("startFromDate");
    String endFromDate = map.get("endFromDate");
    String startToDate = map.get("startToDate");
    String endToDate = map.get("endToDate");
    String fromDateRegister = map.get("fromDateRegister");
    String toDateRegister = map.get("toDateRegister");
    StringBuilder sb = new StringBuilder();
    sb.append("      SELECT    PAR_ID parId,   ");
    sb.append("              DESCRIPTION description,   ");
    sb.append("              PAR_CODE parCode,   ");
    sb.append("              PAR_NAME parName,   ");
    sb.append("              PAR_ORDER parOrder,   ");
    sb.append("              PAR_TYPE parType,   ");
    sb.append("              STATUS status   ");
    sb.append("        FROM APP_PARAMS a   ");
    sb.append("        WHERE a.PAR_TYPE = 'PROVIDER' ");
    sb.append("                     AND lower(a.PAR_CODE) = ANY   ");
    sb.append("              (SELECT DISTINCT lower(ti.PROVIDER)   ");
    sb.append("                 FROM TERM_INFORMATION ti   ");
    sb.append(//  w w  w . j a va2 s . c  o m
            "                 LEFT JOIN CUSTOMER_STATUS cs on ti.TAX_CODE=cs.TAX_CODE and ti.MINE_NAME = cs.MINE_NAME ");
    sb.append("                 JOIN CUSTOMER c on c.TAX_CODE = ti.TAX_CODE ");
    sb.append("                 WHERE ti.IS_CONTACT_INFO is null AND cs.TAX_CODE IS NULL   ");
    sb.append("                 AND ti.MINE_NAME = ANY (:mineName)   ");

    if (!DataUtil.isStringNullOrEmpty(taxAuthority)) {
        sb.append("         and c.TAX_AUTHORITY = ANY(:taxAuthority)   ");
    }

    if (!DataUtil.isStringNullOrEmpty(startFromDate)) {
        sb.append("         and ti.START_TIME >= TO_DATE(:startFromDate,'dd/MM/yyyy') - 1   ");
    }
    if (!DataUtil.isStringNullOrEmpty(endFromDate)) {
        sb.append("         and ti.START_TIME <= TO_DATE(:endFromDate,'dd/MM/yyyy')   + 1 ");
    }
    if (!DataUtil.isStringNullOrEmpty(startToDate)) {
        sb.append("         and ti.END_TIME >= TO_DATE(:startToDate,'dd/MM/yyyy') - 1    ");
    }
    if (!DataUtil.isStringNullOrEmpty(endToDate)) {
        sb.append("         and ti.END_TIME <= TO_DATE(:endToDate,'dd/MM/yyyy') + 1   ");
    }
    if (!DataUtil.isStringNullOrEmpty(fromDateRegister)) {
        sb.append("   AND ti.DATE_REGISTER >= TO_DATE(:fromDateRegister,'dd/MM/yyyy') - 1 ");
    }
    if (!DataUtil.isStringNullOrEmpty(toDateRegister)) {
        sb.append("   AND ti.DATE_REGISTER <= TO_DATE(:toDateRegister,'dd/MM/yyyy') + 1");
    }
    sb.append("              )   ");
    sb.append("        ORDER BY a.PAR_CODE asc   ");
    SQLQuery query;
    try {
        query = getSession().createSQLQuery(sb.toString());
        //Thuc hien chuyen du lieu lay ve thanh thanh doi tuong            
        query.setResultTransformer(Transformers.aliasToBean(AppParamsDTO.class));
        query.addScalar("parId", new StringType());
        query.addScalar("description", new StringType());
        query.addScalar("parCode", new StringType());
        query.addScalar("parName", new StringType());
        query.addScalar("parOrder", new StringType());
        query.addScalar("parType", new StringType());
        query.addScalar("status", new StringType());
        query.setParameterList("mineName", DataUtil.parseInputListString(mineName));
        if (!DataUtil.isStringNullOrEmpty(taxAuthority)) {
            query.setParameterList("taxAuthority", DataUtil.parseInputListString(taxAuthority));
        }
        if (!DataUtil.isStringNullOrEmpty(startFromDate)) {
            query.setString("startFromDate", startFromDate);
        }
        if (!DataUtil.isStringNullOrEmpty(endFromDate)) {
            query.setString("endFromDate", endFromDate);
        }
        if (!DataUtil.isStringNullOrEmpty(startToDate)) {
            query.setString("startToDate", startToDate);
        }
        if (!DataUtil.isStringNullOrEmpty(endToDate)) {
            query.setString("endToDate", endToDate);
        }
        if (!DataUtil.isStringNullOrEmpty(fromDateRegister)) {
            query.setString("fromDateRegister", fromDateRegister);
        }
        if (!DataUtil.isStringNullOrEmpty(toDateRegister)) {
            query.setString("toDateRegister", toDateRegister);
        }
        listAppParams = query.list();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return listAppParams;
}

From source file:com.cms.dao.TaxAuthorityDAO.java

License:Open Source License

public List<TaxAuthorityDTO> getListTaxAuthorityFromMineName(String mineName, Map<String, String> map) {
    String startFromDate = map.get("startFromDate");
    String provider = map.get("provider");
    String endFromDate = map.get("endFromDate");
    String startToDate = map.get("startToDate");
    String endToDate = map.get("endToDate");
    String fromDateRegister = map.get("fromDateRegister");
    String toDateRegister = map.get("toDateRegister");
    List<TaxAuthorityDTO> lstTaxAuthorities = null;
    StringBuilder sqlQuery = new StringBuilder();
    sqlQuery.append("       SELECT ID id,   ");
    sqlQuery.append("         MA_CQT maCqt,   ");
    sqlQuery.append("         MA_QUAN_HUYEN maQuanHuyen,   ");
    sqlQuery.append("         MA_TINH maTinh,   ");
    sqlQuery.append("         STATUS status,   ");
    sqlQuery.append("         TEN_CQT tenCqt   ");
    sqlQuery.append("       FROM TAX_AUTHORITY ta   ");
    sqlQuery.append("       WHERE ta.MA_CQT = ANY   ");
    sqlQuery.append("         ( SELECT DISTINCT c.TAX_AUTHORITY   ");
    sqlQuery.append("         FROM CUSTOMER c   ");
    sqlQuery.append("         JOIN    TERM_INFORMATION ti ON ti.TAX_CODE = c.TAX_CODE ");
    sqlQuery.append("           WHERE ti.IS_CONTACT_INFO is NULL AND ti.MINE_NAME = ANY (:mineName)   ");
    if (!DataUtil.isStringNullOrEmpty(provider)) {
        sqlQuery.append("         and lower(ti.PROVIDER) = ANY (:provider)   ");
    }/*from  ww  w.j a v  a  2 s. c  o  m*/
    if (!DataUtil.isStringNullOrEmpty(startFromDate)) {
        sqlQuery.append("         and ti.START_TIME >= TO_DATE(:startFromDate,'dd/MM/yyyy') - 1   ");
    }
    if (!DataUtil.isStringNullOrEmpty(endFromDate)) {
        sqlQuery.append("         and ti.START_TIME <= TO_DATE(:endFromDate,'dd/MM/yyyy') + 1    ");
    }
    if (!DataUtil.isStringNullOrEmpty(startToDate)) {
        sqlQuery.append("         and ti.END_TIME >= TO_DATE(:startToDate,'dd/MM/yyyy') - 1   ");
    }
    if (!DataUtil.isStringNullOrEmpty(endToDate)) {
        sqlQuery.append("         and ti.END_TIME <= TO_DATE(:endToDate,'dd/MM/yyyy')   + 1   ");
    }
    if (!DataUtil.isStringNullOrEmpty(fromDateRegister)) {
        sqlQuery.append("   AND ti.DATE_REGISTER >= TO_DATE(:fromDateRegister,'dd/MM/yyyy') - 1 ");
    }
    if (!DataUtil.isStringNullOrEmpty(toDateRegister)) {
        sqlQuery.append("   AND ti.DATE_REGISTER <= TO_DATE(:toDateRegister,'dd/MM/yyyy')  + 1");
    }
    sqlQuery.append("       AND NOT " + "                EXISTS ( " + "                    SELECT "
            + "                        cs.tax_code, " + "                        cs.mine_name "
            + "                    FROM " + "                        customer_status cs"
            + "                    WHERE " + "                            cs.tax_code = ti.tax_code "
            + "                        AND " + "                            cs.mine_name = ti.mine_name "
            + "                ) ");
    sqlQuery.append("       )  ");
    sqlQuery.append("       ORDER BY ta.TEN_CQT asc ");
    SQLQuery query;
    try {
        query = getSession().createSQLQuery(sqlQuery.toString());
        //Thuc hien chuyen du lieu lay ve thanh thanh doi tuong            
        query.setResultTransformer(Transformers.aliasToBean(TaxAuthorityDTO.class));
        query.addScalar("id", new StringType());
        query.addScalar("maCqt", new StringType());
        query.addScalar("maQuanHuyen", new StringType());
        query.addScalar("maTinh", new StringType());
        query.addScalar("status", new StringType());
        query.addScalar("tenCqt", new StringType());
        query.setParameterList("mineName", DataUtil.parseInputListString(mineName));
        if (!DataUtil.isStringNullOrEmpty(provider)) {
            query.setParameterList("provider", DataUtil.parseInputListString(provider.toLowerCase()));
        }
        if (!DataUtil.isStringNullOrEmpty(startFromDate)) {
            query.setString("startFromDate", startFromDate);
        }
        if (!DataUtil.isStringNullOrEmpty(endFromDate)) {
            query.setString("endFromDate", endFromDate);
        }
        if (!DataUtil.isStringNullOrEmpty(startToDate)) {
            query.setString("startToDate", startToDate);
        }
        if (!DataUtil.isStringNullOrEmpty(endToDate)) {
            query.setString("endToDate", endToDate);
        }
        if (!DataUtil.isStringNullOrEmpty(fromDateRegister)) {
            query.setString("fromDateRegister", fromDateRegister);
        }
        if (!DataUtil.isStringNullOrEmpty(toDateRegister)) {
            query.setString("toDateRegister", toDateRegister);
        }
        lstTaxAuthorities = query.list();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return lstTaxAuthorities;
}

From source file:com.duroty.application.mail.manager.MailManager.java

License:Open Source License

/**
 * DOCUMENT ME!// w w  w  .j a v a  2s  .c o m
 *
 * @param hsession DOCUMENT ME!
 * @param repositoryName DOCUMENT ME!
 * @param label DOCUMENT ME!
 * @param page DOCUMENT ME!
 * @param messagesByPage DOCUMENT ME!
 * @param order DOCUMENT ME!
 * @param orderType DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 *
 * @throws MailException DOCUMENT ME!
 */
public Vector getMessages(Session hsession, String repositoryName, Label label, int page, int messagesByPage,
        int order, String orderType) throws MailException {
    Vector messages = new Vector();

    try {
        Users user = getUser(hsession, repositoryName);
        Locale locale = new Locale(user.getUseLanguage());
        TimeZone timeZone = TimeZone.getDefault();

        Date now = new Date();
        Calendar calendar = Calendar.getInstance(timeZone, locale);
        calendar.setTime(now);

        SimpleDateFormat formatter1 = new SimpleDateFormat("MMM dd", locale);
        SimpleDateFormat formatter2 = new SimpleDateFormat("HH:mm:ss", locale);
        SimpleDateFormat formatter3 = new SimpleDateFormat("MM/yy", locale);

        Query hquery = hsession.getNamedQuery("messages-by-label");
        String aux = hquery.getQueryString();

        switch (order) {
        case ORDER_BY_IMPORTANT:

            if (orderType.equals("ASC")) {
                aux += " order by mes_flagged asc";
            } else {
                aux += " order by mes_flagged desc";
            }

            break;

        case ORDER_BY_ADDRESS:

            if (orderType.equals("ASC")) {
                aux += " order by mes_from asc";
            } else {
                aux += " order by mes_from desc";
            }

            break;

        case ORDER_BY_SIZE:

            if (orderType.equals("ASC")) {
                aux += " order by mes_size asc";
            } else {
                aux += " order by mes_size desc";
            }

            break;

        case ORDER_BY_SUBJECT:

            if (orderType.equals("ASC")) {
                aux += " order by mes_subject asc";
            } else {
                aux += " order by mes_subject desc";
            }

            break;

        case ORDER_BY_DATE:

            if (orderType.equals("ASC")) {
                aux += " order by mes_date asc";
            } else {
                aux += " order by mes_date desc";
            }

            break;

        case ORDER_BY_UNREAD:

            if (orderType.equals("ASC")) {
                aux += " order by mes_recent asc";
            } else {
                aux += " order by mes_recent desc";
            }

            break;

        default:
            aux += " order by mes_date desc";

            break;
        }

        SQLQuery h2query = hsession.createSQLQuery(aux);
        h2query.addEntity("i", Message.class);
        h2query.setInteger("label", label.getLabIdint());
        h2query.setInteger("user", user.getUseIdint());
        h2query.setString("folderTrash", this.folderTrash);
        h2query.setString("folderSpam", this.folderSpam);
        h2query.setString("folderDelete", FOLDER_DELETE);
        h2query.setFirstResult(page * messagesByPage);
        h2query.setMaxResults(messagesByPage);

        ScrollableResults scroll = h2query.scroll();

        while (scroll.next()) {
            Message message = (Message) scroll.get(0);

            MessageObj obj = new MessageObj(message.getMesName());

            obj.setBox(message.getMesBox());

            obj.setFrom(message.getMesFrom());

            if ((message.getAttachments() != null) && (message.getAttachments().size() > 0)) {
                obj.setHasAttachment(true);
            } else {
                obj.setHasAttachment(false);
            }

            int size = message.getMesSize();
            size /= 1024;

            if (size > 1024) {
                size /= 1024;
                obj.setSize(size + " MB");
            } else {
                obj.setSize(((size > 0) ? (size + "") : "<1") + " kB");
            }

            if (message.getMesBox().equals(folderSent)) {
                try {
                    obj.setEmail(message.getMesTo());
                } catch (Exception e) {
                    obj.setEmail("unknown to");
                }
            } else {
                obj.setEmail(message.getMesFrom());
            }

            Date date = message.getMesDate();

            if (date != null) {
                Calendar calendar2 = Calendar.getInstance(timeZone, locale);
                calendar2.setTime(date);

                if ((calendar.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR))
                        && (calendar.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH))
                        && (calendar.get(Calendar.DATE) == calendar2.get(Calendar.DATE))) {
                    obj.setDateStr(formatter2.format(calendar2.getTime()));
                } else if (calendar.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR)) {
                    obj.setDateStr(formatter1.format(calendar2.getTime()));
                } else {
                    obj.setDateStr(formatter3.format(calendar2.getTime()));
                }
            }

            obj.setDate(date);

            if (message.getLabMeses() != null) {
                Iterator it = message.getLabMeses().iterator();
                StringBuffer buff = new StringBuffer();

                while (it.hasNext()) {
                    if (buff.length() > 0) {
                        buff.append(", ");
                    }

                    LabMes labMes = (LabMes) it.next();
                    buff.append(labMes.getId().getLabel().getLabName());
                }

                obj.setLabel(buff.toString());
            }

            try {
                if (StringUtils.isBlank(message.getMesSubject())) {
                    obj.setSubject("(no subject)");
                } else {
                    obj.setSubject(message.getMesSubject());
                }
            } catch (Exception ex) {
                obj.setSubject("(no subject)");
            }

            if (message.isMesFlagged()) {
                obj.setFlagged(true);
            } else {
                obj.setFlagged(false);
            }

            if (message.isMesRecent()) {
                obj.setRecent(true);
            } else {
                obj.setRecent(false);
            }

            String priority = "normal";

            if (MessageUtilities.isHighPriority(message.getMesHeaders())) {
                priority = "high";
            } else if (MessageUtilities.isLowPriority(message.getMesHeaders())) {
                priority = "low";
            }

            obj.setPriority(priority);

            messages.addElement(obj);
        }

        return messages;
    } catch (Exception e) {
        throw new MailException(e);
    } finally {
        GeneralOperations.closeHibernateSession(hsession);
    }
}

From source file:com.edgenius.wiki.dao.hibernate.SpaceDAOHibernate.java

License:Open Source License

@SuppressWarnings("unchecked")
public List<Resource> getSpacePageResources(final String spaceUname) {
    SQLQuery query = getCurrentSesssion().createSQLQuery(NATIVE_GET_PAGE_RESOURCE_BY_SPACE)
            .addEntity(Resource.class);
    query.setString("spaceUname", spaceUname);
    return query.list();
}

From source file:com.emergya.persistenceGeo.dao.impl.PostgisDBManagementDaoHibernateImpl.java

License:Open Source License

/**
 * Gets a postgis table geometry type.// w ww. j  ava2  s  . co  m
 * 
 * @param tableName
 * @return
 */
@Override
public GeometryType getTableGeometryType(String tableName) {
    SQLQuery query = getSession().createSQLQuery(GEOMETRY_TYPE_SQL);
    query.setString("NAME", tableName);

    String dbType = ((String) query.uniqueResult()).toUpperCase();

    if (StringUtils.contains(dbType, "POINT")) {
        return GeometryType.POINT;
    } else if (StringUtils.contains(dbType, "LINE")) {
        return GeometryType.LINESTRING;
    } else if (StringUtils.contains(dbType, "POLYGON")) {
        return GeometryType.POLYGON;
    } else {
        throw new IllegalStateException(
                String.format("Type %s is not a PersistenceGeo supported GeometryType.", dbType));
    }
}

From source file:com.emergya.persistenceGeo.dao.impl.PostgisDBManagementDaoHibernateImpl.java

License:Open Source License

private BoundingBox calculateBBox(String sql, String tableName) {
    SQLQuery query = getSession().createSQLQuery(sql);

    String result = (String) query.uniqueResult();
    BoundingBox bbox = new BoundingBox();
    if (result == null) { // if layer is empty
        bbox.setMinx(-180);// w w w .  ja  v a  2 s . c  om
        bbox.setMiny(-90);
        bbox.setMaxx(180);
        bbox.setMaxy(90);
    } else {
        result = result.replace("BOX", "");
        result = result.replace("(", "").replace(")", "");
        result = result.replace(" ", ",");
        String[] coords = result.split(",");
        if (coords[0].equals(coords[2]) && coords[1].equals(coords[3])) { // layer
            // store
            // one
            // point
            bbox.setMinx((Double.valueOf(coords[0]) / 2) - 0.75);
            bbox.setMiny((Double.valueOf(coords[1]) / 2) - 0.75);
            bbox.setMaxx((Double.valueOf(coords[2]) / 2) + 0.75);
            bbox.setMaxy((Double.valueOf(coords[3]) / 2) + 0.75);
        } else {
            bbox.setMinx(Double.valueOf(coords[0]));
            bbox.setMiny(Double.valueOf(coords[1]));
            bbox.setMaxx(Double.valueOf(coords[2]));
            bbox.setMaxy(Double.valueOf(coords[3]));
        }
    }

    query = getSession().createSQLQuery(SRID_SQL);
    query.setString("NAME", tableName);
    Integer srid = (Integer) query.uniqueResult();

    bbox.setSrs("EPSG:" + srid);

    return bbox;
}

From source file:com.evolveum.midpoint.repo.sql.DeleteTest.java

License:Apache License

@Test
public void delete0003() throws Exception {
    PrismObject<ShadowType> shadow = prismContext.parseObject(new File(FOLDER_BASE, "delete/shadow.xml"));

    OperationResult result = new OperationResult("add shadow");
    final String oid = repositoryService.addObject(shadow, null, result);

    PrismObject<ShadowType> repoShadow = repositoryService.getObject(ShadowType.class, oid, null, result);
    shadow = prismContext.parseObject(new File(FOLDER_BASE, "delete/shadow.xml"));
    AssertJUnit.assertEquals(shadow, repoShadow);

    repositoryService.deleteObject(ShadowType.class, oid, result);
    result.recomputeStatus();//from www .  j av a 2  s . c  o m

    AssertJUnit.assertTrue(result.isSuccess());

    Session session = getFactory().openSession();
    try {
        SQLQuery query = session.createSQLQuery("select count(*) from m_trigger where owner_oid = ?");
        query.setString(0, oid);

        Number count = (Number) query.uniqueResult();
        AssertJUnit.assertEquals(count.longValue(), 0L);
    } finally {
        session.close();
    }
}

From source file:com.evolveum.midpoint.repo.sql.helpers.ObjectRetriever.java

License:Apache License

public <T extends ObjectType> PrismObject<T> getObjectInternal(Session session, Class<T> type, String oid,
        Collection<SelectorOptions<GetOperationOptions>> options, boolean lockForUpdate,
        OperationResult operationResult)
        throws ObjectNotFoundException, SchemaException, DtoTranslationException {

    boolean lockedForUpdateViaHibernate = false;
    boolean lockedForUpdateViaSql = false;

    LockOptions lockOptions = new LockOptions();
    //todo fix lock for update!!!!!
    if (lockForUpdate) {
        if (getConfiguration().isLockForUpdateViaHibernate()) {
            lockOptions.setLockMode(LockMode.PESSIMISTIC_WRITE);
            lockedForUpdateViaHibernate = true;
        } else if (getConfiguration().isLockForUpdateViaSql()) {
            LOGGER.trace("Trying to lock object {} for update (via SQL)", oid);
            long time = System.currentTimeMillis();
            SQLQuery q = session.createSQLQuery("select oid from m_object where oid = ? for update");
            q.setString(0, oid);
            Object result = q.uniqueResult();
            if (result == null) {
                return throwObjectNotFoundException(type, oid);
            }/*from  ww  w .  j  a  v  a  2 s  . co  m*/
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Locked via SQL (in {} ms)", System.currentTimeMillis() - time);
            }
            lockedForUpdateViaSql = true;
        }
    }

    if (LOGGER.isTraceEnabled()) {
        if (lockedForUpdateViaHibernate) {
            LOGGER.trace("Getting object {} with locking for update (via hibernate)", oid);
        } else if (lockedForUpdateViaSql) {
            LOGGER.trace("Getting object {}, already locked for update (via SQL)", oid);
        } else {
            LOGGER.trace("Getting object {} without locking for update", oid);
        }
    }

    GetObjectResult fullObject = null;
    if (!lockForUpdate) {
        Query query = session.getNamedQuery("get.object");
        query.setString("oid", oid);
        query.setResultTransformer(GetObjectResult.RESULT_TRANSFORMER);
        query.setLockOptions(lockOptions);

        fullObject = (GetObjectResult) query.uniqueResult();
    } else {
        // we're doing update after this get, therefore we load full object right now
        // (it would be loaded during merge anyway)
        // this just loads object to hibernate session, probably will be removed later. Merge after this get
        // will be faster. Read and use object only from fullObject column.
        // todo remove this later [lazyman]
        Criteria criteria = session.createCriteria(ClassMapper.getHQLTypeClass(type));
        criteria.add(Restrictions.eq("oid", oid));

        criteria.setLockMode(lockOptions.getLockMode());
        RObject obj = (RObject) criteria.uniqueResult();

        if (obj != null) {
            obj.toJAXB(prismContext, null).asPrismObject();
            fullObject = new GetObjectResult(obj.getFullObject(), obj.getStringsCount(), obj.getLongsCount(),
                    obj.getDatesCount(), obj.getReferencesCount(), obj.getPolysCount(), obj.getBooleansCount());
        }
    }

    LOGGER.trace("Got it.");
    if (fullObject == null) {
        throwObjectNotFoundException(type, oid);
    }

    LOGGER.trace("Transforming data to JAXB type.");
    PrismObject<T> prismObject = updateLoadedObject(fullObject, type, oid, options, session, operationResult);
    validateObjectType(prismObject, type);

    // this was implemented to allow report parsing errors as warnings to upper layers;
    // however, it causes problems when serialization problems are encountered: in such cases, we put
    // FATAL_ERROR to the result here, and it should be then removed or muted (which is a complication)
    // -- so, as the parsing errors are not implemented, we disabled this code as well

    //         subResult.computeStatusIfUnknown();
    //         if (subResult.isWarning() || subResult.isError() || subResult.isInProgress()) {
    //            prismObject.asObjectable().setFetchResult(subResult.createOperationResultType());
    //         }

    return prismObject;
}

From source file:com.evolveum.midpoint.repo.sql.helpers.ObjectUpdater.java

License:Apache License

private <T extends ObjectType> String nonOverwriteAddObjectAttempt(PrismObject<T> object, RObject rObject,
        String originalOid, Session session, OrgClosureManager.Context closureContext)
        throws ObjectAlreadyExistsException, SchemaException, DtoTranslationException {

    // check name uniqueness (by type)
    if (StringUtils.isNotEmpty(originalOid)) {
        LOGGER.trace("Checking oid uniqueness.");
        //todo improve this table name bullshit
        Class hqlType = ClassMapper.getHQLTypeClass(object.getCompileTimeClass());
        SQLQuery query = session
                .createSQLQuery("select count(*) from " + RUtil.getTableName(hqlType) + " where oid=:oid");
        query.setString("oid", object.getOid());

        Number count = (Number) query.uniqueResult();
        if (count != null && count.longValue() > 0) {
            throw new ObjectAlreadyExistsException("Object '" + object.getCompileTimeClass().getSimpleName()
                    + "' with oid '" + object.getOid() + "' already exists.");
        }//  w  ww .  j  a  v  a  2 s. c om
    }

    updateFullObject(rObject, object);

    LOGGER.trace("Saving object (non overwrite).");
    String oid = (String) session.save(rObject);
    lookupTableHelper.addLookupTableRows(session, rObject, false);
    caseHelper.addCertificationCampaignCases(session, rObject, false);

    if (closureManager.isEnabled()) {
        Collection<ReferenceDelta> modifications = createAddParentRefDelta(object);
        closureManager.updateOrgClosure(null, modifications, session, oid, object.getCompileTimeClass(),
                OrgClosureManager.Operation.ADD, closureContext);
    }

    return oid;
}

From source file:com.evolveum.midpoint.repo.sql.SqlRepositoryServiceImpl.java

License:Apache License

private <T extends ObjectType> PrismObject<T> getObject(Session session, Class<T> type, String oid,
        Collection<SelectorOptions<GetOperationOptions>> options, boolean lockForUpdate)
        throws ObjectNotFoundException, SchemaException, DtoTranslationException, QueryException {

    boolean lockedForUpdateViaHibernate = false;
    boolean lockedForUpdateViaSql = false;

    LockOptions lockOptions = new LockOptions();
    //todo fix lock for update!!!!!
    if (lockForUpdate) {
        if (getConfiguration().isLockForUpdateViaHibernate()) {
            lockOptions.setLockMode(LockMode.PESSIMISTIC_WRITE);
            lockedForUpdateViaHibernate = true;
        } else if (getConfiguration().isLockForUpdateViaSql()) {
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Trying to lock object " + oid + " for update (via SQL)");
            }/*from ww  w .  j a v a2 s  . co m*/
            long time = System.currentTimeMillis();
            SQLQuery q = session.createSQLQuery("select oid from m_object where oid = ? for update");
            q.setString(0, oid);
            Object result = q.uniqueResult();
            if (result == null) {
                return throwObjectNotFoundException(type, oid);
            }
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace("Locked via SQL (in " + (System.currentTimeMillis() - time) + " ms)");
            }
            lockedForUpdateViaSql = true;
        }
    }

    if (LOGGER.isTraceEnabled()) {
        if (lockedForUpdateViaHibernate) {
            LOGGER.trace("Getting object " + oid + " with locking for update (via hibernate)");
        } else if (lockedForUpdateViaSql) {
            LOGGER.trace("Getting object " + oid + ", already locked for update (via SQL)");
        } else {
            LOGGER.trace("Getting object " + oid + " without locking for update");
        }
    }

    GetObjectResult fullObject = null;
    if (!lockForUpdate) {
        Query query = session.getNamedQuery("get.object");
        query.setString("oid", oid);
        query.setResultTransformer(GetObjectResult.RESULT_TRANSFORMER);
        query.setLockOptions(lockOptions);

        fullObject = (GetObjectResult) query.uniqueResult();
    } else {
        // we're doing update after this get, therefore we load full object right now
        // (it would be loaded during merge anyway)
        // this just loads object to hibernate session, probably will be removed later. Merge after this get
        // will be faster. Read and use object only from fullObject column.
        // todo remove this later [lazyman]
        Criteria criteria = session.createCriteria(ClassMapper.getHQLTypeClass(type));
        criteria.add(Restrictions.eq("oid", oid));

        criteria.setLockMode(lockOptions.getLockMode());
        RObject obj = (RObject) criteria.uniqueResult();

        if (obj != null) {
            obj.toJAXB(getPrismContext(), null).asPrismObject();
            fullObject = new GetObjectResult(obj.getFullObject(), obj.getStringsCount(), obj.getLongsCount(),
                    obj.getDatesCount(), obj.getReferencesCount(), obj.getPolysCount());
        }
    }

    LOGGER.trace("Got it.");
    if (fullObject == null) {
        throwObjectNotFoundException(type, oid);
    }

    LOGGER.trace("Transforming data to JAXB type.");
    PrismObject<T> prismObject = updateLoadedObject(fullObject, type, options, session);
    validateObjectType(prismObject, type);

    return prismObject;
}