當前位置: 首頁>>代碼示例>>Java>>正文


Java Collector類代碼示例

本文整理匯總了Java中org.apache.flink.util.Collector的典型用法代碼示例。如果您正苦於以下問題:Java Collector類的具體用法?Java Collector怎麽用?Java Collector使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Collector類屬於org.apache.flink.util包,在下文中一共展示了Collector類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: main

import org.apache.flink.util.Collector; //導入依賴的package包/類
public static void main(String... args) throws Exception {

        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStream<WikipediaEditEvent> edits = env.addSource(new WikipediaEditsSource());

        edits
            .timeWindowAll(Time.minutes(1))
            .apply(new AllWindowFunction<WikipediaEditEvent, Tuple3<Date, Long, Long>, TimeWindow>() {
                @Override
                public void apply(TimeWindow timeWindow, Iterable<WikipediaEditEvent> iterable, Collector<Tuple3<Date, Long, Long>> collector) throws Exception {
                    long count = 0;
                    long bytesChanged = 0;

                    for (WikipediaEditEvent event : iterable) {
                        count++;
                        bytesChanged += event.getByteDiff();
                    }

                    collector.collect(new Tuple3<>(new Date(timeWindow.getEnd()), count, bytesChanged));
                }
            })
            .print();


        env.execute();
    }
 
開發者ID:mushketyk,項目名稱:flink-examples,代碼行數:27,代碼來源:NumberOfWikiEditsPerWindow.java

示例2: flatMap

import org.apache.flink.util.Collector; //導入依賴的package包/類
@Override
public void flatMap(String tweetJsonStr, Collector<Tuple2<String, Integer>> collector) throws Exception {
    JsonNode tweetJson = mapper.readTree(tweetJsonStr);
    JsonNode entities = tweetJson.get("entities");
    if (entities == null) return;

    JsonNode hashtags = entities.get("hashtags");
    if (hashtags == null) return;

    for (Iterator<JsonNode> iter = hashtags.getElements(); iter.hasNext();) {
        JsonNode node = iter.next();
        String hashtag = node.get("text").getTextValue();

        if (hashtag.matches("\\w+")) {
            collector.collect(new Tuple2<>(hashtag, 1));
        }
    }
}
 
開發者ID:mushketyk,項目名稱:flink-examples,代碼行數:19,代碼來源:TopTweet.java

示例3: reduce

import org.apache.flink.util.Collector; //導入依賴的package包/類
@Override
public void reduce(Iterable<Tuple4<Long, Integer, String, TagEvent>> values, Collector<ChartsResult> out) throws Exception {
    int counter = 0;
    String group= "";
    log.info("Reducing Groups and applyting limit(" + limit + ") by field " + groupPosition);

    for (Tuple4<Long, Integer, String, TagEvent> t : values) {
        if (!t.getField(groupPosition).equals(group))    {
            counter= 0;
            group= t.f2;
        }
        if (counter < limit) {
            out.collect(new ChartsResult(t.f0, t.f1, t.f3));
        }
        counter++;
    }
}
 
開發者ID:aaitor,項目名稱:flink-charts,代碼行數:18,代碼來源:StateChartsPipeline.java

示例4: apply

import org.apache.flink.util.Collector; //導入依賴的package包/類
/**
 * Evaluates the window and outputs none or several elements.
 *
 * @param window The window that is being evaluated.
 * @param values The elements in the window being evaluated.
 * @param out    A collector for emitting elements.
 * @throws Exception The function may throw exceptions to fail the program and trigger recovery.
 */
@Override
public void apply(TimeWindow window, Iterable<WindowWordWithCount> values, Collector<WindowWordRanking> out) throws Exception {
  this.ranking.setWStart(window.getStart());
  this.ranking.setWEnd(window.getEnd());

  List<WindowWordWithCount> rank = this.ranking.getRank();

  rank.clear();
  values.forEach(rank::add);
  rank.sort((e1,e2) -> Long.compare(e2.getCount(), e1.getCount()));
  int size = rank.size();
  rank.subList(Math.min(this.rankSize, size), size).clear();

  LOG.debug("WOUT: {}", this.ranking);

  out.collect(this.ranking);
}
 
