Example usage for org.hibernate.criterion Restrictions sqlRestriction

List of usage examples for org.hibernate.criterion Restrictions sqlRestriction

Introduction

In this page you can find the example usage for org.hibernate.criterion Restrictions sqlRestriction.

Prototype

public static Criterion sqlRestriction(String sql) 

Source Link

Document

Apply a constraint expressed in SQL with no JDBC parameters.

Usage

From source file:org.jpos.ee.pm.core.DataAccessDB.java

License:Open Source License

public Object getItem(PMContext ctx, String property, String value) throws PMException {
    try {/*from   w  w w . j av a  2s  .  c  om*/
        DB db = getDb(ctx);
        Criteria c = db.session().createCriteria(Class.forName(getEntity(ctx).getClazz()));
        c.setMaxResults(1);
        c.add(Restrictions.sqlRestriction(property + "=" + value));
        return c.uniqueResult();
    } catch (ClassNotFoundException e) {
        return null;
    }
}

From source file:org.ktunaxa.referral.server.layer.FullTextCriteriaVisitor.java

License:Open Source License

@Override
public Object visit(PropertyIsLike filter, Object userData) {
    Expression expression = filter.getExpression();
    if (expression instanceof PropertyName) {
        String propertyName = ((PropertyName) expression).getPropertyName();
        String value = filter.getLiteral();
        if (KtunaxaConstant.ATTRIBUTE_FULL_TEXT.equalsIgnoreCase(propertyName)) {
            return Restrictions.sqlRestriction(
                    KtunaxaConstant.ATTRIBUTE_FULL_TEXT + " @@ " + "to_tsquery('" + value + ":*')");
        } else {/*from   www .  ja  v  a 2  s . c o m*/
            return super.visit(filter, userData);
        }
    } else {
        return super.visit(filter, userData);
    }
}

From source file:org.life.sl.routefinder.Label.java

License:Open Source License

/**
 * Retrieve the database IDs of nodes and edges
 * @see getNodeIDs_unordered()//from  w  ww  .j  a  va  2 s .c  o m
 * @return array with node IDs
 */
public int[] getNodeIDs() {
    if (nodeIDs == null) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        List<DirectedEdge> edges = getRouteAsEdges();
        int nEdges = edges.size();
        nodeIDs = new int[nEdges + 1];
        /*int n = 0, lastValidEdgeID = 0;
        for (DirectedEdge e : edges) {      // for each node along the route:
           @SuppressWarnings("unchecked")
           HashMap<String, Object> ed = (HashMap<String, Object>) e.getEdge().getData();
           int eID = (Integer)ed.get("id");
                
           Node node = e.getFromNode();   // node at beginning of edge
           Coordinate c_n = node.getCoordinate();
                
           // get node ID from database:
           // TODO: make this more efficient (now we have 2 queries per edge!)
           int nodeID = 0;
           if (n == nEdges-1 && eID < 0) {   // last edge may be split!
              eID = lastValidEdgeID;
           }
           if (eID > 0) {
              lastValidEdgeID = eID;
              String s = " from OSMEdge where id=" + eID;
              s = "from OSMNode where (id = (select fromnode"+s+") or id = (select tonode"+s+"))";
              Query nodeRes = session.createQuery(s);
              // TODO: make this more efficient using a PostGIS spatial query with indexing?
              // match coordinates:
              @SuppressWarnings("unchecked")
              Iterator<OSMNode> it = nodeRes.iterate();
              while (it.hasNext()) {
          OSMNode on = it.next();
          Coordinate onc = on.getGeometry().getCoordinate();
          if (Math.abs(c_n.x - onc.x) < kCoordEps && Math.abs(c_n.y - onc.y) < kCoordEps) {
             nodeID = on.getId();
             break;
          }                        
              }
           }   // now, nodeID is either 0 or the database ID of the corresponding node
           nodeIDs[n++] = nodeID;
        }
        for (int i : nodeIDs) System.out.print(i+"\t");System.out.println();
        nodeIDs = new int[nEdges + 1];*/

        //first, collect edge IDs:
        ArrayList<Integer> edgeIDs = new ArrayList<Integer>(nEdges);
        String se = "";
        for (DirectedEdge e : edges) { // for each node along the route:
            @SuppressWarnings("unchecked")
            HashMap<String, Object> ed = (HashMap<String, Object>) e.getEdge().getData();
            int eID = (Integer) ed.get("id");
            edgeIDs.add(eID);
            se += "," + eID;
        }
        se = se.substring(1); // remove leading comma
        String s = " from OSMEdge where id in (" + se + ")";
        Criteria cr = session.createCriteria(OSMNode.class);
        cr.add(Restrictions
                .sqlRestriction("(id in (select fromnode" + s + ") or id in (select tonode" + s + "))"));
        cr.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
        @SuppressWarnings("unchecked")
        List<OSMNode> osmNodes = cr.list();
        //for (OSMNode o : osmNodes) System.out.print(o.getId()+"\t");
        //System.out.println();

        List<Node> nodes = getNodes();
        Coordinate c = null, onc = null;
        int nodeID;
        int n = 0;
        for (Node nd : nodes) {
            c = nd.getCoordinate();
            nodeID = 0;
            for (OSMNode on : osmNodes) {
                onc = on.getGeometry().getCoordinate();
                if (Math.abs(c.x - onc.x) < kCoordEps && Math.abs(c.y - onc.y) < kCoordEps) {
                    nodeID = on.getId();
                    osmNodes.remove(onc); // we won't need this again, assuming each node occurs only once!
                    break;
                }
            }
            nodeIDs[n++] = nodeID;
        }
        //for (int i : nodeIDs) System.out.print(i+"\t");System.out.println();

        //session.getTransaction().commit();
    }

    //for (int i : nodeIDs) System.out.print(i+"\t"); System.out.println();
    return nodeIDs;
}

