List of usage examples for java.util Collections binarySearch
public static <T> int binarySearch(List<? extends Comparable<? super T>> list, T key)
From source file:org.jfree.data.ComparableObjectSeries.java
/** * Returns the index of the item with the specified x-value, or a negative * index if the series does not contain an item with that x-value. Be * aware that for an unsorted series, the index is found by iterating * through all items in the series./*from w w w. j a v a 2 s . c o m*/ * * @param x the x-value (<code>null</code> not permitted). * * @return The index. */ public int indexOf(Comparable x) { if (this.autoSort) { return Collections.binarySearch(this.data, new ComparableObjectItem(x, null)); } else { for (int i = 0; i < this.data.size(); i++) { ComparableObjectItem item = (ComparableObjectItem) this.data.get(i); if (item.getComparable().equals(x)) { return i; } } return -1; } }
From source file:org.apereo.portal.events.aggr.AggregationIntervalHelperImpl.java
/** * Return a sorted list of AcademicTermDetail objects where the the first element of the list where the first element * is the first term that starts after the specified start DateTime. *//*from w ww . j a va 2 s. c o m*/ protected List<AcademicTermDetail> getAcademicTermsAfter(DateTime start) { final List<AcademicTermDetail> terms = this.eventAggregationManagementDao.getAcademicTermDetails(); final int index = Collections.binarySearch(terms, new AcademicTermDetailImpl(start.toDateMidnight(), start.plusDays(1).toDateMidnight(), "")); if (index > 0) { return terms.subList(index, terms.size()); } else if (index < 0) { return terms.subList(-(index + 1), terms.size()); } return terms; }
From source file:com.bigdata.dastor.locator.TokenMetadata.java
public Token getPredecessor(Token token) { List tokens = sortedTokens(); int index = Collections.binarySearch(tokens, token); assert index >= 0 : token + " not found in " + StringUtils.join(tokenToEndPointMap.keySet(), ", "); return (Token) (index == 0 ? tokens.get(tokens.size() - 1) : tokens.get(index - 1)); }
From source file:com.bigdata.dastor.locator.TokenMetadata.java
public Token getSuccessor(Token token) { List tokens = sortedTokens(); int index = Collections.binarySearch(tokens, token); assert index >= 0 : token + " not found in " + StringUtils.join(tokenToEndPointMap.keySet(), ", "); return (Token) ((index == (tokens.size() - 1)) ? tokens.get(0) : tokens.get(index + 1)); }
From source file:org.apache.phoenix.util.EquiDepthStreamHistogram.java
/** * Get the appropriate bar for the value, extending existing bar bounds to accommodate if necessary * @param value value to add//from w ww .ja va 2 s . co m * @return the bar for the value */ @VisibleForTesting Bar getBar(byte[] value) { Bar searchKey = new Bar(value, value); int searchIdx = Collections.binarySearch(this.bars, searchKey); if (searchIdx < 0) { // copy value so later changes by caller don't affect histogram results byte[] newBound = Bytes.copy(value); if (this.bars.size() == 0) { Bar firstBar = new Bar(newBound, newBound); bars.add(firstBar); return firstBar; } int expectedIndex = Math.abs(searchIdx + 1); // jdk binary search index if (expectedIndex == bars.size()) { // no bars >= value, need to extend rightBound of last bar Bar lastBar = bars.get(expectedIndex - 1); lastBar.setRightBoundExclusive(newBound); // actually inclusive for last bar return lastBar; } else { // extend leftBound of next greatest bar Bar nextBar = bars.get(expectedIndex); nextBar.setLeftBoundInclusive(newBound); return nextBar; } } else { return bars.get(searchIdx); } }
From source file:org.accada.epcis.repository.query.QueryOperationsModule.java
/** * Create an SQL query string from the given query parameters. * <p>/* ww w .j a v a 2 s. c om*/ * Note: the CXF framework always returns an instance of org.w3c.dom.Element * for the query parameter value given in the <code>queryParams</code> * argument, because the spec defines this value to be of type * <code>anyType</code>. CXF <i>does not</i> resolve the type of the * query parameter value from the query name as Axis does! However, if the * user specifies the XML type in the request, then CXF returns an instance * of the corresponding type. * <p> * Consider the following example of a query parameter: * * <pre> * <param> * <name>GE_eventTime</name> * <value>2007-07-07T07:07:07+02:00</value> * </param> * </pre> * * For the query parameter value, CXF will return an instance of * org.w3c.dom.Element containing the text value * "2007-07-07T07:07:07+02:00". However, if the user provides the following * instead, CXF will return an instance of * javax.xml.datatype.XMLGregorianCalendar. * * <pre> * <param> * <name>GE_eventTime</name> * <value * xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" * xmlns:xs="http://www.w3.org/2001/XMLSchema" * xsi:type="xs:dateTime"> * 2007-07-07T07:07:07+02:00 * </value> * </param> * </pre> * * As a consequence, we always first need to check if the value is an * instance of Element, and if so, we need to parse it manually according to * the semantics of the parameter name. * * @param queryParams * The query parameters. * @param eventType * Has to be one of the four basic event types "ObjectEvent", * "AggregationEvent", "QuantityEvent", "TransactionEvent". * @return The prepared sql statement. * @throws SQLException * Whenever something goes wrong when querying the db. * @throws QueryParameterException * If one of the given QueryParam is invalid. * @throws ImplementationException * If an error in the implementation occurred. */ private List<SimpleEventQueryDTO> constructSimpleEventQueries(final QueryParams queryParams) throws SQLException, QueryParameterExceptionResponse { SimpleEventQueryDTO aggrEventQuery = new SimpleEventQueryDTO(EpcisConstants.AGGREGATION_EVENT); SimpleEventQueryDTO objEventQuery = new SimpleEventQueryDTO(EpcisConstants.OBJECT_EVENT); SimpleEventQueryDTO quantEventQuery = new SimpleEventQueryDTO(EpcisConstants.QUANTITY_EVENT); SimpleEventQueryDTO transEventQuery = new SimpleEventQueryDTO(EpcisConstants.TRANSACTION_EVENT); boolean includeAggrEvents = true; boolean includeObjEvents = true; boolean includeQuantEvents = true; boolean includeTransEvents = true; String orderBy = null; OrderDirection orderDirection = null; int eventCountLimit = -1; int maxEventCount = -1; // a sorted List of query parameter names - keeps track of the processed // names in order to cope with duplicates List<String> sortedParamNames = new ArrayList<String>(); for (QueryParam param : queryParams.getParam()) { String paramName = param.getName(); Object paramValue = param.getValue(); // check for null values if (paramName == null || "".equals(paramName)) { String msg = "Missing name for a query parameter"; throw queryParameterException(msg, null); } if (paramValue == null) { String msg = "Missing value for query parameter '" + paramName + "'"; throw queryParameterException(msg, null); } // check if the current query parameter has already been provided int index = Collections.binarySearch(sortedParamNames, paramName); if (index < 0) { // we have not yet seen this query parameter name - ok sortedParamNames.add(-index - 1, paramName); } else { // we have already handled this query parameter name - not ok String msg = "Query parameter '" + paramName + "' provided more than once"; throw queryParameterException(msg, null); } if (LOG.isDebugEnabled()) { LOG.debug("Handling query parameter: " + paramName); } try { if (paramName.equals("eventType")) { // by default all event types will be included List<String> eventTypes = parseAsArrayOfString(paramValue).getString(); if (!eventTypes.isEmpty()) { // check if valid event types are provided checkEventTypes(eventTypes); // check for excluded event types if (!eventTypes.contains(EpcisConstants.AGGREGATION_EVENT)) { includeAggrEvents = false; } if (!eventTypes.contains(EpcisConstants.OBJECT_EVENT)) { includeObjEvents = false; } if (!eventTypes.contains(EpcisConstants.QUANTITY_EVENT)) { includeQuantEvents = false; } if (!eventTypes.contains(EpcisConstants.TRANSACTION_EVENT)) { includeTransEvents = false; } } } else if (paramName.equals("GE_eventTime") || paramName.equals("LT_eventTime") || paramName.equals("GE_recordTime") || paramName.equals("LT_recordTime")) { Timestamp ts = parseAsTimestamp(paramValue, paramName); Operation op = Operation.valueOf(paramName.substring(0, 2)); String eventField = paramName.substring(3, paramName.length()); aggrEventQuery.addEventQueryParam(eventField, op, ts); objEventQuery.addEventQueryParam(eventField, op, ts); quantEventQuery.addEventQueryParam(eventField, op, ts); transEventQuery.addEventQueryParam(eventField, op, ts); } else if (paramName.equals("EQ_action")) { // QuantityEvents have no "action" field, thus exclude them includeQuantEvents = false; ArrayOfString aos = parseAsArrayOfString(paramValue); if (!aos.getString().isEmpty()) { checkActionValues(aos.getString()); aggrEventQuery.addEventQueryParam("action", Operation.EQ, aos.getString()); objEventQuery.addEventQueryParam("action", Operation.EQ, aos.getString()); transEventQuery.addEventQueryParam("action", Operation.EQ, aos.getString()); } } else if (paramName.equals("EQ_bizStep") || paramName.equals("EQ_disposition") || paramName.equals("EQ_readPoint") || paramName.equals("EQ_bizLocation")) { ArrayOfString aos = parseAsArrayOfString(paramValue); if (!aos.getString().isEmpty()) { String eventField = paramName.substring(3, paramName.length()); aggrEventQuery.addEventQueryParam(eventField, Operation.EQ, aos.getString()); objEventQuery.addEventQueryParam(eventField, Operation.EQ, aos.getString()); quantEventQuery.addEventQueryParam(eventField, Operation.EQ, aos.getString()); transEventQuery.addEventQueryParam(eventField, Operation.EQ, aos.getString()); } } else if (paramName.equals("WD_readPoint") || paramName.equals("WD_bizLocation")) { ArrayOfString aos = parseAsArrayOfString(paramValue); if (!aos.getString().isEmpty()) { // append a "*" to each of the parameter values - this // should implement the semantics of "With Descendant" // TODO: should??? CollectionUtils.transform(aos.getString(), new StringTransformer()); String eventField = paramName.substring(3, paramName.length()); aggrEventQuery.addEventQueryParam(eventField, Operation.WD, aos.getString()); objEventQuery.addEventQueryParam(eventField, Operation.WD, aos.getString()); quantEventQuery.addEventQueryParam(eventField, Operation.WD, aos.getString()); transEventQuery.addEventQueryParam(eventField, Operation.WD, aos.getString()); } } else if (paramName.startsWith("EQ_bizTransaction_")) { // type extracted from parameter name String bizTransType = paramName.substring(18); ArrayOfString aos = parseAsArrayOfString(paramValue); if (!aos.getString().isEmpty()) { aggrEventQuery.addEventQueryParam("bizTransList.type", Operation.EQ, bizTransType); objEventQuery.addEventQueryParam("bizTransList.type", Operation.EQ, bizTransType); quantEventQuery.addEventQueryParam("bizTransList.type", Operation.EQ, bizTransType); transEventQuery.addEventQueryParam("bizTransList.type", Operation.EQ, bizTransType); aggrEventQuery.addEventQueryParam("bizTransList.bizTrans", Operation.EQ, aos.getString()); objEventQuery.addEventQueryParam("bizTransList.bizTrans", Operation.EQ, aos.getString()); quantEventQuery.addEventQueryParam("bizTransList.bizTrans", Operation.EQ, aos.getString()); transEventQuery.addEventQueryParam("bizTransList.bizTrans", Operation.EQ, aos.getString()); } } else if (paramName.equals("MATCH_epc") || paramName.equals("MATCH_anyEPC")) { // QuantityEvents have no field for EPCs, thus exclude them includeQuantEvents = false; ArrayOfString aos = parseAsArrayOfString(paramValue); if (!aos.getString().isEmpty()) { aggrEventQuery.addEventQueryParam("childEPCs", Operation.MATCH, aos.getString()); objEventQuery.addEventQueryParam("epcList", Operation.MATCH, aos.getString()); transEventQuery.addEventQueryParam("epcList", Operation.MATCH, aos.getString()); if (paramName.equals("MATCH_anyEPC")) { // AggregationEvent and TransactionEvent need // special treatment ("parentID" field) aggrEventQuery.setIsAnyEpc(true); transEventQuery.setIsAnyEpc(true); } } } else if (paramName.equals("MATCH_parentID")) { includeQuantEvents = false; includeObjEvents = false; ArrayOfString aos = parseAsArrayOfString(paramValue); if (!aos.getString().isEmpty()) { aggrEventQuery.addEventQueryParam("parentID", Operation.MATCH, aos.getString()); transEventQuery.addEventQueryParam("parentID", Operation.MATCH, aos.getString()); } } else if (paramName.equals("MATCH_epcClass")) { includeAggrEvents = false; includeObjEvents = false; includeTransEvents = false; ArrayOfString aos = parseAsArrayOfString(paramValue); if (!aos.getString().isEmpty()) { quantEventQuery.addEventQueryParam("epcClass", Operation.MATCH, aos.getString()); } } else if (paramName.endsWith("_quantity")) { includeAggrEvents = false; includeObjEvents = false; includeTransEvents = false; Operation op = Operation.valueOf(paramName.substring(0, paramName.indexOf('_'))); quantEventQuery.addEventQueryParam("quantity", op, parseAsInteger(paramValue)); } else if (paramName.startsWith("GT_") || paramName.startsWith("GE_") || paramName.startsWith("EQ_") || paramName.startsWith("LE_") || paramName.startsWith("LT_")) { // must be an event field extension String fieldname = paramName.substring(3); String[] parts = fieldname.split("#"); if (parts.length != 2) { String msg = "Invalid parameter " + paramName; throw queryParameterException(msg, null); } Operation op = Operation.valueOf(paramName.substring(0, 2)); String eventField; Object value; try { value = parseAsInteger(paramValue); eventField = "extension.intValue"; } catch (NumberFormatException e1) { try { value = parseAsFloat(paramValue); eventField = "extension.floatValue"; } catch (NumberFormatException e2) { try { value = parseAsTimestamp(paramValue, paramName); eventField = "extension.dateValue"; } catch (QueryParameterExceptionResponse e) { value = parseAsString(paramValue); eventField = "extension.strValue"; } } } aggrEventQuery.addEventQueryParam(eventField, op, value); objEventQuery.addEventQueryParam(eventField, op, value); quantEventQuery.addEventQueryParam(eventField, op, value); transEventQuery.addEventQueryParam(eventField, op, value); aggrEventQuery.addEventQueryParam("extension.fieldname", Operation.EQ, fieldname); objEventQuery.addEventQueryParam("extension.fieldname", Operation.EQ, fieldname); quantEventQuery.addEventQueryParam("extension.fieldname", Operation.EQ, fieldname); transEventQuery.addEventQueryParam("extension.fieldname", Operation.EQ, fieldname); } else if (paramName.startsWith("EXISTS_")) { String fieldname = paramName.substring(7); if (fieldname.equals("childEPCs")) { includeObjEvents = false; includeQuantEvents = false; includeTransEvents = false; aggrEventQuery.addEventQueryParam("childEPCs", Operation.EXISTS, null); } else if (fieldname.equals("epcList")) { includeAggrEvents = false; includeQuantEvents = false; objEventQuery.addEventQueryParam("epcList", Operation.EXISTS, null); transEventQuery.addEventQueryParam("epcList", Operation.EXISTS, null); } else if (fieldname.equals("action")) { includeQuantEvents = false; aggrEventQuery.addEventQueryParam("action", Operation.EXISTS, null); objEventQuery.addEventQueryParam("action", Operation.EXISTS, null); transEventQuery.addEventQueryParam("action", Operation.EXISTS, null); } else if (fieldname.equals("parentID")) { includeObjEvents = false; includeQuantEvents = false; aggrEventQuery.addEventQueryParam("parentID", Operation.EXISTS, null); transEventQuery.addEventQueryParam("parentID", Operation.EXISTS, null); } else if (fieldname.equals("quantity") || fieldname.equals("epcClass")) { includeAggrEvents = false; includeObjEvents = false; includeTransEvents = false; quantEventQuery.addEventQueryParam(fieldname, Operation.EXISTS, null); } else if (fieldname.equals("eventTime") || fieldname.equals("recordTime") || fieldname.equals("eventTimeZoneOffset") || fieldname.equals("bizStep") || fieldname.equals("disposition") || fieldname.equals("readPoint") || fieldname.equals("bizLocation") || fieldname.equals("bizTransList")) { aggrEventQuery.addEventQueryParam(fieldname, Operation.EXISTS, null); objEventQuery.addEventQueryParam(fieldname, Operation.EXISTS, null); quantEventQuery.addEventQueryParam(fieldname, Operation.EXISTS, null); transEventQuery.addEventQueryParam(fieldname, Operation.EXISTS, null); } else { // lets see if we have an extension fieldname String[] parts = fieldname.split("#"); if (parts.length != 2) { String msg = "Invalid parameter " + paramName; throw queryParameterException(msg, null); } aggrEventQuery.addEventQueryParam("extension.fieldname", Operation.EQ, fieldname); objEventQuery.addEventQueryParam("extension.fieldname", Operation.EQ, fieldname); quantEventQuery.addEventQueryParam("extension.fieldname", Operation.EQ, fieldname); transEventQuery.addEventQueryParam("extension.fieldname", Operation.EQ, fieldname); } } else if (paramName.startsWith("HASATTR_")) { // restrict by attribute name String fieldname = paramName.substring(8); ArrayOfString aos = parseAsArrayOfString(paramValue); String eventField = fieldname + ".attribute"; aggrEventQuery.addEventQueryParam(eventField, Operation.EQ, aos.getString()); objEventQuery.addEventQueryParam(eventField, Operation.EQ, aos.getString()); quantEventQuery.addEventQueryParam(eventField, Operation.EQ, aos.getString()); transEventQuery.addEventQueryParam(eventField, Operation.EQ, aos.getString()); } else if (paramName.startsWith("EQATTR_")) { String fieldname = paramName.substring(7); String attrname = null; String[] parts = fieldname.split("_"); if (parts.length > 2) { String msg = "Query parameter has invalid format: " + paramName + ". Expected: EQATTR_fieldname_attrname"; throw queryParameterException(msg, null); } else if (parts.length == 2) { fieldname = parts[0]; attrname = parts[1]; } // restrict by attribute name String eventField = fieldname + ".attribute"; aggrEventQuery.addEventQueryParam(eventField, Operation.EQ, attrname); objEventQuery.addEventQueryParam(eventField, Operation.EQ, attrname); quantEventQuery.addEventQueryParam(eventField, Operation.EQ, attrname); transEventQuery.addEventQueryParam(eventField, Operation.EQ, attrname); // restrict by attribute value ArrayOfString aos = parseAsArrayOfString(paramValue); eventField = eventField + ".value"; aggrEventQuery.addEventQueryParam(eventField, Operation.EQ, aos.getString()); objEventQuery.addEventQueryParam(eventField, Operation.EQ, aos.getString()); quantEventQuery.addEventQueryParam(eventField, Operation.EQ, aos.getString()); transEventQuery.addEventQueryParam(eventField, Operation.EQ, aos.getString()); } else if (paramName.equals("orderBy")) { orderBy = parseAsString(paramValue); if (!"eventTime".equals(orderBy) && !"recordTime".equals(orderBy) && !"quantity".equals(orderBy)) { String[] parts = orderBy.split("#"); if (parts.length != 2) { String msg = "orderBy must be one of eventTime, recordTime, quantity, or an extension field"; throw queryParameterException(msg, null); } } } else if (paramName.equals("orderDirection")) { orderDirection = OrderDirection.valueOf(parseAsString(paramValue)); } else if (paramName.equals("eventCountLimit")) { eventCountLimit = parseAsInteger(paramValue).intValue(); } else if (paramName.equals("maxEventCount")) { maxEventCount = parseAsInteger(paramValue).intValue(); } else { String msg = "Unknown query parameter: " + paramName; throw queryParameterException(msg, null); } } catch (ClassCastException e) { String msg = "Type of value invalid for query parameter '" + paramName + "': " + paramValue; throw queryParameterException(msg, e); } catch (IllegalArgumentException e) { String msg = "Unparseable value for query parameter '" + paramName + "'. " + e.getMessage(); throw queryParameterException(msg, e); } } // some more user input checks if (maxEventCount > -1 && eventCountLimit > -1) { String msg = "Paramters 'maxEventCount' and 'eventCountLimit' are mutually exclusive"; throw queryParameterException(msg, null); } if (orderBy == null && eventCountLimit > -1) { String msg = "'eventCountLimit' may only be used when 'orderBy' is specified"; throw queryParameterException(msg, null); } if (orderBy == null && orderDirection != null) { String msg = "'orderDirection' may only be used when 'orderBy' is specified"; throw queryParameterException(msg, null); } if (orderBy != null) { aggrEventQuery.setOrderBy(orderBy); objEventQuery.setOrderBy(orderBy); quantEventQuery.setOrderBy(orderBy); transEventQuery.setOrderBy(orderBy); if (orderDirection != null) { aggrEventQuery.setOrderDirection(orderDirection); objEventQuery.setOrderDirection(orderDirection); quantEventQuery.setOrderDirection(orderDirection); transEventQuery.setOrderDirection(orderDirection); } } if (eventCountLimit > -1) { aggrEventQuery.setLimit(eventCountLimit); objEventQuery.setLimit(eventCountLimit); quantEventQuery.setLimit(eventCountLimit); transEventQuery.setLimit(eventCountLimit); } if (maxEventCount > -1) { aggrEventQuery.setMaxEventCount(maxEventCount); objEventQuery.setMaxEventCount(maxEventCount); quantEventQuery.setMaxEventCount(maxEventCount); transEventQuery.setMaxEventCount(maxEventCount); } List<SimpleEventQueryDTO> eventQueries = new ArrayList<SimpleEventQueryDTO>(4); if (includeAggrEvents) { eventQueries.add(aggrEventQuery); } if (includeObjEvents) { eventQueries.add(objEventQuery); } if (includeQuantEvents) { eventQueries.add(quantEventQuery); } if (includeTransEvents) { eventQueries.add(transEventQuery); } return eventQueries; }
From source file:com.bigdata.dastor.locator.TokenMetadata.java
/** * iterator over the Tokens in the given ring, starting with the token for the node owning start * (which does not have to be a Token in the ring) * @param includeMin True if the minimum token should be returned in the ring even if it has no owner. *///from w w w .j a v a 2s . c om public static Iterator<Token> ringIterator(final List ring, Token start, boolean includeMin) { assert ring.size() > 0; // insert the minimum token (at index == -1) if we were asked to include it and it isn't a member of the ring final boolean insertMin = (includeMin && !ring.get(0).equals(StorageService.getPartitioner().getMinimumToken())) ? true : false; int i = Collections.binarySearch(ring, start); if (i < 0) { i = (i + 1) * (-1); if (i >= ring.size()) i = insertMin ? -1 : 0; } final int startIndex = i; return new AbstractIterator<Token>() { int j = startIndex; protected Token computeNext() { if (j < -1) return endOfData(); try { // return minimum for index == -1 if (j == -1) return StorageService.getPartitioner().getMinimumToken(); // return ring token for other indexes return (Token) ring.get(j); } finally { j++; if (j == ring.size()) j = insertMin ? -1 : 0; if (j == startIndex) // end iteration j = -2; } } }; }
From source file:org.fosstrak.epcis.repository.query.QueryOperationsModule.java
/** * Create an SQL query string from the given query parameters. * <p>//from w w w . j a va2 s . com * Note: the CXF framework always returns an instance of org.w3c.dom.Element * for the query parameter value given in the <code>queryParams</code> * argument, because the spec defines this value to be of type * <code>anyType</code>. CXF <i>does not</i> resolve the type of the * query parameter value from the query name as Axis does! However, if the * user specifies the XML type in the request, then CXF returns an instance * of the corresponding type. * <p> * Consider the following example of a query parameter: * * <pre> * <param> * <name>GE_eventTime</name> * <value>2007-07-07T07:07:07+02:00</value> * </param> * </pre> * * For the query parameter value, CXF will return an instance of * org.w3c.dom.Element containing the text value * "2007-07-07T07:07:07+02:00". However, if the user provides the following * instead, CXF will return an instance of * javax.xml.datatype.XMLGregorianCalendar. * * <pre> * <param> * <name>GE_eventTime</name> * <value * xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" * xmlns:xs="http://www.w3.org/2001/XMLSchema" * xsi:type="xs:dateTime"> * 2007-07-07T07:07:07+02:00 * </value> * </param> * </pre> * * As a consequence, we always first need to check if the value is an * instance of Element, and if so, we need to parse it manually according to * the semantics of the parameter name. * * @param queryParams * The query parameters. * @param eventType * Has to be one of the four basic event types "ObjectEvent", * "AggregationEvent", "QuantityEvent", "TransactionEvent". * @return The prepared sql statement. * @throws SQLException * Whenever something goes wrong when querying the db. * @throws QueryParameterException * If one of the given QueryParam is invalid. * @throws ImplementationException * If an error in the implementation occurred. */ private List<SimpleEventQueryDTO> constructSimpleEventQueries(final QueryParams queryParams) throws SQLException, QueryParameterExceptionResponse { SimpleEventQueryDTO aggrEventQuery = new SimpleEventQueryDTO(EpcisConstants.AGGREGATION_EVENT); SimpleEventQueryDTO objEventQuery = new SimpleEventQueryDTO(EpcisConstants.OBJECT_EVENT); SimpleEventQueryDTO quantEventQuery = new SimpleEventQueryDTO(EpcisConstants.QUANTITY_EVENT); SimpleEventQueryDTO transEventQuery = new SimpleEventQueryDTO(EpcisConstants.TRANSACTION_EVENT); boolean includeAggrEvents = true; boolean includeObjEvents = true; boolean includeQuantEvents = true; boolean includeTransEvents = true; String orderBy = null; OrderDirection orderDirection = null; int eventCountLimit = -1; int maxEventCount = -1; // a sorted List of query parameter names - keeps track of the processed // names in order to cope with duplicates List<String> sortedParamNames = new ArrayList<String>(); int nofEventFieldExtensions = 0; for (QueryParam param : queryParams.getParam()) { String paramName = param.getName(); Object paramValue = param.getValue(); // check for null values if (paramName == null || "".equals(paramName)) { String msg = "Missing name for a query parameter"; throw queryParameterException(msg, null); } if (paramValue == null) { String msg = "Missing value for query parameter '" + paramName + "'"; throw queryParameterException(msg, null); } // check if the current query parameter has already been provided int index = Collections.binarySearch(sortedParamNames, paramName); if (index < 0) { // we have not yet seen this query parameter name - ok sortedParamNames.add(-index - 1, paramName); } else { // we have already handled this query parameter name - not ok String msg = "Query parameter '" + paramName + "' provided more than once"; throw queryParameterException(msg, null); } if (LOG.isDebugEnabled()) { LOG.debug("Handling query parameter: " + paramName); } try { if (paramName.equals("eventType")) { // by default all event types will be included List<String> eventTypes = parseAsArrayOfString(paramValue).getString(); if (!eventTypes.isEmpty()) { // check if valid event types are provided checkEventTypes(eventTypes); // check for excluded event types if (!eventTypes.contains(EpcisConstants.AGGREGATION_EVENT)) { includeAggrEvents = false; } if (!eventTypes.contains(EpcisConstants.OBJECT_EVENT)) { includeObjEvents = false; } if (!eventTypes.contains(EpcisConstants.QUANTITY_EVENT)) { includeQuantEvents = false; } if (!eventTypes.contains(EpcisConstants.TRANSACTION_EVENT)) { includeTransEvents = false; } } } else if (paramName.equals("GE_eventTime") || paramName.equals("LT_eventTime") || paramName.equals("GE_recordTime") || paramName.equals("LT_recordTime")) { Calendar cal = parseAsCalendar(paramValue, paramName); Operation op = Operation.valueOf(paramName.substring(0, 2)); String eventField = paramName.substring(3, paramName.length()) + "Ms"; aggrEventQuery.addEventQueryParam(eventField, op, cal.getTimeInMillis()); objEventQuery.addEventQueryParam(eventField, op, cal.getTimeInMillis()); quantEventQuery.addEventQueryParam(eventField, op, cal.getTimeInMillis()); transEventQuery.addEventQueryParam(eventField, op, cal.getTimeInMillis()); } else if (paramName.equals("EQ_action")) { // QuantityEvents have no "action" field, thus exclude them includeQuantEvents = false; ArrayOfString aos = parseAsArrayOfString(paramValue); if (!aos.getString().isEmpty()) { checkActionValues(aos.getString()); aggrEventQuery.addEventQueryParam("action", Operation.EQ, aos.getString()); objEventQuery.addEventQueryParam("action", Operation.EQ, aos.getString()); transEventQuery.addEventQueryParam("action", Operation.EQ, aos.getString()); } } else if (paramName.equals("EQ_bizStep") || paramName.equals("EQ_disposition") || paramName.equals("EQ_readPoint") || paramName.equals("EQ_bizLocation")) { ArrayOfString aos = parseAsArrayOfString(paramValue); if (!aos.getString().isEmpty()) { String eventField = paramName.substring(3, paramName.length()); aggrEventQuery.addEventQueryParam(eventField, Operation.EQ, aos.getString()); objEventQuery.addEventQueryParam(eventField, Operation.EQ, aos.getString()); quantEventQuery.addEventQueryParam(eventField, Operation.EQ, aos.getString()); transEventQuery.addEventQueryParam(eventField, Operation.EQ, aos.getString()); } } else if (paramName.equals("WD_readPoint") || paramName.equals("WD_bizLocation")) { ArrayOfString aos = parseAsArrayOfString(paramValue); if (!aos.getString().isEmpty()) { // append a "*" to each of the parameter values - this // should implement the semantics of "With Descendant" // TODO: should??? CollectionUtils.transform(aos.getString(), new StringTransformer()); String eventField = paramName.substring(3, paramName.length()); aggrEventQuery.addEventQueryParam(eventField, Operation.WD, aos.getString()); objEventQuery.addEventQueryParam(eventField, Operation.WD, aos.getString()); quantEventQuery.addEventQueryParam(eventField, Operation.WD, aos.getString()); transEventQuery.addEventQueryParam(eventField, Operation.WD, aos.getString()); } } else if (paramName.startsWith("EQ_bizTransaction_")) { // type extracted from parameter name String bizTransType = paramName.substring(18); ArrayOfString aos = parseAsArrayOfString(paramValue); if (!aos.getString().isEmpty()) { aggrEventQuery.addEventQueryParam("bizTransList.type", Operation.EQ, bizTransType); objEventQuery.addEventQueryParam("bizTransList.type", Operation.EQ, bizTransType); quantEventQuery.addEventQueryParam("bizTransList.type", Operation.EQ, bizTransType); transEventQuery.addEventQueryParam("bizTransList.type", Operation.EQ, bizTransType); aggrEventQuery.addEventQueryParam("bizTransList.bizTrans", Operation.EQ, aos.getString()); objEventQuery.addEventQueryParam("bizTransList.bizTrans", Operation.EQ, aos.getString()); quantEventQuery.addEventQueryParam("bizTransList.bizTrans", Operation.EQ, aos.getString()); transEventQuery.addEventQueryParam("bizTransList.bizTrans", Operation.EQ, aos.getString()); } } else if (paramName.equals("MATCH_epc") || paramName.equals("MATCH_anyEPC")) { // QuantityEvents have no field for EPCs, thus exclude them includeQuantEvents = false; ArrayOfString aos = parseAsArrayOfString(paramValue); if (!aos.getString().isEmpty()) { aggrEventQuery.addEventQueryParam("childEPCs", Operation.MATCH, aos.getString()); objEventQuery.addEventQueryParam("epcList", Operation.MATCH, aos.getString()); transEventQuery.addEventQueryParam("epcList", Operation.MATCH, aos.getString()); if (paramName.equals("MATCH_anyEPC")) { // AggregationEvent and TransactionEvent need // special treatment ("parentID" field) aggrEventQuery.setIsAnyEpc(true); transEventQuery.setIsAnyEpc(true); } } } else if (paramName.equals("MATCH_parentID")) { includeQuantEvents = false; includeObjEvents = false; ArrayOfString aos = parseAsArrayOfString(paramValue); if (!aos.getString().isEmpty()) { aggrEventQuery.addEventQueryParam("parentID", Operation.MATCH, aos.getString()); transEventQuery.addEventQueryParam("parentID", Operation.MATCH, aos.getString()); } } else if (paramName.equals("MATCH_epcClass")) { includeAggrEvents = false; includeObjEvents = false; includeTransEvents = false; ArrayOfString aos = parseAsArrayOfString(paramValue); if (!aos.getString().isEmpty()) { quantEventQuery.addEventQueryParam("epcClass", Operation.MATCH, aos.getString()); } } else if (paramName.endsWith("_quantity")) { includeAggrEvents = false; includeObjEvents = false; includeTransEvents = false; Operation op = Operation.valueOf(paramName.substring(0, paramName.indexOf('_'))); quantEventQuery.addEventQueryParam("quantity", op, parseAsInteger(paramValue)); } else if (paramName.startsWith("GT_") || paramName.startsWith("GE_") || paramName.startsWith("EQ_") || paramName.startsWith("LE_") || paramName.startsWith("LT_")) { // must be an event field extension String fieldname = paramName.substring(3); String[] parts = fieldname.split("#"); if (parts.length != 2) { String msg = "Invalid parameter " + paramName; throw queryParameterException(msg, null); } nofEventFieldExtensions++; String eventFieldExtBase = "extension" + nofEventFieldExtensions; EventQueryParam queryParam = parseExtensionField(eventFieldExtBase, paramName, paramValue); aggrEventQuery.addEventQueryParam(queryParam); objEventQuery.addEventQueryParam(queryParam); quantEventQuery.addEventQueryParam(queryParam); transEventQuery.addEventQueryParam(queryParam); String eventFieldExt = eventFieldExtBase + ".fieldname"; aggrEventQuery.addEventQueryParam(eventFieldExt, Operation.EQ, fieldname); objEventQuery.addEventQueryParam(eventFieldExt, Operation.EQ, fieldname); quantEventQuery.addEventQueryParam(eventFieldExt, Operation.EQ, fieldname); transEventQuery.addEventQueryParam(eventFieldExt, Operation.EQ, fieldname); } else if (paramName.startsWith("EXISTS_")) { String fieldname = paramName.substring(7); if (fieldname.equals("childEPCs")) { includeObjEvents = false; includeQuantEvents = false; includeTransEvents = false; aggrEventQuery.addEventQueryParam("childEPCs", Operation.EXISTS, null); } else if (fieldname.equals("epcList")) { includeAggrEvents = false; includeQuantEvents = false; objEventQuery.addEventQueryParam("epcList", Operation.EXISTS, null); transEventQuery.addEventQueryParam("epcList", Operation.EXISTS, null); } else if (fieldname.equals("action")) { includeQuantEvents = false; aggrEventQuery.addEventQueryParam("action", Operation.EXISTS, null); objEventQuery.addEventQueryParam("action", Operation.EXISTS, null); transEventQuery.addEventQueryParam("action", Operation.EXISTS, null); } else if (fieldname.equals("parentID")) { includeObjEvents = false; includeQuantEvents = false; aggrEventQuery.addEventQueryParam("parentID", Operation.EXISTS, null); transEventQuery.addEventQueryParam("parentID", Operation.EXISTS, null); } else if (fieldname.equals("quantity") || fieldname.equals("epcClass")) { includeAggrEvents = false; includeObjEvents = false; includeTransEvents = false; quantEventQuery.addEventQueryParam(fieldname, Operation.EXISTS, null); } else if (fieldname.equals("eventTime") || fieldname.equals("recordTime") || fieldname.equals("eventTimeZoneOffset") || fieldname.equals("bizStep") || fieldname.equals("disposition") || fieldname.equals("readPoint") || fieldname.equals("bizLocation") || fieldname.equals("bizTransList")) { aggrEventQuery.addEventQueryParam(fieldname, Operation.EXISTS, null); objEventQuery.addEventQueryParam(fieldname, Operation.EXISTS, null); quantEventQuery.addEventQueryParam(fieldname, Operation.EXISTS, null); transEventQuery.addEventQueryParam(fieldname, Operation.EXISTS, null); } else { // lets see if we have an extension fieldname String[] parts = fieldname.split("#"); if (parts.length != 2) { String msg = "Invalid parameter " + paramName; throw queryParameterException(msg, null); } nofEventFieldExtensions++; String eventFieldExt = "extension" + nofEventFieldExtensions + ".fieldname"; aggrEventQuery.addEventQueryParam(eventFieldExt, Operation.EQ, fieldname); objEventQuery.addEventQueryParam(eventFieldExt, Operation.EQ, fieldname); quantEventQuery.addEventQueryParam(eventFieldExt, Operation.EQ, fieldname); transEventQuery.addEventQueryParam(eventFieldExt, Operation.EQ, fieldname); } } else if (paramName.startsWith("HASATTR_")) { // restrict by attribute name String fieldname = paramName.substring(8); ArrayOfString aos = parseAsArrayOfString(paramValue); String eventField = fieldname + ".attribute"; aggrEventQuery.addEventQueryParam(eventField, Operation.EQ, aos.getString()); objEventQuery.addEventQueryParam(eventField, Operation.EQ, aos.getString()); quantEventQuery.addEventQueryParam(eventField, Operation.EQ, aos.getString()); transEventQuery.addEventQueryParam(eventField, Operation.EQ, aos.getString()); } else if (paramName.startsWith("EQATTR_")) { String fieldname = paramName.substring(7); String attrname = null; String[] parts = fieldname.split("_"); if (parts.length > 2) { String msg = "Query parameter has invalid format: " + paramName + ". Expected: EQATTR_fieldname_attrname"; throw queryParameterException(msg, null); } else if (parts.length == 2) { fieldname = parts[0]; attrname = parts[1]; } // restrict by attribute name String eventField = fieldname + ".attribute"; aggrEventQuery.addEventQueryParam(eventField, Operation.EQ, attrname); objEventQuery.addEventQueryParam(eventField, Operation.EQ, attrname); quantEventQuery.addEventQueryParam(eventField, Operation.EQ, attrname); transEventQuery.addEventQueryParam(eventField, Operation.EQ, attrname); // restrict by attribute value ArrayOfString aos = parseAsArrayOfString(paramValue); eventField = eventField + ".value"; aggrEventQuery.addEventQueryParam(eventField, Operation.EQ, aos.getString()); objEventQuery.addEventQueryParam(eventField, Operation.EQ, aos.getString()); quantEventQuery.addEventQueryParam(eventField, Operation.EQ, aos.getString()); transEventQuery.addEventQueryParam(eventField, Operation.EQ, aos.getString()); } else if (paramName.equals("orderBy")) { orderBy = parseAsString(paramValue); if (!"eventTime".equals(orderBy) && !"recordTime".equals(orderBy) && !"quantity".equals(orderBy)) { String[] parts = orderBy.split("#"); if (parts.length != 2) { String msg = "orderBy must be one of eventTime, recordTime, quantity, or an extension field"; throw queryParameterException(msg, null); } } } else if (paramName.equals("orderDirection")) { orderDirection = OrderDirection.valueOf(parseAsString(paramValue)); } else if (paramName.equals("eventCountLimit")) { eventCountLimit = parseAsInteger(paramValue).intValue(); } else if (paramName.equals("maxEventCount")) { maxEventCount = parseAsInteger(paramValue).intValue(); } else { String msg = "Unknown query parameter: " + paramName; throw queryParameterException(msg, null); } } catch (ClassCastException e) { String msg = "Type of value invalid for query parameter '" + paramName + "': " + paramValue; throw queryParameterException(msg, e); } catch (IllegalArgumentException e) { String msg = "Unparseable value for query parameter '" + paramName + "'. " + e.getMessage(); throw queryParameterException(msg, e); } } // some more user input checks if (maxEventCount > -1 && eventCountLimit > -1) { String msg = "Paramters 'maxEventCount' and 'eventCountLimit' are mutually exclusive"; throw queryParameterException(msg, null); } if (orderBy == null && eventCountLimit > -1) { String msg = "'eventCountLimit' may only be used when 'orderBy' is specified"; throw queryParameterException(msg, null); } if (orderBy == null && orderDirection != null) { String msg = "'orderDirection' may only be used when 'orderBy' is specified"; throw queryParameterException(msg, null); } if (orderBy != null) { aggrEventQuery.setOrderBy(orderBy); objEventQuery.setOrderBy(orderBy); quantEventQuery.setOrderBy(orderBy); transEventQuery.setOrderBy(orderBy); if (orderDirection != null) { aggrEventQuery.setOrderDirection(orderDirection); objEventQuery.setOrderDirection(orderDirection); quantEventQuery.setOrderDirection(orderDirection); transEventQuery.setOrderDirection(orderDirection); } } if (eventCountLimit > -1) { aggrEventQuery.setLimit(eventCountLimit); objEventQuery.setLimit(eventCountLimit); quantEventQuery.setLimit(eventCountLimit); transEventQuery.setLimit(eventCountLimit); } if (maxEventCount > -1) { aggrEventQuery.setMaxEventCount(maxEventCount); objEventQuery.setMaxEventCount(maxEventCount); quantEventQuery.setMaxEventCount(maxEventCount); transEventQuery.setMaxEventCount(maxEventCount); } List<SimpleEventQueryDTO> eventQueries = new ArrayList<SimpleEventQueryDTO>(4); if (includeAggrEvents) { eventQueries.add(aggrEventQuery); } if (includeObjEvents) { eventQueries.add(objEventQuery); } if (includeQuantEvents) { eventQueries.add(quantEventQuery); } if (includeTransEvents) { eventQueries.add(transEventQuery); } return eventQueries; }
From source file:org.orbisgis.corejdbc.internal.ReadRowSetImpl.java
@Override public SortedSet<Integer> getRowNumberFromRowPk(SortedSet<Long> pkSet) throws SQLException { SortedSet<Integer> rowsNum = new IntegerUnion(); if (rowFetchFirstPk == null) { for (long pk : pkSet) { rowsNum.add((int) pk); }/* w ww. j a v a 2s .c om*/ } else { // Use first Pk value of batch in order to fetch only batch that contains a selected pk Iterator<Long> fetchPkIt = pkSet.iterator(); int batchIterId = -1; List<Long> batchPK = new ArrayList<>(fetchSize); while (fetchPkIt.hasNext()) { Long fetchPk = fetchPkIt.next(); if (fetchPk != null) { if (batchIterId == -1 || fetchPk > batchPK.get(batchPK.size() - 1)) { batchPK.clear(); // Iterate through batch until next PK is superior than search pk. // For optimisation sake, a binary search could be faster than serial search Long nextPk = Long.MAX_VALUE; final int batchCount = getBatchCount(); do { batchIterId++; if (batchIterId + 1 >= rowFetchFirstPk.size() || rowFetchFirstPk.get(batchIterId + 1) == null) { fetchBatchPk(batchIterId + 1); } if (rowFetchFirstPk.size() > batchIterId + 1) { nextPk = rowFetchFirstPk.get(batchIterId + 1); } else { break; } } while (nextPk < fetchPk && batchIterId + 1 < batchCount - 1); if (nextPk <= fetchPk) { batchIterId++; } } fetchBatchPk(batchIterId); Long batchFirstPk = rowFetchFirstPk.get(batchIterId); // We are in good batch // Query only PK for this batch if (batchPK.isEmpty()) { try (Connection connection = dataSource.getConnection(); PreparedStatement st = createBatchQuery(connection, batchFirstPk, false, 0, fetchSize, true)) { try (ResultSet rs = st.executeQuery()) { while (rs.next()) { batchPK.add(rs.getLong(1)); } } } } // Target batch is in memory, just find the target pk index in it rowsNum.add(batchIterId * fetchSize + Collections.binarySearch(batchPK, fetchPk) + 1); } } } return rowsNum; }
From source file:org.libreplan.business.calendars.entities.AvailabilityTimeLine.java
private Interval findPossibleIntervalFor(LocalDate date) { Interval point = Interval.point(date); int binarySearch = Collections.binarySearch(invalids, point); if (binarySearch >= 0) { return invalids.get(binarySearch); } else {/*from www. ja v a2 s .co m*/ int insertionPoint = insertionPoint(binarySearch); if (insertionPoint == 0) { return null; } return invalids.get(insertionPoint - 1); } }