開發者ID:gmarciani,項目名稱:flink-scaffolding,代碼行數:26,代碼來源:WordRankerWindowFunction.java

示例5: flatMap

import org.apache.flink.util.Collector; //導入依賴的package包/類
@Override
public void flatMap(RichSensorEvent event, Collector<PlayerSpeedStatistics> out) throws Exception {
  if (event.equals(this.eos)) {
    //LOG.debug("EOS RECEIVED");
    out.collect(new PlayerSpeedStatistics(0,0,0, this.averageSpeed));
    out.collect(END_OF_STREAM);
    super.close();
  }

  this.numEvents++;

  //LOG.debug("IN ({}): {}", this.numEvents, event);

  final double speed = PhysicsUtil.computeSpeed(event.getV(), event.getVx(), event.getVy(), event.getA(), event.getAx(), event.getAy());

  this.averageSpeed = ((this.averageSpeed * (this.numEvents - 1)) + speed) / this.numEvents;

  //LOG.debug("ACC: {} {}", this.numEvents, this.averageSpeed);
}
 
開發者ID:braineering,項目名稱:socstream,代碼行數:20,代碼來源:PlayerSpeedStatisticsCalculator.java

示例6: apply

import org.apache.flink.util.Collector; //導入依賴的package包/類
/**
 * Evaluates the window and outputs none or several elements.
 *
 * @param window The window that is being evaluated.
 * @param values The elements in the window being evaluated.
 * @param out    A collector for emitting elements.
 * @throws Exception The function may throw exceptions to fail the program and trigger recovery.
 */
@Override
public void apply(TimeWindow window, Iterable<PlayerSpeedStatistics> values, Collector<PlayersSpeedRanking> out) throws Exception {
  this.ranking.setTsStart(window.getStart());
  this.ranking.setTsStop(window.getEnd());

  List<RankingElement> rank = this.ranking.getRank();

  rank.clear();
  values.forEach(e -> rank.add(new RankingElement(e.getPid(), e.getAverageSpeed())));
  rank.sort(Comparator.reverseOrder());
  int size = rank.size();
  rank.subList(Math.min(this.rankSize, size), size).clear();

  //LOG.debug("WOUT: {}", this.ranking);

  out.collect(this.ranking);
}
 
開發者ID:braineering,項目名稱:socstream,代碼行數:26,代碼來源:GlobalRankerWindowFunction.java

示例7: processElement

import org.apache.flink.util.Collector; //導入依賴的package包/類
@Override
public void processElement(Tuple3<String, Long, String> message, Context context,
    Collector<Tuple3<String, Long, String>> out) throws Exception {

  TimerService timerService = context.timerService();

  if (context.timestamp() > timerService.currentWatermark()) {
    PriorityQueue<Tuple3<String, Long, String>> queue = queueState.value();
    if (queue == null) {
      queue = new PriorityQueue<>(15, new RawMessageTuplesComparator());
    }
    queue.add(message);
    queueState.update(queue);
    // register a timer to be fired when the watermark passes this message timestamp
    timerService.registerEventTimeTimer(message.f1);
  } else {
    String outOfOrderErrorMessage = "out of order message: " + message.f2;
    logger.info(outOfOrderErrorMessage);
    throw new Exception(outOfOrderErrorMessage);
  }
}
 
開發者ID:ehabqadah,項目名稱:in-situ-processing-datAcron,代碼行數:22,代碼來源:RawMessagesSorter.java

示例8: processElement