From source file:org.openeos.wf.internal.dao.WorkflowDefinitionDAOHibernateImpl.java

License:Apache License

@Override
@Transactional//from   www  .  j a v a 2  s .c o m
public WorkflowDefinition findLastByKey(String key) {
    Criteria crit = getSession().createCriteria(WorkflowDefinition.class);
    crit.add(Restrictions.eq(WorkflowDefinition.PROPERTY_VALUE, key));
    crit.add(Restrictions.sqlRestriction(
            "{alias}.version=(select max(version) from wf_definition alias_wf where alias_wf.value={alias}.value)"));
    return (WorkflowDefinition) crit.uniqueResult();
}

From source file:org.opennms.netmgt.scriptd.ins.events.InsAbstractSession.java

License:Open Source License

protected String getIfAlias(final int nodeid, final int ifindex) {

    LOG.debug("getting ifalias for nodeid: {} and ifindex: {}", nodeid, ifindex);

    setCriteria("nodeid = " + nodeid + " AND snmpifindex = " + ifindex);
    BeanFactoryReference bf = BeanUtils.getBeanFactory("daoContext");
    final SnmpInterfaceDao snmpInterfaceDao = BeanUtils.getBean(bf, "snmpInterfaceDao", SnmpInterfaceDao.class);
    final TransactionTemplate transTemplate = BeanUtils.getBean(bf, "transactionTemplate",
            TransactionTemplate.class);
    final List<OnmsSnmpInterface> iface = transTemplate
            .execute(new TransactionCallback<List<OnmsSnmpInterface>>() {
                public List<OnmsSnmpInterface> doInTransaction(final TransactionStatus status) {
                    final OnmsCriteria onmsCriteria = new OnmsCriteria(OnmsSnmpInterface.class);
                    onmsCriteria.add(Restrictions.sqlRestriction(getCriteria()));
                    return snmpInterfaceDao.findMatching(onmsCriteria);
                }//from w w w . j  a  va2 s . c  om
            });
    LOG.debug("interfaces found: {}", iface.size());

    if (iface.size() == 0)
        return "-1";
    final String ifAlias = iface.get(0).getIfAlias();
    LOG.debug("ifalias found: {}", ifAlias);

    return ifAlias;
}

From source file:org.opennms.netmgt.scriptd.ins.events.InsSession.java

