@Test public void testData() throws Exception { final String INDEX_NAME = "dataIndex"; IndexManager indexManager = new IndexManager(TEST_UTIL.getConfiguration()); IndexDefinition indexDef = new IndexDefinition(INDEX_NAME, INDEX_NAME); indexDef.addStringField("field1"); indexManager.createIndex(indexDef); Index index = indexManager.getIndex(INDEX_NAME, INDEX_NAME); String[] values = new String[] {"foo", "bar"}; for (String value : values) { IndexEntry entry = new IndexEntry(); entry.addField("field1", value); entry.addData(Bytes.toBytes("originalValue"), Bytes.toBytes(value)); index.addEntry(entry, Bytes.toBytes(value)); } Query query = new Query(); query.setRangeCondition("field1", Query.MIN_VALUE, Query.MAX_VALUE); QueryResult result = index.performQuery(query); assertNotNull(result.next()); assertEquals("bar", result.getDataAsString("originalValue")); assertNotNull(result.next()); assertEquals("foo", result.getDataAsString("originalValue")); }
@Override public List<Forum> getForumsOfaUser(int userId) { // TODO Auto-generated method stub List<Forum> forums = new ArrayList<Forum>(); Session session = sessionFactory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); Query query = session.createQuery("from Subscription where userId = :userId"); query.setString("userId", String.valueOf(userId)); List<Subscription> userSubscribedGroups = query.list(); for (Subscription subsc : userSubscribedGroups) { query = session.createQuery("from Forum where forumId = :forumId"); query.setParameter("forumId", subsc.getForumId()); // add this to a list variable query.uniqueResult(); forums.add((Forum) query.uniqueResult()); } } catch (HibernateException e) { if (tx != null) { tx.rollback(); e.printStackTrace(); } } finally { session.close(); } return forums; }
public void testDescendOne() { Query q = st.query(); Object[] r = store(); q.constrain(STVectorEU.class); q.descend("col").constrain(new Integer(17)); st.expect(q, new Object[] {r[0]}); }
@SuppressWarnings("unchecked") private ObjectSet executeSODAQuery(final A a, Evaluation e) { Query q = db().query(); q.constrain(e); ObjectSet set = q.execute(); return set; }
@Override public void deleteSubscription(int userId, int forumId) { // TODO Auto-generated method stub Session session = this.sessionFactory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); Query query = session.createQuery( "delete from Subscription where userId = :userId and forumId = :forumId"); query.setParameter("userId", userId); query.setParameter("forumId", forumId); int result = query.executeUpdate(); System.out.println("Execute query.."); if (result > 0) { tx.commit(); // System.out.println("Subscription Removed.."); } else { // System.out.println("Subscription does not exist"); tx.rollback(); } } catch (HibernateException e) { if (tx != null) { tx.rollback(); e.printStackTrace(); } } finally { session.close(); } }
@Test public void testToString() { Query query = new Query(); query.setManufacturer("a"); query.setComponent("b"); assertEquals(query.toString(), "(Query (a,b))"); }
@Test public void testExecuteOnDBConnection() throws IOException { Query<Organisation> query = new Query<Organisation>(Organisation.class); query.clear(); query.add(Organisation.FLD_NAME1, "=", "orgname2"); // create a new DBConnection DBConnection connection = new DBConnection(); connection.setDBConnectString("jdbc:h2:mem:test_query_mem"); connection.setDBUser("sa"); connection.setDBPassword(""); assertTrue(connection.connect()); initElexisDatabase(connection); List<Organisation> result = query.execute(connection); assertEquals(0, result.size()); DBConnection initialConnection = PersistentObject.getDefaultConnection(); // change default connection of PersistenObject and create an Organization PersistentObject.connect(connection); new Organisation("orgname2", "orgzusatz1"); result = query.execute(connection); assertEquals(1, result.size()); // cleanup new connection and reset to initial connection PersistentObject.disconnect(); PersistentObject.connect(initialConnection); }
private Collection<GroupData> fetchGroupDataForUser( final User user, final boolean restrictToSuscribed) { final String ifConnectedColumns = "max(ifnull(USER_ID=:userId, false))>0, sum(ifnull(USER_ID=:userId AND LAST_VISIT<PUBLIC_MESSAGES.`DATE`, false))"; final Query query = entityManager.createNativeQuery( "select GROUPS.ID, name, count(DISTINCT GROUP_USER.USER_ID), " + (user != null ? ifConnectedColumns : " 0,0") + " from GROUPS left join GROUP_USER on GROUP_ID=ID " + " left join PUBLIC_MESSAGES on PUBLIC_MESSAGES.GROUP_ID=GROUP_USER.GROUP_ID " + (restrictToSuscribed ? " where GROUP_USER.USER_ID=:userId" : "") + " group by GROUPS.ID order by CREATION_DATE"); if (user != null) query.setParameter("userId", user.getId()); final List<Object[]> list = query.getResultList(); final Collection<GroupData> result = new ArrayList<GroupData>(list.size()); for (final Object[] o : list) result.add( new GroupData( ((Number) o[0]).longValue(), UserStringImpl.valueOf(String.valueOf(o[1])), ((Number) o[2]).longValue(), ((Number) o[3]).intValue() != 0, ((Number) o[4]).intValue())); return result; }
private PaginatedCollection<User> fetchGroupMembers(final Group group) { final String queryString = "select u from GroupImpl g inner join g.members u where g=:group order by u.name"; final Query query = query(queryString); query.setParameter("group", group); return paginateList(0, 100, query.getResultList()); }
public <E extends BaseEntity> List<E> find(String ql, Object... args) { Query query = createQuery(ql, args); @SuppressWarnings("unchecked") List<E> resultList = query.getResultList(); return resultList; }
public List<NewMessageData> fetchNewMessagesCount(final User user) { final Query query = query( "select new com.nraynaud.sport.data.NewMessageData(m.sender.name, count(m)) from PrivateMessageImpl m where m.receiver = :user and m.read = false group by m.sender.name"); query.setParameter("user", user); return query.getResultList(); }
@PooledConnection public JSONArray getRowsWithQuery( String keyspace, String columnFamily, String queryStr, ConsistencyLevel consistencyLevel) throws InvalidRequestException, UnavailableException, TimedOutException, TException, CharacterCodingException { Query query = QueryParser.parse(queryStr); SlicePredicate predicate = new SlicePredicate(); SliceRange range = new SliceRange(ByteBufferUtil.bytes(""), ByteBufferUtil.bytes(""), false, MAX_COLUMNS); predicate.setSlice_range(range); ColumnParent parent = new ColumnParent(columnFamily); IndexClause indexClause = new IndexClause(); indexClause.setCount(MAX_ROWS); indexClause.setStart_key(new byte[0]); for (String keyName : query.getEqStmt().keySet()) { indexClause.addToExpressions( new IndexExpression( ByteBufferUtil.bytes(keyName), IndexOperator.EQ, ByteBufferUtil.bytes(query.getEqStmt().get(keyName)))); } List<KeySlice> rows = getConnection(keyspace) .get_indexed_slices(parent, indexClause, predicate, ConsistencyLevel.QUORUM); return JsonMarshaller.marshallRows(rows, true); }
public static MInfoWindow get(String tableName, String trxName) { Query query = new Query( Env.getCtx(), MTable.get(Env.getCtx(), MInfoWindow.Table_ID), MInfoWindow.COLUMNNAME_AD_Table_ID + "=? AND IsValid='Y' ", null); MTable table = MTable.get(Env.getCtx(), tableName); if (table != null) { List<MInfoWindow> iws = query .setParameters(table.getAD_Table_ID()) .setOrderBy( "AD_Client_ID Desc, AD_Org_ID Desc, IsDefault Desc, AD_InfoWindow_ID Desc") .setOnlyActiveRecords(true) .setApplyAccessFilter(true) .list(); // verify role has access and return the first with access / IDEMPIERE-893 for (MInfoWindow iw : iws) { Boolean access = MRole.getDefault().getInfoAccess(iw.getAD_InfoWindow_ID()); if (access != null && access.booleanValue()) return iw; } } return null; }
@Override protected boolean beforeSave(boolean newRecord) { AccessSqlParser parser = new AccessSqlParser("SELECT * FROM " + getFromClause()); TableInfo[] tableInfos = parser.getTableInfo(0); if (tableInfos == null || tableInfos.length == 0) { log.saveError("ParseFromClauseError", "Failed to parse from clause"); return false; } // only one default per table if (newRecord || is_ValueChanged("IsDefault")) { if (isDefault()) { if (newRecord) { Query query = new Query( getCtx(), MTable.get(getCtx(), Table_ID), "AD_Table_ID=? AND IsDefault='Y' AND AD_Client_ID=?", get_TrxName()); List<MInfoWindow> list = query.setParameters(getAD_Table_ID(), getAD_Client_ID()).list(); for (MInfoWindow iw : list) { iw.setIsDefault(false); iw.saveEx(); } } else { Query query = new Query( getCtx(), MTable.get(getCtx(), Table_ID), "AD_InfoWindow_ID<>? AND AD_Table_ID=? AND IsDefault='Y' AND AD_Client_ID=?", get_TrxName()); List<MInfoWindow> list = query .setParameters(getAD_InfoWindow_ID(), getAD_Table_ID(), getAD_Client_ID()) .list(); for (MInfoWindow iw : list) { iw.setIsDefault(false); iw.saveEx(); } } } } // evaluate need valid boolean isNeedValid = is_new() || is_ValueChanged(I_AD_InfoWindow.COLUMNNAME_AD_Table_ID) || is_ValueChanged(I_AD_InfoWindow.COLUMNNAME_WhereClause) || is_ValueChanged(I_AD_InfoWindow.COLUMNNAME_FromClause) || is_ValueChanged(I_AD_InfoWindow.COLUMNNAME_OrderByClause) || is_ValueChanged(I_AD_InfoWindow.COLUMNNAME_OtherClause) || is_ValueChanged(I_AD_InfoWindow.COLUMNNAME_IsDistinct); // valid config if (isNeedValid) { validate(); } return true; }
@Test public void groupTitleSearch() throws Exception { UUID applicationId = createApplication("testOrganization", "groupTitleSearch"); assertNotNull(applicationId); EntityManager em = emf.getEntityManager(applicationId); assertNotNull(em); String titleName = "groupName" + UUIDUtils.newTimeUUID(); Map<String, Object> properties = new LinkedHashMap<String, Object>(); properties.put("title", titleName); properties.put("path", "testPath"); properties.put("name", "testName"); Entity group = em.create("group", properties); assertNotNull(group); // EntityRef Query query = new Query(); query.addEqualityFilter("title", titleName); Results r = em.searchCollection(em.getApplicationRef(), "groups", query); assertTrue(r.size() > 0); Entity returned = r.getEntities().get(0); assertEquals(group.getUuid(), returned.getUuid()); }
private Double fetchGlobalDistance(final Group group) { final Query query = query( "select sum(w.distance) from GroupImpl g left join g.members u left join u.workouts w where g=:group"); query.setParameter("group", group); return (Double) query.getSingleResult(); }
private void checkForSharedSourceCommand(AccessNode aNode) { // create a top level key to avoid the full command toString String modelName = aNode.getModelName(); Command cmd = aNode.getCommand(); // don't share full scans against internal sources, it's a waste of buffering if (CoreConstants.SYSTEM_MODEL.equals(modelName) || CoreConstants.SYSTEM_ADMIN_MODEL.equals(modelName) || TempMetadataAdapter.TEMP_MODEL.getName().equals(modelName)) { if (!(cmd instanceof Query)) { return; } Query query = (Query) cmd; if (query.getOrderBy() == null && query.getCriteria() == null) { return; } } AccessNode other = sharedCommands.get(cmd); if (other == null) { sharedCommands.put(cmd, aNode); } else { if (other.info == null) { other.info = new RegisterRequestParameter.SharedAccessInfo(); other.info.id = sharedId.getAndIncrement(); } other.info.sharingCount++; aNode.info = other.info; } }
private Collection<ConversationSummary> fetchCorrespondents(final User user) { final Map<String, ConversationSummary> correspondants = new HashMap<String, ConversationSummary>(); { final Query query = query( "select m.sender.name, m.receiver.name, count(m), m.read from PrivateMessageImpl m where (m.receiver=:user OR " + "(m.sender=:user)) AND(m.deleter IS NULL OR m.deleter <> :user) " + "group by m.sender.name, m.receiver.name, m.read"); query.setParameter("user", user); for (final Object[] row : (List<Object[]>) query.getResultList()) { final boolean sent = row[0].equals(((UserImpl) user).getBareName()); final String name = (String) (sent ? row[1] : row[0]); final ConversationSummary previous = correspondants.get(name); final long count = ((Number) row[2]).longValue(); final long newCount; if (row[3].equals(Boolean.FALSE) && !sent) newCount = count; else newCount = 0; if (previous != null) { correspondants.put( name, new ConversationSummary( UserStringImpl.valueOf(name), count + previous.messageCount, newCount + previous.newMessageCount)); } else correspondants.put( name, new ConversationSummary(UserStringImpl.valueOf(name), count, newCount)); } } return new TreeSet<ConversationSummary>(correspondants.values()); }
// FIXME public void _testDescendOne() { Query q = newQuery(); q.constrain(STVectorEU.class); q.descend("col").constrain(new Integer(17)); expect(q, new int[] {0}); }
private void separatePrivateMessagesFromWorkout(final Long id) { final Query query = entityManager.createNativeQuery( "UPDATE MESSAGES SET WORKOUT_ID=NULL WHERE WORKOUT_ID=:id AND RECEIVER_ID IS NOT NULL"); query.setParameter("id", id); query.executeUpdate(); }
private String getFolio(Almacen almacen) { Query query = currentSession() .createQuery( "select f from Folio f where f.nombre = :nombre and f.almacen.id = :almacenId"); query.setString("nombre", "FACTURA"); query.setLong("almacenId", almacen.getId()); query.setLockOptions(LockOptions.UPGRADE); Folio folio = (Folio) query.uniqueResult(); if (folio == null) { folio = new Folio("FACTURA"); folio.setAlmacen(almacen); currentSession().save(folio); return getFolio(almacen); } folio.setValor(folio.getValor() + 1); java.text.NumberFormat nf = java.text.DecimalFormat.getInstance(); nf.setGroupingUsed(false); nf.setMinimumIntegerDigits(9); nf.setMaximumIntegerDigits(9); nf.setMaximumFractionDigits(0); StringBuilder sb = new StringBuilder(); sb.append("FA-"); sb.append(almacen.getEmpresa().getOrganizacion().getCodigo()); sb.append(almacen.getEmpresa().getCodigo()); sb.append(almacen.getCodigo()); sb.append(nf.format(folio.getValor())); return sb.toString(); }
public void testDescendToObject() { Query q = st.query(); Object[] r = store(); q.constrain(new STHashtableT()); q.descend("col").descend("foo1").constrain("bar"); st.expect(q, new Object[] {r[5], r[6]}); }
@Override public List<Reply> getRepliesToPost(int postId) { // TODO Auto-generated method stub Session session = sessionFactory.openSession(); Transaction tx = null; List<Reply> replyArr = new ArrayList<Reply>(); try { tx = session.beginTransaction(); Query query = session.createQuery("from Reply where postId = :postId order by createdDate desc"); query.setParameter("postId", postId); replyArr = query.list(); /* for(Reply reply : replyArr){ System.out.println("Reply - id----"+reply.getReplyId()); System.out.println("Reply - Description----"+reply.getDescription()); System.out.println("Reply - Post id----"+reply.getPostId()); }*/ } catch (HibernateException e) { if (tx != null) { tx.rollback(); e.printStackTrace(); } } finally { session.close(); } return replyArr; }
@Test public void testRedefineTerms() throws Exception { UUID applicationId = createApplication("testOrganization", "testRedefineTerms"); EntityManager em = emf.getEntityManager(applicationId); Map<String, Object> properties = new LinkedHashMap<String, Object>(); properties.put("username", "edanuff"); properties.put("email", "*****@*****.**"); em.create("user", properties); String s = "select {name: username, email: email} where username = '******'"; Query query = Query.fromQL(s); Results r = em.searchCollection(em.getApplicationRef(), "users", query); assertTrue(r.size() == 1); // selection results should be a list of lists List<Object> sr = query.getSelectionResults(r); assertTrue(sr.size() == 1); Map firstResult = (Map) sr.get(0); assertTrue("edanuff".equals(firstResult.get("name"))); assertTrue("*****@*****.**".equals(firstResult.get("email"))); }
public int getCountOfSubscribers(int forumId, int userId) { // TODO Auto-generated method stub Session session = this.sessionFactory.openSession(); Transaction tx = null; int countOfSubscribers = 0; try { tx = session.beginTransaction(); Query query = null; if (userId == 0) { query = session.createQuery("select count(*) from Subscription where forumId = :forumId"); query.setParameter("forumId", forumId); } else { query = session.createQuery( "select count(*) from Subscription where forumId = :forumId and userId = :userId"); query.setParameter("forumId", forumId); query.setParameter("userId", userId); } Long count = (Long) query.uniqueResult(); countOfSubscribers = count.intValue(); // System.out.println("No of subscribers.."+countOfSubscribers); } catch (HibernateException e) { if (tx != null) { tx.rollback(); e.printStackTrace(); } } finally { session.close(); } return countOfSubscribers; }
@Test public void testNotQueryAnd() throws Exception { UUID applicationId = createApplication("testOrganization", "testNotQueryAnd"); EntityManager em = emf.getEntityManager(applicationId); Map<String, Object> location = new LinkedHashMap<String, Object>(); location.put("Place", "24 Westminster Avenue, Venice, CA 90291, USA"); location.put("Longitude", -118.47425979999998); location.put("Latitude", 33.9887663); Map<String, Object> recipient = new LinkedHashMap<String, Object>(); recipient.put("TimeRequested", 1359077878l); recipient.put("Username", "fb_536692245"); recipient.put("Location", location); Map<String, Object> properties = new LinkedHashMap<String, Object>(); properties.put("Flag", "requested"); properties.put("Recipient", recipient); em.create("loveobject", properties); location = new LinkedHashMap<String, Object>(); location.put( "Place", "Via Pietro Maroncelli, 48, 62012 Santa Maria Apparente Province of Macerata, Italy"); location.put("Longitude", 13.693080199999999); location.put("Latitude", 43.2985019); recipient = new LinkedHashMap<String, Object>(); recipient.put("TimeRequested", 1359077878l); recipient.put("Username", "fb_100000787138041"); recipient.put("Location", location); properties = new LinkedHashMap<String, Object>(); properties.put("Flag", "requested"); properties.put("Recipient", recipient); em.create("loveobject", properties); // String s = "select * where Flag = 'requested'"; // String s = // "select * where Flag = 'requested' and NOT Recipient.Username = '******' order by // created asc"; String s = "select * where Flag = 'requested' and NOT Recipient.Username = '******' order by created asc"; Query query = Query.fromQL(s); Results r = em.searchCollection(em.getApplicationRef(), "loveobjects", query); assertTrue(r.size() == 1); String username = (String) ((Map) r.getEntities().get(0).getProperty("Recipient")).get("Username"); // selection results should be a list of lists List<Object> sr = query.getSelectionResults(r); assertTrue(sr.size() == 1); assertEquals("fb_100000787138041", username); }
private int getHttpsPort() { try { MBeanServer mBeanServer = MBeanServerFactory.findMBeanServer(null).get(0); QueryExp query = Query.eq(Query.attr("Scheme"), Query.value("https")); Set<ObjectName> objectNames = mBeanServer.queryNames(null, query); if (objectNames != null && objectNames.size() > 0) { for (ObjectName objectName : objectNames) { String name = objectName.toString(); if (name.indexOf("port=") > -1) { String[] parts = name.split("port="); String port = parts[1]; try { int portNum = Integer.parseInt(port); return portNum; } catch (NumberFormatException e) { logger.error("Error parsing https port:" + port); return -1; } } } } } catch (Throwable t) { logger.error("Error getting https port:", t); } return -1; }
@Test public void userLastNameSearch() throws Exception { UUID applicationId = createApplication("testOrganization", "testLastName"); assertNotNull(applicationId); EntityManager em = emf.getEntityManager(applicationId); assertNotNull(em); String lastName = "lastName" + UUIDUtils.newTimeUUID(); Map<String, Object> properties = new LinkedHashMap<String, Object>(); properties.put("username", "edanuff"); properties.put("email", "*****@*****.**"); properties.put("lastname", lastName); Entity user = em.create("user", properties); assertNotNull(user); // EntityRef Query query = new Query(); query.addEqualityFilter("lastname", lastName); Results r = em.searchCollection(em.getApplicationRef(), "users", query); assertTrue(r.size() > 0); Entity returned = r.getEntities().get(0); assertEquals(user.getUuid(), returned.getUuid()); }
/** Immediately refreshes all globals using the backing database. */ public synchronized void refreshGlobals() { bootstrapOnce.ensure(); Database database = getDatabase(); LOGGER.info("Loading globals from [{}]", database.getName()); Query<Object> globalsQuery = Query.from(Object.class).where("_id = ?", GLOBALS_ID).using(database).noCache(); State newGlobals = State.getInstance(globalsQuery.first()); if (newGlobals == null) { newGlobals = State.getInstance(globalsQuery.master().first()); } if (newGlobals == null) { newGlobals = new State(); newGlobals.setDatabase(database); newGlobals.setId(GLOBALS_ID); newGlobals.save(); } globals = newGlobals; lastGlobalsUpdate = new Date(); fieldsCache.reset(); metricFieldsCache.reset(); indexesCache.reset(); }
@Test public void testDescendingIntAscendingKeyIndex() throws Exception { final String INDEX_NAME = "descendingIntAscendingKey"; IndexManager indexManager = new IndexManager(TEST_UTIL.getConfiguration()); IndexDefinition indexDef = new IndexDefinition(INDEX_NAME, INDEX_NAME); IntegerIndexFieldDefinition fieldDef = indexDef.addIntegerField("field1"); fieldDef.setOrder(Order.DESCENDING); indexManager.createIndex(indexDef); Index index = indexManager.getIndex(INDEX_NAME, INDEX_NAME); Integer[] values = {1, 1, 2, 2}; for (int i = 0; i < values.length; i++) { IndexEntry entry = new IndexEntry(); entry.addField("field1", values[i]); index.addEntry(entry, Bytes.toBytes("key" + (i + 1))); } // The index on the value is descending, the identifiers themselves are ascending! Query query = new Query(); query.setRangeCondition("field1", 2, 1); QueryResult result = index.performQuery(query); assertResultIds(result, "key3", "key4", "key1", "key2"); }