import org.apache.flink.util.Collector; //導入依賴的package包/類
@Override
public void processElement(AisMessage message, Context context, Collector<AisMessage> out)
    throws Exception {

  TimerService timerService = context.timerService();

  PriorityQueue<AisMessage> queue = queueState.value();
  if (queue == null) {
    queue =
        new PriorityQueue<>(MAX_NUMBER_OF_QUEUED_ELEMENTS + 1, new PositionMessagesComparator());
  }
  long timestamp = System.currentTimeMillis();
  if (context.timestamp() > timerService.currentWatermark()) {
    queue.add(message);
    queueState.update(queue);
    // register a timer to be fired when the watermark passes this message timestamp
    timerService.registerEventTimeTimer(timestamp);
  } else {
    // logger.info("out of order message: " + message.toString());
    // throw new Exception(timerService.currentWatermark() + "out of order message: "
    // + message.toString());
    queue.add(message);
    queueState.update(queue);

  }
}
 
開發者ID:ehabqadah,項目名稱:in-situ-processing-datAcron,代碼行數:27,代碼來源:AisMessagesStreamSorter.java

示例9: flatMap

import org.apache.flink.util.Collector; //導入依賴的package包/類
@Override
public void flatMap(Event event, Collector<Event.Alert> collector) throws Exception {
	EventStateMachine.State value = state.value();
	if(value == null) {
		value = EventStateMachine.Transitions.initialState;
	}

	EventStateMachine.State nextValue = value.transition(event.getEvent());
	if(nextValue instanceof EventStateMachine.InvalidTransition) {
		Event.Alert alert = new Event.Alert(Instant.now(), event, value);
		collector.collect(alert);
		state.update(null);
	} else if (!nextValue.terminal()){
		state.update(nextValue);
	} else {
		state.update(null);
	}
}
 
開發者ID:pravega,項目名稱:pravega-samples,代碼行數:19,代碼來源:EventStateMachineMapper.java

示例10: apply

import org.apache.flink.util.Collector; //導入依賴的package包/類
/**
 * @param key the key to calculate by (address or id in this section)
 * @param window the time window
 * @param lamps the Iterable<{@link StreetLamp}>
 * @param collector the collector to handle the hand off between streams
 * @throws Exception
 */
@Override
public void apply(Integer key, TimeWindow window, Iterable<StreetLamp> lamps, Collector<LampEMAConsumption> collector) throws Exception {

    // creating lamp consumption
    LampEMAConsumption lampConsumption = new LampEMAConsumption();
    lampConsumption.setId(key);
    lampConsumption.setComputed(Instant.now().getEpochSecond());

    // iterating over lamps in window
    for (Object lamp : lamps) {
        if (lampConsumption.getConsumption() == 0) {
            // initializing average
            lampConsumption.setConsumption(((StreetLamp) lamp).getConsumption());
            lampConsumption.setAddress(((StreetLamp) lamp).getAddress());
        } else {
            // using EMA to calculate average on the selected window
            // the formula is: S_t = alpha * Y_t + (1 - alpha) * S_t-1
            lampConsumption.setConsumption(ALPHA * ((StreetLamp) lamp).getConsumption() + (1 - ALPHA) * lampConsumption.getConsumption());
        }
    }

    // returning the consumption
    collector.collect(lampConsumption);
}
 
開發者ID:ProjectEmber,項目名稱:project-ember,代碼行數:32,代碼來源:EmberEMAWindowMean.java

示例11: apply

import org.apache.flink.util.Collector; //導入依賴的package包/類
/**
 * @param key the key to calculate by (address or id in this section)
 * @param window the time window
 * @param lamps the Iterable<{@link StreetLamp}>
 * @param collector the collector to handle the hand off between streams
 * @throws Exception
 */
@Override
public void apply(String key, TimeWindow window, Iterable<StreetLamp> lamps, Collector<LampEMAConsumptionStreet> collector) throws Exception {

    // creating lamp consumption
    LampEMAConsumptionStreet streetConsumption = new LampEMAConsumptionStreet();
    streetConsumption.setAddress(key);
    streetConsumption.setComputed(Instant.now().getEpochSecond());

    // iterating over lamps in window
    for (Object lamp : lamps) {
        if (streetConsumption.getConsumption() == 0) {
            // initializing average
            streetConsumption.setConsumption(((StreetLamp) lamp).getConsumption());
        } else {
            // using EMA to calculate average on the selected window
            // the formula is: S_t = alpha * Y_t + (1 - alpha) * S_t-1
            streetConsumption.setConsumption(ALPHA * ((StreetLamp) lamp).getConsumption() + (1 - ALPHA) * streetConsumption.getConsumption());
        }
    }

    // returning the consumption
    collector.collect(streetConsumption);
}
 