License:Open Source License

private void getEventsByCriteria() {
    LOG.debug("clearing events");

    clearEvents();//from   w w  w .  jav a2 s  .  c  o m
    final BeanFactoryReference bf = BeanUtils.getBeanFactory("daoContext");
    final EventDao eventDao = BeanUtils.getBean(bf, "eventDao", EventDao.class);
    final TransactionTemplate transTemplate = BeanUtils.getBean(bf, "transactionTemplate",
            TransactionTemplate.class);
    try {
        transTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            public void doInTransactionWithoutResult(final TransactionStatus status) {
                LOG.debug("Entering transaction call back: selection with criteria: {}", criteriaRestriction);
                final OnmsCriteria criteria = new OnmsCriteria(OnmsEvent.class);
                criteria.add(Restrictions.sqlRestriction(criteriaRestriction));

                final List<OnmsEvent> events = eventDao.findMatching(criteria);
                LOG.info("Found {} event(s) with criteria: {}", events.size(), criteriaRestriction);

                for (final OnmsEvent onmsEvent : events) {
                    final Event xmlEvent = getXMLEvent(onmsEvent);
                    if (xmlEvent != null)
                        addEvent(xmlEvent);
                }
            }

        });

    } catch (final RuntimeException e) {
        LOG.error("Error while getting events.", e);
    }

}

From source file:org.opennms.netmgt.snmpinterfacepoller.DefaultPollContext.java

License:Open Source License

/** {@inheritDoc} */
public List<OnmsSnmpInterface> get(int nodeId, String criteria) {
    final OnmsCriteria onmsCriteria = new OnmsCriteria(OnmsSnmpInterface.class);
    onmsCriteria.add(Restrictions.sqlRestriction(criteria + " and nodeid = " + nodeId + "and snmppoll = 'P'"));
    return getSnmpInterfaceDao().findMatching(onmsCriteria);

}

From source file:org.opennms.netmgt.snmpinterfacepoller.DefaultPollContext.java

License:Open Source License

@Override
public List<OnmsIpInterface> getPollableNodesByIp(String ipaddr) {
    final OnmsCriteria criteria = new OnmsCriteria(OnmsIpInterface.class);
    criteria.add(Restrictions
            .sqlRestriction(" ipaddr = '" + ipaddr + "' and  issnmpprimary = 'P' and ismanaged='M'"));
    return getIpInterfaceDao().findMatching(criteria);
}

From source file:org.opennms.netmgt.snmpinterfacepoller.DefaultPollContext.java

License:Open Source License

@Override
public List<OnmsIpInterface> getPollableNodes() {
    final OnmsCriteria criteria = new OnmsCriteria(OnmsIpInterface.class);
    criteria.add(Restrictions.sqlRestriction("issnmpprimary = 'P' and ismanaged='M'"));
    return getIpInterfaceDao().findMatching(criteria);
}

From source file:org.opennms.web.svclayer.support.DefaultNodeListService.java

License:Open Source License

private static void addCriteriaForSnmpParm(OnmsCriteria criteria, String snmpParm, String snmpParmValue,
        String snmpParmMatchType) {
    criteria.createAlias("node.ipInterfaces", "ipInterface");
    criteria.add(Restrictions.ne("ipInterface.isManaged", "D"));

    criteria.createAlias("node.snmpInterfaces", "snmpInterface");
    criteria.add(Restrictions.ne("snmpInterface.collect", "D"));
    if (snmpParmMatchType.equals("contains")) {
        criteria.add(Restrictions.ilike("snmpInterface.".concat(snmpParm), snmpParmValue, MatchMode.ANYWHERE));
    } else if (snmpParmMatchType.equals("equals")) {
        snmpParmValue = snmpParmValue.toLowerCase();
        criteria.add(Restrictions.sqlRestriction(
                "{alias}.nodeid in (select nodeid from snmpinterface where snmpcollect != 'D' and lower(snmp"
                        + snmpParm + ") = '" + snmpParmValue + "')"));
    }/*from  w  w  w  .j a  va 2 s  . c o m*/
}