public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{ try{ String customerID = request.getParameter("customerID"); BasicAWSCredentials awsCredentials = new BasicAWSCredentials("test", "test"); AmazonSimpleDBClient sdbc = new AmazonSimpleDBClient(awsCredentials); String query = "select * from invoices where customerID = '" + customerID; SelectResult sdbResult = sdbc.select(new SelectRequest(query)); //BAD SelectResult sdbResult2 = sdbc.select(new SelectRequest(query, false)); //BAD SelectRequest sdbRequest = new SelectRequest(); SelectResult sdbResult3 = sdbc.select(sdbRequest.withSelectExpression(query)); //BAD String query2 = "select * from invoices where customerID = 123"; SelectResult sdbResult4 = sdbc.select(new SelectRequest(query2)); //OK }catch(Exception e){ System.out.println(e); } }
/** * @{inheritDoc */ @Override public PagedDatabaseResult getPagedItems(String tableName, Object token, String minRange, String maxRange, String instanceId, String jobId) { List<Item> ret = new ArrayList<Item>(); String whereClause = null; if (minRange != null && maxRange != null) { whereClause = " Timestamp between '" + minRange + "' and '" + maxRange + "' "; } else if (minRange != null) { whereClause = " Timestamp >= '" + minRange + "' "; } else if (maxRange != null) { whereClause = " Timestamp < '" + maxRange + "' "; } else { whereClause = ""; } SelectRequest request = new SelectRequest("SELECT * from `" + tableName + "`" + whereClause).withConsistentRead(true); String nextToken = (String) token; request.withNextToken(nextToken); SelectResult result = db.select(request); for (com.amazonaws.services.simpledb.model.Item item : result.getItems()) { ret.add(resultToItem(item)); } nextToken = result.getNextToken(); return new PagedDatabaseResult(ret, result.getNextToken()); }
public <T> List<T> queryWithSort(Class<T> dataClass, String property, AdminQueryOperator operator, Object parameter, String sortProperty, AdminSortOperator sortOperator) throws WPBIOException { SelectRequest selectRequest = new SelectRequest(); Set<String> properties = new HashSet<String>(); properties.add(property); Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put(property, parameter); Map<String, AdminQueryOperator> operators = new HashMap<String, AdminQueryOperator>(); operators.put(property, operator); selectRequest.withConsistentRead(true).withSelectExpression(build_query_with_condition_and_sort("*", dataClass, properties, operators, parameters, sortProperty, sortOperator)); return internalQuery(dataClass, selectRequest); }
/** * Retrieve itemNames for all quotes that were not posted by the user * * @param myUserId user ID of the viewer so that their posts do not appear in their main feed */ public static List<String> getFeedItemNames(String myUserId) { SelectRequest selectRequest = new SelectRequest("select itemName() from Quotes where userId != '" + myUserId + "' and timestamp is not null order by timestamp desc").withConsistentRead(true); AmazonSimpleDBClient client = getInstance(); if (client != null) { List<Item> items = client.select(selectRequest).getItems(); List<String> itemNames = new ArrayList<String>(); for (int i = 0; i < items.size(); i++) { itemNames.add((items.get(i)).getName()); } return itemNames; } else return new ArrayList<String>(); }
/** * Retrieve quotes posted by posters the user is following * * @param myUserId facebook user ID */ public static List<String> getFollowingFeedItemNames(String myUserId) { SelectRequest selectRequestNames = new SelectRequest("select followedId from Following where followerId = '" + myUserId + "'").withConsistentRead(true); List<Item> names = getInstance().select(selectRequestNames).getItems(); // Work-around for no nested queries in SimpleDB String followedSet = "("; for (int j = 0; j < names.size(); j++) { followedSet += "'" + names.get(j).getAttributes().get(0).getValue() + "',"; } followedSet = followedSet.substring(0, followedSet.length() - 1) + ")"; SelectRequest selectRequest = new SelectRequest("select itemName() from Quotes where userId in " + followedSet + " and timestamp is not null order by timestamp desc").withConsistentRead(true); List<Item> items = getInstance().select(selectRequest).getItems(); List<String> itemNames = new ArrayList<String>(); for (int i = 0; i < items.size(); i++) { itemNames.add((items.get(i)).getName()); } return itemNames; }
@Override public ImmutableSet<CassandraInstance> findAll(String ring) { List<CassandraInstance> instances = Lists.newArrayList(); String nextToken = null; do { SelectRequest request = new SelectRequest(String.format(ALL_QUERY, domain(ring))) .withNextToken(nextToken); SelectResult result = client.select(request); for (Item item : result.getItems()) { instances.add(transform(item)); } nextToken = result.getNextToken(); } while (nextToken != null); return ImmutableSet.copyOf(instances); }
@Test public void findAll() { List<Item> items = createItems(); SelectResult result = createMock(SelectResult.class); Capture<SelectRequest> requestCapture = new Capture<SelectRequest>(); expect(domainFactory.createFromRing(RING_NAME)).andReturn(domain(RING_NAME)); expect(simpleDbClient.select(capture(requestCapture))).andReturn(result); expect(result.getItems()).andReturn(items); expect(result.getNextToken()).andReturn(null); replayAll(); Set<CassandraInstance> expected = transform(items); assertEquals(expected, dao.findAll(RING_NAME)); assertEquals(ALL_QUERY, requestCapture.getValue().getSelectExpression()); assertNull(requestCapture.getValue().getNextToken()); }
@Test public void findById() { List<Item> items = ImmutableList.of(createItem(1)); SelectResult result = createMock(SelectResult.class); Capture<SelectRequest> requestCapture = new Capture<SelectRequest>(); expect(domainFactory.createFromRing(RING_NAME)).andReturn(domain(RING_NAME)); expect(simpleDbClient.select(capture(requestCapture))).andReturn(result); expect(result.getItems()).andStubReturn(items); replayAll(); Set<CassandraInstance> expected = transform(items); assertEquals(expected.iterator().next(), dao.findById(RING_NAME, ID)); assertEquals(String.format(SdbCassandraInstanceDao.INSTANCE_QUERY, DOMAIN, ID), requestCapture.getValue().getSelectExpression()); assertNull(requestCapture.getValue().getNextToken()); }
/** * Region.Simple can select items. * @throws Exception If some problem inside */ @Test public void selectsMultipleItems() throws Exception { final Domain domain = this.domain(); try { final String attr = "alpha"; domain.item("first").put(attr, "val-99"); domain.item("second").put("beta", ""); MatcherAssert.assertThat( domain.select( new SelectRequest().withSelectExpression( String.format( "SELECT * FROM `%s` WHERE `%s` = 'val-99'", domain.name(), attr ) ).withConsistentRead(true) ), Matchers.<Item>hasItem(Matchers.hasKey(attr)) ); } finally { domain.drop(); } }
/** * Region.Simple can select many items. * @throws Exception If some problem inside */ @Test public void selectsManyItems() throws Exception { final Domain domain = this.domain(); try { for (int idx = 0; idx < Tv.TEN; ++idx) { domain.item(String.format("i-%d", idx)).put("hey", ""); } MatcherAssert.assertThat( domain.select( new SelectRequest().withSelectExpression( String.format("SELECT * FROM `%s`", domain.name()) ).withConsistentRead(true) ), Matchers.<Item>iterableWithSize(Tv.TEN) ); } finally { domain.drop(); } }
@Test public void testGetAllItemsCorrectlyCallsSimpleDB() throws Exception { // ARRANGE initialiseOptimisticPersister(); SelectRequest selectRequest = new SelectRequest(); selectRequest.setConsistentRead(true); selectRequest.setSelectExpression("select * from `" + testSimpleDBDomainName + "`"); // Configure select result with an item to be returned: SelectResult selectResult = new SelectResult(); Set<Item> items = new HashSet<>(); Item item = new Item(); String itemDate = "2016-07-23"; item.setName(itemDate); item.setAttributes(allAttributes); items.add(item); selectResult.setItems(items); mockery.checking(new Expectations() { { oneOf(mockSimpleDBClient).select(with(equal(selectRequest))); will(returnValue(selectResult)); } }); List<ImmutablePair<String, List<Attribute>>> expectedItems = new ArrayList<>(); ImmutablePair<String, List<Attribute>> pair = new ImmutablePair<>(itemDate, new ArrayList<>( activeNonVersionAttributes)); expectedItems.add(pair); // ACT List<ImmutablePair<String, List<Attribute>>> actualItems = optimisticPersister.getAllItems(); // ASSERT assertTrue("OptimisticPersister should return the correct items. Actual: " + actualItems + ", Expected: " + expectedItems, actualItems.equals(expectedItems)); }
public void execute() { SelectRequest request = new SelectRequest() .withSelectExpression(determineSelectExpression()) .withConsistentRead(determineConsistentRead()) .withNextToken(determineNextToken()); log.trace("Sending request [{}] for exchange [{}]...", request, exchange); SelectResult result = this.sdbClient.select(request); log.trace("Received result [{}]", result); Message msg = getMessageForResponse(exchange); msg.setHeader(SdbConstants.ITEMS, result.getItems()); msg.setHeader(SdbConstants.NEXT_TOKEN, result.getNextToken()); }
@Override public SelectResult select(SelectRequest selectRequest) throws AmazonServiceException, AmazonClientException { this.selectRequest = selectRequest; SelectResult result = new SelectResult(); result.setNextToken("TOKEN2"); result.getItems().add(new Item("ITEM1", null)); result.getItems().add(new Item("ITEM2", null)); return result; }
private Iterator<Item> searchAmazonSimpleDB(boolean users,Filter filter,ArrayList<Attribute> attributes) { StringBuffer sqlWhere = new StringBuffer(); ArrayList<Object> vals = new ArrayList<Object>(); this.stringFilter(filter.getRoot(),sqlWhere, vals); StringBuffer SQL = new StringBuffer(); SQL.append("SELECT "); if (attributes.size() == 0) { SQL.append("* "); } else if (attributes.size() == 1 && attributes.get(0).equals("*")) { SQL.append("* "); } else if (attributes.size() == 1 && attributes.get(0).getAttribute().getName().equals("1.1")) { SQL.append("uid "); } else { for(Attribute attr : attributes) { SQL.append(attr.getAttribute().getName()).append(','); } SQL.setLength(SQL.length() - 1); } SQL.append(" FROM ").append('`'); if (users) { SQL.append(this.userDomain); } else { SQL.append(this.groupDomain); } SQL.append("` WHERE ").append(sqlWhere); if (logger.isDebugEnabled()) { logger.debug("SQL : " + SQL.toString()); } SelectResult res = this.sdb.select(new SelectRequest(SQL.toString())); return res.getItems().iterator(); }
/** * @{inheritDoc */ @Override public boolean hasJobData(String tableName, String jobId) { boolean ret = false; if (hasTable(tableName)) { SelectRequest request = new SelectRequest("SELECT * from `" + tableName + "`"); SelectResult result = db.select(request); ret = !result.getItems().isEmpty(); } return ret; }
public <T> void delete(Class<T> dataClass, String property, AdminQueryOperator operator, Object parameter) throws WPBIOException { SelectRequest selectRequest = new SelectRequest(); Set<String> properties = new HashSet<String>(); properties.add(property); Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put(property, parameter); Map<String, AdminQueryOperator> operators = new HashMap<String, AdminQueryOperator>(); operators.put(property, operator); selectRequest.withConsistentRead(true).withSelectExpression(build_query_with_condition("itemName()", dataClass, properties, operators, parameters)); internalDelete(selectRequest); }
private<T> List<T> internalQuery(Class<T> dataClass, SelectRequest selectRequest) throws WPBIOException { List<T> result = new ArrayList<T>(); try { SelectResult selectResult = null; do { if (selectResult != null) { selectRequest.setNextToken(selectResult.getNextToken()); } selectResult = sdbClient.select(selectRequest); List<Item> items = selectResult.getItems(); for(Item item: items) { T t = copyAttributesToInstance(dataClass, item.getAttributes()); result.add(t); } } while (selectResult.getNextToken() != null); } catch (Exception e) { throw new WPBIOException("cannot get all records " + dataClass.getSimpleName(), e); } return result; }
public <T> List<T> query(Class<T> dataClass, String property, AdminQueryOperator operator, Object parameter) throws WPBIOException { SelectRequest selectRequest = new SelectRequest(); Set<String> properties = new HashSet<String>(); properties.add(property); Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put(property, parameter); Map<String, AdminQueryOperator> operators = new HashMap<String, AdminQueryOperator>(); operators.put(property, operator); selectRequest.withConsistentRead(true).withSelectExpression(build_query_with_condition("*", dataClass, properties, operators, parameters)); return internalQuery(dataClass, selectRequest); }
public <T> List<T> queryEx(Class<T> dataClass, Set<String> propertyNames, Map<String, AdminQueryOperator> operators, Map<String, Object> values) throws WPBIOException { SelectRequest selectRequest = new SelectRequest(); selectRequest.withConsistentRead(true).withSelectExpression(build_query_with_condition("*", dataClass, propertyNames, operators, values)); return internalQuery(dataClass, selectRequest); }
@Test @Ignore public void getAttributeNamesEmptyStringTest() throws Exception { DomainMetadataResult metadataResult = mock(DomainMetadataResult.class); SelectResult result = mock(SelectResult.class); // List itemsList = mock(ArrayList.class); // Iterator iterator = mock(Iterator.class); // Attribute // when(itemsList.iterator()).thenReturn(iterator); when(metadataResult.getAttributeNameCount()).thenReturn(3); when(client.select(any(SelectRequest.class))).thenReturn(result); // when(client.domainMetadata(any(DomainMetadataRequest.class))).thenReturn(metadataResult); System.out.println(simpleDbApi.getAttributeNames(null)); }
public static String[] getItemNamesForDomain(String domainName) { SelectRequest selectRequest = new SelectRequest("select itemName() from `" + domainName + "`").withConsistentRead(true); List<Item> items = getInstance().select(selectRequest).getItems(); String[] itemNames = new String[items.size()]; for (int i = 0; i < items.size(); i++) { itemNames[i] = items.get(i).getName(); } return itemNames; }
/** * Check whether the user has followed a specific user * * @param posterId id of user who posted the quote and is now being followed * @param userId id of the user who pressed the follow icon */ public static boolean isFollowedByUser(String posterId, String userId) { SelectRequest selectRequest = new SelectRequest("select itemName() from Following where followedId = '" + posterId + "' and followerId = '" + userId + "'").withConsistentRead(true); List<Item> items = getInstance().select(selectRequest).getItems(); return items.size() > 0; }
/** * @param myUserId User ID to return all quotes posted by them * @return itemNames of all the Quotes created by the user */ public static List<String> getMyQuotesItemNames(String myUserId) { SelectRequest selectRequest = new SelectRequest("select itemName() from Quotes where userId = '" + myUserId + "' and timestamp is not null order by timestamp desc").withConsistentRead(true); List<Item> items = getInstance().select(selectRequest).getItems(); List<String> itemNames = new ArrayList<String>(); for (int i = 0; i < items.size(); i++) { itemNames.add(items.get(i).getName()); } return itemNames; }
/** * Retrieve the number of favorites a specific post has * * @param postId the post identifier to look up its number of favorites */ public static int favCount(String postId) { SelectRequest selectRequest = new SelectRequest("select favorites from Quotes where itemName() = '" + postId + "'") .withConsistentRead(true); List<Item> items = getInstance().select(selectRequest).getItems(); return Integer.parseInt(items.get(0).getAttributes().get(0).getValue()); }
/** * Check whether the user has favorited a specific post * * @param postId post identifier * @param userId user ID seeing the feed */ public static boolean isFavoritedByUser(String postId, String userId) { SelectRequest selectRequest = new SelectRequest("select itemName() from Favorites where postID = '" + postId + "' and likedBy = '" + userId + "'").withConsistentRead(true); List<Item> items = getInstance().select(selectRequest).getItems(); return items.size() > 0; }
/** * Retrieve itemNames for all quotes that were not posted by the user in order of favorites */ public static List<String> getPopularFeedItemNames() { SelectRequest selectRequest = new SelectRequest("select itemName() from Quotes where favorites is not null " + "order by favorites desc").withConsistentRead(true); List<Item> items = getInstance().select(selectRequest).getItems(); List<String> itemNames = new ArrayList<String>(); for (int i = 0; i < items.size(); i++) { itemNames.add(((Item) items.get(i)).getName()); } return itemNames; }
/** * Get quotes by a specific user * * @param userId ID of the user whose quotes are being looked up */ public static List<String> getUserItemNames(String userId) { SelectRequest selectRequest = new SelectRequest("select itemName() from Quotes where userId = '" + userId + "' and timestamp is not null order by timestamp desc").withConsistentRead(true); List<Item> items = getInstance().select(selectRequest).getItems(); List<String> itemNames = new ArrayList<String>(); for (int i = 0; i < items.size(); i++) { itemNames.add(items.get(i).getName()); } return itemNames; }
/** * Get quotes favorited by a specific user * * @param userId ID of the user whose favorites are being looked up */ public static List<String> getFavoriteFeedItemNames(String userId) { SelectRequest selectRequest = new SelectRequest("select postID from Favorites where likedBy = '" + userId + "' and postID is not null order by postID asc").withConsistentRead(true); List<Item> items = getInstance().select(selectRequest).getItems(); List<String> itemNames = new ArrayList<String>(); for (int i = 0; i < items.size(); i++) { itemNames.add(items.get(i).getAttributes().get(0).getValue()); } return itemNames; }
/** * Get quotes by a specific category * * @param category name of the quote category */ public static List<String> getFeedItemNamesByCategory(String category) { SelectRequest selectRequest = new SelectRequest("select itemName() from Quotes where category = '" + category + "' and timestamp is not null order by timestamp desc").withConsistentRead(true); List<Item> items = getInstance().select(selectRequest).getItems(); List<String> itemNames = new ArrayList<String>(); for (int i = 0; i < items.size(); i++) { itemNames.add(items.get(i).getName()); } return itemNames; }
/** * Get quotes in which query term appears in the quote, author, or poster name * * @param query the term to search by */ public static List<String> getItemNamesBySearchQuery(String query) { SelectRequest selectRequest = new SelectRequest("select itemName() from Quotes where " + "(author like '%" + query + "%' or fbName like '%" + query + "%' or quoteText like '%" + query + "%') and " + "timestamp is not null order by timestamp desc limit 25").withConsistentRead(true); List<Item> items = getInstance().select(selectRequest).getItems(); List<String> itemNames = new ArrayList<String>(); for (int i = 0; i < items.size(); i++) { itemNames.add(items.get(i).getName()); } return itemNames; }
@Override public @Nullable CassandraInstance findById(String ring, int id) { SelectRequest request = new SelectRequest(String.format(INSTANCE_QUERY, domain(ring), id)); SelectResult result = client.select(request); if (result.getItems().size() == 0) { return null; } return transform(result.getItems().get(0)); }
@Test public void findAll_paginated() { List<Item> items1 = createItems(0); List<Item> items2 = createItems(10); SelectResult result = createMock(SelectResult.class); Capture<SelectRequest> requestCapture = new Capture<SelectRequest>(CaptureType.ALL); expect(domainFactory.createFromRing(RING_NAME)).andReturn(domain(RING_NAME)).times(2); expect(simpleDbClient.select(capture(requestCapture))).andReturn(result); expect(result.getItems()).andReturn(items1); expect(result.getNextToken()).andReturn(NEXT_TOKEN); expect(simpleDbClient.select(capture(requestCapture))).andReturn(result); expect(result.getItems()).andReturn(items2); expect(result.getNextToken()).andReturn(null); replayAll(); Set<CassandraInstance> expected = Sets.newHashSet( Iterables.concat(transform(items1), transform(items2))); assertEquals(expected, dao.findAll(RING_NAME)); List<SelectRequest> requests = requestCapture.getValues(); assertEquals(2, requests.size()); assertEquals(ALL_QUERY, requests.get(0).getSelectExpression()); assertNull(requests.get(0).getNextToken()); assertEquals(ALL_QUERY, requests.get(1).getSelectExpression()); assertEquals(NEXT_TOKEN, requests.get(1).getNextToken()); }
@Test public void findById_notFound() { List<Item> items = ImmutableList.of(); SelectResult result = createMock(SelectResult.class); Capture<SelectRequest> requestCapture = new Capture<SelectRequest>(); expect(domainFactory.createFromRing(RING_NAME)).andReturn(domain(RING_NAME)); expect(simpleDbClient.select(capture(requestCapture))).andReturn(result); expect(result.getItems()).andStubReturn(items); replayAll(); assertNull(dao.findById(RING_NAME, ID)); }
/** * {@inheritDoc} */ @Override public Iterable<Item> select(final SelectRequest request) { return new Iterable<Item>() { @Override public Iterator<Item> iterator() { return new AwsIterator( AwsDomain.this.credentials, AwsDomain.this.table, request ); } }; }
/** * Public ctor. * @param creds Credentials * @param name Domain name * @param req Request */ protected AwsIterator(final Credentials creds, final String name, final SelectRequest req) { this.credentials = creds; this.table = name; this.request = req; }
public SelectResult select(SelectRequest selectRequest) { SelectResult response = null; return response; }
@Override public List<ImmutablePair<String, List<Attribute>>> getAllItems() { if (!initialised) { throw new IllegalStateException("The optimistic persister has not been initialised"); } // Query database to get items List<ImmutablePair<String, List<Attribute>>> items = new ArrayList<>(); AmazonSimpleDB client = getSimpleDBClient(); SelectRequest selectRequest = new SelectRequest(); // N.B. Think if results are paged, second and subsequent pages will always // be eventually-consistent only. This is currently used only to back up the // database - so being eventually-consistent is good enough - after all - // even if we were fully consistent, someone could still add a new booking // right after our call anyway. selectRequest.setConsistentRead(true); // Query all items in the domain selectRequest.setSelectExpression("select * from `" + simpleDbDomainName + "`"); String nextToken = null; do { SelectResult selectResult = client.select(selectRequest); selectResult.getItems().forEach( item -> { List<Attribute> attributes = new ArrayList<>(); item.getAttributes() .stream() // Do not return the version attribute or inactive attributes .filter( attribute -> (!attribute.getName().equals(versionAttributeName) && !attribute .getValue().startsWith("Inactive"))).forEach(attribute -> { attributes.add(attribute); }); items.add(new ImmutablePair<>(item.getName(), attributes)); }); nextToken = selectResult.getNextToken(); selectRequest.setNextToken(nextToken); } while (nextToken != null); return items; }
public <T> List<T> getAllRecords(Class<T> dataClass) throws WPBIOException { SelectRequest selectRequest = new SelectRequest(); selectRequest.withConsistentRead(true).withSelectExpression(build_queryAll_statement("*", dataClass)); return internalQuery(dataClass, selectRequest); }
public <T> List<T> getAllRecords(Class<T> dataClass, String property, AdminSortOperator operator) throws WPBIOException { SelectRequest selectRequest = new SelectRequest(); selectRequest.withConsistentRead(true).withSelectExpression(build_queryAll_statement(dataClass, property, operator)); return internalQuery(dataClass, selectRequest); }
public <T> void deleteAllRecords(Class<T> dataClass) throws WPBIOException { SelectRequest selectRequest = new SelectRequest(); selectRequest.withConsistentRead(true).withSelectExpression(build_queryAll_statement("itemName()", dataClass)); internalDelete(selectRequest); }