開發者ID:ProjectEmber,項目名稱:project-ember,代碼行數:31,代碼來源:EmberEMAWindowMeanAddress.java

示例12: ReduceFacade

import org.apache.flink.util.Collector; //導入依賴的package包/類
public ReduceFacade(ReduceFunction<T> reducer, Collector<T> outputCollector, boolean objectReuseEnabled) {
	this.reducer = reducer;
	this.outputCollector = outputCollector;
	this.objectReuseEnabled = objectReuseEnabled;
	this.prober = getProber(buildSideComparator, new SameTypePairComparator<>(buildSideComparator));
	this.reuse = buildSideSerializer.createInstance();
}
 
開發者ID:axbaretto,項目名稱:flink,代碼行數:8,代碼來源:InPlaceMutableHashTable.java

示例13: reduce

import org.apache.flink.util.Collector; //導入依賴的package包/類
@Override
public void reduce(Iterable<Edge> edgesIter, Collector<Triad> out) throws Exception {

	final Iterator<Edge> edges = edgesIter.iterator();

	// clear vertex list
	vertices.clear();

	// read first edge
	Edge firstEdge = edges.next();
	outTriad.setFirstVertex(firstEdge.getFirstVertex());
	vertices.add(firstEdge.getSecondVertex());

	// build and emit triads
	while (edges.hasNext()) {
		Integer higherVertexId = edges.next().getSecondVertex();

		// combine vertex with all previously read vertices
		for (Integer lowerVertexId : vertices) {
			outTriad.setSecondVertex(lowerVertexId);
			outTriad.setThirdVertex(higherVertexId);
			out.collect(outTriad);
		}
		vertices.add(higherVertexId);
	}
}
 
開發者ID:axbaretto,項目名稱:flink,代碼行數:27,代碼來源:EnumTriangles.java

示例14: combine

import org.apache.flink.util.Collector; //導入依賴的package包/類
@Override
public void combine(Iterable<Tuple3<Integer, Long, String>> values, Collector<Tuple3<Integer, Long, String>> out) {

	Iterator<Tuple3<Integer, Long, String>> it = values.iterator();
	Tuple3<Integer, Long, String> t = it.next();

	int i = t.f0;
	out.collect(t);

	while (it.hasNext()) {
		t = it.next();
		if (i > t.f0) {
			t.f2 = "INVALID-ORDER!";
			out.collect(t);
		}
	}

}
 
開發者ID:axbaretto,項目名稱:flink,代碼行數:19,代碼來源:GroupReduceITCase.java

示例15: coGroup

import org.apache.flink.util.Collector; //導入依賴的package包/類
@Override
public void coGroup(Iterable<Edge<K, EV>> edges, Iterable<Vertex<K, Tuple3<VV, LongValue, LongValue>>> state,
					Collector<Tuple2<K, Message>> out) throws Exception {

	final Iterator<Vertex<K, Tuple3<VV, LongValue, LongValue>>> stateIter = state.iterator();

	if (stateIter.hasNext()) {
		Vertex<K, Tuple3<VV, LongValue, LongValue>> vertexWithDegrees = stateIter.next();

		nextVertex.f0 = vertexWithDegrees.f0;
		nextVertex.f1 = vertexWithDegrees.f1.f0;

		scatterFunction.setInDegree(vertexWithDegrees.f1.f1.getValue());
		scatterFunction.setOutDegree(vertexWithDegrees.f1.f2.getValue());

		scatterFunction.set(edges.iterator(), out, vertexWithDegrees.getId());
		scatterFunction.sendMessages(nextVertex);
	}
}
 
開發者ID:axbaretto,項目名稱:flink,代碼行數:20,代碼來源:ScatterGatherIteration.java


注:本文中的org.apache.flink.util.Collector類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。