List of usage examples for java.util Map toString
public String toString()
From source file:org.apache.accumulo.examples.wikisearch.parser.RangeCalculator.java
/** * /*from w w w. ja v a2 s . co m*/ * @param c * @param auths * @param indexedTerms * @param terms * @param query * @param logic * @param typeFilter * @throws ParseException */ public void execute(Connector c, Authorizations auths, Multimap<String, Normalizer> indexedTerms, Multimap<String, QueryTerm> terms, String query, AbstractQueryLogic logic, Set<String> typeFilter) throws ParseException { super.execute(query); this.c = c; this.auths = auths; this.indexedTerms = indexedTerms; this.termsCopy.putAll(terms); this.indexTableName = logic.getIndexTableName(); this.reverseIndexTableName = logic.getReverseIndexTableName(); this.queryThreads = logic.getQueryThreads(); Map<MapKey, Set<Range>> indexRanges = new HashMap<MapKey, Set<Range>>(); Map<MapKey, Set<Range>> trailingWildcardRanges = new HashMap<MapKey, Set<Range>>(); Map<MapKey, Set<Range>> leadingWildcardRanges = new HashMap<MapKey, Set<Range>>(); Map<Text, RangeBounds> rangeMap = new HashMap<Text, RangeBounds>(); // Here we iterate over all of the terms in the query to determine if they are an equivalence, // wildcard, or range type operator for (Entry<String, QueryTerm> entry : terms.entries()) { if (entry.getValue().getOperator().equals(JexlOperatorConstants.getOperator(ASTEQNode.class)) || entry.getValue().getOperator().equals(JexlOperatorConstants.getOperator(ASTERNode.class)) || entry.getValue().getOperator().equals(JexlOperatorConstants.getOperator(ASTLTNode.class)) || entry.getValue().getOperator().equals(JexlOperatorConstants.getOperator(ASTLENode.class)) || entry.getValue().getOperator().equals(JexlOperatorConstants.getOperator(ASTGTNode.class)) || entry.getValue().getOperator().equals(JexlOperatorConstants.getOperator(ASTGENode.class))) { // If this term is not in the set of indexed terms, then bail if (!indexedTerms.containsKey(entry.getKey())) { termCardinalities.put(entry.getKey().toUpperCase(), 0L); continue; } // In the case of function calls, the query term could be null. Dont query the index for it. if (null == entry.getValue()) { termCardinalities.put(entry.getKey().toUpperCase(), 0L); continue; } // In the case where we are looking for 'null', then skip. if (null == entry.getValue().getValue() || ((String) entry.getValue().getValue()).equals("null")) { termCardinalities.put(entry.getKey().toUpperCase(), 0L); continue; } // Remove the begin and end ' marks String value = null; if (((String) entry.getValue().getValue()).startsWith("'") && ((String) entry.getValue().getValue()).endsWith("'")) value = ((String) entry.getValue().getValue()).substring(1, ((String) entry.getValue().getValue()).length() - 1); else value = (String) entry.getValue().getValue(); // The entries in the index are normalized for (Normalizer normalizer : indexedTerms.get(entry.getKey())) { String normalizedFieldValue = normalizer.normalizeFieldValue(null, value); Text fieldValue = new Text(normalizedFieldValue); Text fieldName = new Text(entry.getKey().toUpperCase()); // EQUALS if (entry.getValue().getOperator().equals(JexlOperatorConstants.getOperator(ASTEQNode.class))) { Key startRange = new Key(fieldValue, fieldName); Range r = new Range(startRange, true, startRange.followingKey(PartialKey.ROW), true); MapKey key = new MapKey(fieldName.toString(), fieldValue.toString()); key.setOriginalQueryValue(value); this.originalQueryValues.put(value, key); if (!indexRanges.containsKey(key)) indexRanges.put(key, new HashSet<Range>()); indexRanges.get(key).add(r); // WILDCARD } else if (entry.getValue().getOperator() .equals(JexlOperatorConstants.getOperator(ASTERNode.class))) { // This is a wildcard query using regex. We can only support leading and trailing wildcards at this time. Leading // wildcards will need be reversed and sent to the global reverse index. Trailing wildcard queries will be sent to the // global index. In all cases, the range for the wilcard will be the range of possible UNICODE codepoints, hex 0 to 10FFFF. int loc = normalizedFieldValue.indexOf(WILDCARD); if (-1 == loc) loc = normalizedFieldValue.indexOf(SINGLE_WILDCARD); if (-1 == loc) { // Then no wildcard in the query? Treat like the equals case above. Key startRange = new Key(fieldValue, fieldName); Range r = new Range(startRange, true, startRange.followingKey(PartialKey.ROW), true); MapKey key = new MapKey(fieldName.toString(), fieldValue.toString()); key.setOriginalQueryValue(value); this.originalQueryValues.put(value, key); if (!indexRanges.containsKey(key)) indexRanges.put(key, new HashSet<Range>()); indexRanges.get(key).add(r); } else { if (loc == 0) { // Then we have a leading wildcard, reverse the term and use the global reverse index. StringBuilder buf = new StringBuilder(normalizedFieldValue.substring(2)); normalizedFieldValue = buf.reverse().toString(); Key startRange = new Key(new Text(normalizedFieldValue + "\u0000"), fieldName); Key endRange = new Key(new Text(normalizedFieldValue + "\u10FFFF"), fieldName); Range r = new Range(startRange, true, endRange, true); MapKey key = new MapKey(fieldName.toString(), normalizedFieldValue); key.setOriginalQueryValue(value); this.originalQueryValues.put(value, key); if (!leadingWildcardRanges.containsKey(key)) leadingWildcardRanges.put(key, new HashSet<Range>()); leadingWildcardRanges.get(key).add(r); } else if (loc == (normalizedFieldValue.length() - 2)) { normalizedFieldValue = normalizedFieldValue.substring(0, loc); // Then we have a trailing wildcard character. Key startRange = new Key(new Text(normalizedFieldValue + "\u0000"), fieldName); Key endRange = new Key(new Text(normalizedFieldValue + "\u10FFFF"), fieldName); Range r = new Range(startRange, true, endRange, true); MapKey key = new MapKey(fieldName.toString(), normalizedFieldValue); key.setOriginalQueryValue(value); this.originalQueryValues.put(value, key); if (!trailingWildcardRanges.containsKey(key)) trailingWildcardRanges.put(key, new HashSet<Range>()); trailingWildcardRanges.get(key).add(r); } else { // throw new RuntimeException("Unsupported wildcard location. Only trailing or leading wildcards are supported: " + normalizedFieldValue); // Don't throw an exception, there must be a wildcard in the query, we'll treat it as a filter on the results since it is not // leading or trailing. } } // RANGES } else if (entry.getValue().getOperator() .equals(JexlOperatorConstants.getOperator(ASTGTNode.class)) || entry.getValue().getOperator() .equals(JexlOperatorConstants.getOperator(ASTGENode.class))) { // Then we have a lower bound to a range query if (!rangeMap.containsKey(fieldName)) rangeMap.put(fieldName, new RangeBounds()); rangeMap.get(fieldName).setLower(fieldValue); rangeMap.get(fieldName).setOriginalLower(value); } else if (entry.getValue().getOperator() .equals(JexlOperatorConstants.getOperator(ASTLTNode.class)) || entry.getValue().getOperator() .equals(JexlOperatorConstants.getOperator(ASTLENode.class))) { // Then we have an upper bound to a range query if (!rangeMap.containsKey(fieldName)) rangeMap.put(fieldName, new RangeBounds()); rangeMap.get(fieldName).setUpper(fieldValue); rangeMap.get(fieldName).setOriginalUpper(value); } } } } // INDEX RANGE QUERY // Now that we have figured out the range bounds, create the index ranges. for (Entry<Text, RangeBounds> entry : rangeMap.entrySet()) { if (entry.getValue().getLower() != null && entry.getValue().getUpper() != null) { // Figure out the key order Key lk = new Key(entry.getValue().getLower()); Key up = new Key(entry.getValue().getUpper()); Text lower = lk.getRow(); Text upper = up.getRow(); // Swith the order if needed. if (lk.compareTo(up) > 0) { lower = up.getRow(); upper = lk.getRow(); } Key startRange = new Key(lower, entry.getKey()); Key endRange = new Key(upper, entry.getKey()); Range r = new Range(startRange, true, endRange, true); // For the range queries we need to query the global index and then handle the results a little differently. Map<MapKey, Set<Range>> ranges = new HashMap<MapKey, Set<Range>>(); MapKey key = new MapKey(entry.getKey().toString(), entry.getValue().getLower().toString()); key.setOriginalQueryValue(entry.getValue().getOriginalLower().toString()); this.originalQueryValues.put(entry.getValue().getOriginalLower().toString(), key); ranges.put(key, new HashSet<Range>()); ranges.get(key).add(r); // Now query the global index and override the field value used in the results map try { Map<MapKey, TermRange> lowerResults = queryGlobalIndex(ranges, entry.getKey().toString(), this.indexTableName, false, key, typeFilter); // Add the results to the global index results for both the upper and lower field values. Map<MapKey, TermRange> upperResults = new HashMap<MapKey, TermRange>(); for (Entry<MapKey, TermRange> e : lowerResults.entrySet()) { MapKey key2 = new MapKey(e.getKey().getFieldName(), entry.getValue().getUpper().toString()); key2.setOriginalQueryValue(entry.getValue().getOriginalUpper().toString()); upperResults.put(key2, e.getValue()); this.originalQueryValues.put(entry.getValue().getOriginalUpper(), key2); } this.globalIndexResults.putAll(lowerResults); this.globalIndexResults.putAll(upperResults); } catch (TableNotFoundException e) { log.error("index table not found", e); throw new RuntimeException(" index table not found", e); } } else { log.warn("Unbounded range detected, not querying index for it. Field " + entry.getKey().toString() + " in query: " + query); } } // Now that we have calculated all of the ranges, query the global index. try { // Query for the trailing wildcards if we have any for (Entry<MapKey, Set<Range>> trailing : trailingWildcardRanges.entrySet()) { Map<MapKey, Set<Range>> m = new HashMap<MapKey, Set<Range>>(); m.put(trailing.getKey(), trailing.getValue()); if (log.isDebugEnabled()) log.debug("Ranges for Wildcard Global Index query: " + m.toString()); this.globalIndexResults.putAll(queryGlobalIndex(m, trailing.getKey().getFieldName(), this.indexTableName, false, trailing.getKey(), typeFilter)); } // Query for the leading wildcards if we have any for (Entry<MapKey, Set<Range>> leading : leadingWildcardRanges.entrySet()) { Map<MapKey, Set<Range>> m = new HashMap<MapKey, Set<Range>>(); m.put(leading.getKey(), leading.getValue()); if (log.isDebugEnabled()) log.debug("Ranges for Wildcard Global Reverse Index query: " + m.toString()); this.globalIndexResults.putAll(queryGlobalIndex(m, leading.getKey().getFieldName(), this.reverseIndexTableName, true, leading.getKey(), typeFilter)); } // Query for the equals case for (Entry<MapKey, Set<Range>> equals : indexRanges.entrySet()) { Map<MapKey, Set<Range>> m = new HashMap<MapKey, Set<Range>>(); m.put(equals.getKey(), equals.getValue()); if (log.isDebugEnabled()) log.debug("Ranges for Global Index query: " + m.toString()); this.globalIndexResults.putAll(queryGlobalIndex(m, equals.getKey().getFieldName(), this.indexTableName, false, equals.getKey(), typeFilter)); } } catch (TableNotFoundException e) { log.error("index table not found", e); throw new RuntimeException(" index table not found", e); } if (log.isDebugEnabled()) log.debug("Ranges from Global Index query: " + globalIndexResults.toString()); // Now traverse the AST EvaluationContext ctx = new EvaluationContext(); this.getAST().childrenAccept(this, ctx); if (ctx.lastRange.getRanges().size() == 0) { log.debug("No resulting range set"); } else { if (log.isDebugEnabled()) log.debug("Setting range results to: " + ctx.lastRange.getRanges().toString()); this.result = ctx.lastRange.getRanges(); } }
From source file:org.jumpmind.symmetric.io.data.writer.TransformWriter.java
protected Object transformColumn(DataContext context, TransformedData data, TransformColumn transformColumn, Map<String, String> sourceValues, Map<String, String> oldSourceValues) throws IgnoreRowException, IgnoreColumnException { Object returnValue = null;/*ww w .ja v a 2s.c om*/ String value = transformColumn.getSourceColumnName() != null ? sourceValues.get(transformColumn.getSourceColumnName()) : null; returnValue = value; IColumnTransform<?> transform = columnTransforms != null ? columnTransforms.get(transformColumn.getTransformType()) : null; if (transform != null) { try { String oldValue = null; if (oldSourceValues != null) { oldValue = oldSourceValues.get(transformColumn.getSourceColumnName()); } returnValue = transform.transform(platform, context, transformColumn, data, sourceValues, value, oldValue); } catch (RuntimeException ex) { log.warn("Column transform failed {}.{} ({}) for source values of {}", new Object[] { transformColumn.getTransformId(), transformColumn.getTargetColumnName(), transformColumn.getIncludeOn().name(), sourceValues.toString() }); throw ex; } } else { throw new TransformColumnException(String.format("Could not locate a column transform of type '%s'", transformColumn.getTransformType())); } return returnValue; }
From source file:org.apache.sqoop.connector.idf.TestCSVIntermediateDataFormat.java
@Test public void testMapWithComplexIntegerListValueWithObjectArrayInObjectArrayOut() { Schema schema = new Schema("test"); schema.addColumn(new org.apache.sqoop.schema.type.Map("1", new Text("key"), new Array("value", new FixedPoint("number", 2L, true)))); schema.addColumn(new org.apache.sqoop.schema.type.Text("2")); dataFormat = new CSVIntermediateDataFormat(schema); Map<Object, Object> givenMap = new HashMap<Object, Object>(); List<Integer> intList = new ArrayList<Integer>(); intList.add(11);/*from www . ja v a 2 s . com*/ intList.add(12); givenMap.put("testKey", intList); // create an array inside the object array Object[] data = new Object[2]; data[0] = givenMap; data[1] = "text"; dataFormat.setObjectData(data); @SuppressWarnings("unchecked") Map<Object, Object> expectedMap = (Map<Object, Object>) dataFormat.getObjectData()[0]; assertEquals(givenMap.toString(), expectedMap.toString()); assertEquals("text", dataFormat.getObjectData()[1]); }
From source file:org.apache.sqoop.connector.idf.TestCSVIntermediateDataFormat.java
@Test public void testMapWithComplexStringListValueWithObjectArrayInObjectArrayOut() { Schema schema = new Schema("test"); schema.addColumn(//from ww w . jav a 2s .com new org.apache.sqoop.schema.type.Map("1", new Text("key"), new Array("value", new Text("text")))); schema.addColumn(new org.apache.sqoop.schema.type.Text("2")); dataFormat = new CSVIntermediateDataFormat(schema); Map<Object, Object> givenMap = new HashMap<Object, Object>(); List<String> stringList = new ArrayList<String>(); stringList.add("A"); stringList.add("A"); givenMap.put("testKey", stringList); // create an array inside the object array Object[] data = new Object[2]; data[0] = givenMap; data[1] = "text"; dataFormat.setObjectData(data); @SuppressWarnings("unchecked") Map<Object, Object> expectedMap = (Map<Object, Object>) dataFormat.getObjectData()[0]; assertEquals(givenMap.toString(), expectedMap.toString()); assertEquals("text", dataFormat.getObjectData()[1]); }
From source file:org.apache.zeppelin.spark.SparkInterpreter.java
public void populateSparkWebUrl(InterpreterContext ctx) { if (sparkUrl == null) { sparkUrl = getSparkUIUrl();// w ww. j a va2 s . c o m Map<String, String> infos = new java.util.HashMap<>(); if (sparkUrl != null) { infos.put("url", sparkUrl); if (ctx != null && ctx.getClient() != null) { logger.info("Sending metainfos to Zeppelin server: {}", infos.toString()); getZeppelinContext().setEventClient(ctx.getClient()); ctx.getClient().onMetaInfosReceived(infos); } } } }
From source file:org.gytheio.content.transform.ffmpeg.FfmpegContentTransformerWorker.java
protected void singleTransformInternal(File sourceFile, String sourceMimetype, File targetFile, String targetMimetype, TransformationOptions options, ContentTransformerWorkerProgressReporter progressReporter) throws Exception { Map<String, String> properties = new HashMap<String, String>(5); // set properties String sourceCommandOptions = getSourceCommandOptions(sourceFile, targetFile, sourceMimetype, targetMimetype, options);/*from w w w. j av a2 s .c o m*/ String targetCommandOptions = getTargetCommandOptions(sourceFile, targetFile, sourceMimetype, targetMimetype, options); properties.put(VAR_SOURCE_OPTIONS, sourceCommandOptions.trim()); properties.put(VAR_SOURCE, sourceFile.getAbsolutePath()); properties.put(VAR_TARGET_OPTIONS, targetCommandOptions.trim()); properties.put(VAR_TARGET, targetFile.getAbsolutePath()); long timeoutMs = options.getTimeoutMs(); if (logger.isTraceEnabled()) { logger.trace("Executing with timeoutMs=" + timeoutMs + ", properties=" + properties.toString()); } // execute the statement RuntimeExec.ExecutionResult result = executer.execute(properties, null, new FfmpegInputStreamReaderThreadFactory(progressReporter, isVersion1orGreater()), timeoutMs); if (result.getExitValue() != 0 && result.getStdErr() != null && result.getStdErr().length() > 0) { throw new Exception("Failed to perform ffmpeg transformation: \n" + result.toString() + "\n\n-------- Full Error --------\n" + result.getStdErr() + "\n----------------------------\n"); } // success if (logger.isDebugEnabled()) { logger.debug("ffmpeg executed successfully: \n" + result); } }
From source file:dev.meng.wikidata.fileusage.Fileusage.java
private void queryPageInfo(String lang, String pageId, PageInfo page) { Map<String, Object> params = new HashMap<>(); params.put("format", "json"); params.put("action", "query"); params.put("pageids", pageId); params.put("prop", "info"); try {/*from w ww .j av a2s . c o m*/ String urlString = String.format(Configure.FILEUSAGE.API_ENDPOINT, lang) + "?" + StringUtils.mapToURLParameters(params, Configure.FILEUSAGE.DEFAULT_ENCODING); URL url = new URL(urlString); JSONObject response = HttpUtils.queryForJSONResponse(url, Configure.FILEUSAGE.DEFAULT_ENCODING); try { JSONObject pageInfo = response.getJSONObject("query").getJSONObject("pages").getJSONObject(pageId); page.setTitle(pageInfo.getString("title")); page.setSize(pageInfo.getLong("length")); page.setLastRevisionId(Long.toString(pageInfo.getLong("lastrevid"))); } catch (JSONException ex) { Logger.log(this.getClass(), LogLevel.WARNING, "Error in response: " + urlString + ", " + response.toString() + ", " + ex.getMessage()); } } catch (UnsupportedEncodingException ex) { Logger.log(this.getClass(), LogLevel.WARNING, "Error in encoding: " + params.toString() + ", " + ex.getMessage()); } catch (MalformedURLException ex) { Logger.log(this.getClass(), LogLevel.ERROR, ex); } catch (IOException ex) { Logger.log(this.getClass(), LogLevel.ERROR, ex); } catch (StringConvertionException ex) { Logger.log(this.getClass(), LogLevel.ERROR, ex); } }
From source file:com.prey.net.PreyRestHttpClient.java
public PreyHttpResponse post(String url, Map<String, String> params, List<EntityFile> entityFiles) throws IOException { HttpPost method = new HttpPost(url); method.setHeader("Accept", "*/*"); SimpleMultipartEntity entity = new SimpleMultipartEntity(); for (Iterator<Map.Entry<String, String>> it = params.entrySet().iterator(); it.hasNext();) { Map.Entry<String, String> entry = it.next(); String key = entry.getKey(); String value = entry.getValue(); entity.addPart(key, value);/*from w w w . jav a2s.c om*/ } try { for (int i = 0; i < entityFiles.size(); i++) { EntityFile entityFile = entityFiles.get(i); boolean isLast = ((i + 1) == entityFiles.size() ? true : false); // PreyLogger.d("["+i+"]type:"+entityFile.getType()+" name:"+entityFile.getName()+ " File:" + entityFile.getFile() + " MimeType:" + entityFile.getMimeType()+" isLast:"+isLast); entity.addPart(entityFile.getType(), entityFile.getName(), entityFile.getFile(), entityFile.getMimeType(), isLast); } } catch (Exception e) { } method.setEntity(entity); PreyLogger.d("Sending using 'POST' - URI: " + url + " - parameters: " + params.toString()); httpclient.setRedirectHandler(new NotRedirectHandler()); HttpResponse httpResponse = httpclient.execute(method); PreyHttpResponse response = new PreyHttpResponse(httpResponse); PreyLogger.d("Response from server: " + response.toString()); return response; }
From source file:com.seatgeek.placesautocompletedemo.MainFragment.java
private void sendComment(int pos, final String title, final String cmt, final int rate, final ParkingCar location) { String endPoint = ""; // endPoint = EndPoints.SEND_COMMENT.replace("_ID_",pos+""); endPoint = EndPoints.FEEDS_COUNT;//from w w w. j ava2 s . c o m Log.e(TAG, "endPoint: " + endPoint); StringRequest strReq = new StringRequest(Request.Method.POST, endPoint, new com.android.volley.Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject obj = new JSONObject(response); // check for error if (obj.getBoolean("error") == false) { if (dialogReview.isShowing()) dialogReview.dismiss(); Toast.makeText(TheApp.getAppContext(), "Review OK!!", Toast.LENGTH_LONG).show(); // JSONArray commentsObj = obj.getJSONArray("messages"); // // for (int i = 0; i < commentsObj.length(); i++) { // JSONObject commentObj = (JSONObject) commentsObj.get(i); // // } } else { Toast.makeText(TheApp.getAppContext(), "" + obj.getJSONObject("error").getString("message"), Toast.LENGTH_LONG) .show(); } } catch (JSONException e) { Log.e(TAG, "json parsing error:dasd " + e.getMessage()); Toast.makeText(TheApp.getAppContext(), "json parse error: " + e.getMessage(), Toast.LENGTH_SHORT).show(); } } }, new com.android.volley.Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { NetworkResponse response = error.networkResponse; Log.e(TAG, "Volley error: " + error.getMessage() + ", code: " + response); Toast.makeText(TheApp.getAppContext(), "Volley error: " + error.getMessage(), Toast.LENGTH_SHORT).show(); // As of f605da3 the following should work // NetworkResponse response = error.networkResponse; if (error instanceof ServerError && response != null) { try { String res = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); // Now you can use any deserializer to make sense of data JSONObject obj = new JSONObject(res); } catch (UnsupportedEncodingException e1) { // Couldn't properly decode data to string e1.printStackTrace(); } catch (JSONException e2) { // returned data is not JSONObject? e2.printStackTrace(); } } } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); params.put("user_id", "100"); params.put("location_id", "50");// location.getIdLocation()+""); params.put("title", title); params.put("message", cmt); params.put("rate", rate + ""); Log.e(TAG, "Params: " + params.toString()); return params; }; }; int socketTimeout = 0; RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT); strReq.setRetryPolicy(policy); //Adding request to request queue TheApp.getInstance().addToRequestQueue(strReq); }
From source file:org.apache.flink.streaming.connectors.kafka.KafkaConsumerTestBase.java
/** * Read topic to list, only using Kafka code. *//*from ww w . jav a 2 s.co m*/ private static List<MessageAndMetadata<byte[], byte[]>> readTopicToList(String topicName, ConsumerConfig config, final int stopAfter) { ConsumerConnector consumerConnector = Consumer.createJavaConsumerConnector(config); // we request only one stream per consumer instance. Kafka will make sure that each consumer group // will see each message only once. Map<String, Integer> topicCountMap = Collections.singletonMap(topicName, 1); Map<String, List<KafkaStream<byte[], byte[]>>> streams = consumerConnector .createMessageStreams(topicCountMap); if (streams.size() != 1) { throw new RuntimeException("Expected only one message stream but got " + streams.size()); } List<KafkaStream<byte[], byte[]>> kafkaStreams = streams.get(topicName); if (kafkaStreams == null) { throw new RuntimeException("Requested stream not available. Available streams: " + streams.toString()); } if (kafkaStreams.size() != 1) { throw new RuntimeException( "Requested 1 stream from Kafka, bot got " + kafkaStreams.size() + " streams"); } LOG.info("Opening Consumer instance for topic '{}' on group '{}'", topicName, config.groupId()); ConsumerIterator<byte[], byte[]> iteratorToRead = kafkaStreams.get(0).iterator(); List<MessageAndMetadata<byte[], byte[]>> result = new ArrayList<>(); int read = 0; while (iteratorToRead.hasNext()) { read++; result.add(iteratorToRead.next()); if (read == stopAfter) { LOG.info("Read " + read + " elements"); return result; } } return result; }