List of usage examples for org.apache.commons.lang3.tuple MutablePair MutablePair
public MutablePair(final L left, final R right)
From source file:com.datatorrent.stram.ResourceRequestHandler.java
/** * Add container request to list of issued requests to Yarn along with current loop counter * @param requestedResources//from w ww .j ava2 s.c om * @param loopCounter * @param containerRequests * @param csr * @param cr */ public void addContainerRequest( Map<StreamingContainerAgent.ContainerStartRequest, MutablePair<Integer, ContainerRequest>> requestedResources, int loopCounter, List<ContainerRequest> containerRequests, StreamingContainerAgent.ContainerStartRequest csr, ContainerRequest cr) { MutablePair<Integer, ContainerRequest> pair = new MutablePair<>(loopCounter, cr); requestedResources.put(csr, pair); containerRequests.add(cr); }
From source file:de.hub.cs.dbis.lrb.operators.AverageVehicleSpeedBolt.java
@Override public void execute(Tuple input) { this.inputPositionReport.clear(); this.inputPositionReport.addAll(input.getValues()); LOGGER.trace(this.inputPositionReport.toString()); Integer vid = this.inputPositionReport.getVid(); short minute = this.inputPositionReport.getMinuteNumber(); int speed = this.inputPositionReport.getSpeed().intValue(); this.segment.set(this.inputPositionReport); assert (minute >= this.currentMinute); if (minute > this.currentMinute) { // emit all values for last minute // (because input tuples are ordered by ts, we can close the last minute safely) for (Entry<Integer, Pair<AvgValue, SegmentIdentifier>> entry : this.avgSpeedsMap.entrySet()) { Pair<AvgValue, SegmentIdentifier> value = entry.getValue(); SegmentIdentifier segId = value.getRight(); // VID, Minute-Number, X-Way, Segment, Direction, Avg(speed) this.collector.emit(new AvgVehicleSpeedTuple(entry.getKey(), new Short(this.currentMinute), segId.getXWay(), segId.getSegment(), segId.getDirection(), value.getLeft().getAverage())); }/*from www. j av a 2 s .c o m*/ this.avgSpeedsMap.clear(); this.currentMinute = minute; } Pair<AvgValue, SegmentIdentifier> vehicleEntry = this.avgSpeedsMap.get(vid); if (vehicleEntry != null && !vehicleEntry.getRight().equals(this.segment)) { SegmentIdentifier segId = vehicleEntry.getRight(); // VID, Minute-Number, X-Way, Segment, Direction, Avg(speed) this.collector.emit(new AvgVehicleSpeedTuple(vid, new Short(this.currentMinute), segId.getXWay(), segId.getSegment(), segId.getDirection(), vehicleEntry.getLeft().getAverage())); // set to null to get new vehicle entry below vehicleEntry = null; } if (vehicleEntry == null) { vehicleEntry = new MutablePair<AvgValue, SegmentIdentifier>(new AvgValue(speed), this.segment.copy()); this.avgSpeedsMap.put(vid, vehicleEntry); } else { vehicleEntry.getLeft().updateAverage(speed); } this.collector.ack(input); }
From source file:com.wolvereness.renumerated.Renumerated.java
private void process() throws Throwable { validateInput();//www . j a v a2s . co m final MultiProcessor executor = MultiProcessor.newMultiProcessor(cores - 1, new ThreadFactoryBuilder().setDaemon(true) .setNameFormat(Renumerated.class.getName() + "-processor-%d") .setUncaughtExceptionHandler(this).build()); final Future<?> fileCopy = executor.submit(new Callable<Object>() { @Override public Object call() throws Exception { if (original != null) { if (original.exists()) { original.delete(); } Files.copy(input, original); } return null; } }); final List<Pair<ZipEntry, Future<byte[]>>> fileEntries = newArrayList(); final List<Pair<MutableObject<ZipEntry>, Future<byte[]>>> classEntries = newArrayList(); { final ZipFile input = new ZipFile(this.input); final Enumeration<? extends ZipEntry> inputEntries = input.entries(); while (inputEntries.hasMoreElements()) { final ZipEntry entry = inputEntries.nextElement(); final Future<byte[]> future = executor.submit(new Callable<byte[]>() { @Override public byte[] call() throws Exception { return ByteStreams.toByteArray(input.getInputStream(entry)); } }); if (entry.getName().endsWith(".class")) { classEntries.add(new MutablePair<MutableObject<ZipEntry>, Future<byte[]>>( new MutableObject<ZipEntry>(entry), future)); } else { fileEntries.add(new ImmutablePair<ZipEntry, Future<byte[]>>(entry, future)); } } for (final Pair<MutableObject<ZipEntry>, Future<byte[]>> pair : classEntries) { final byte[] data = pair.getRight().get(); pair.setValue(executor.submit(new Callable<byte[]>() { String className; List<String> fields; @Override public byte[] call() throws Exception { try { return method(); } catch (final Exception ex) { throw new Exception(pair.getLeft().getValue().getName(), ex); } } private byte[] method() throws Exception { final ClassReader clazz = new ClassReader(data); clazz.accept(new ClassVisitor(ASM4) { @Override public void visit(final int version, final int access, final String name, final String signature, final String superName, final String[] interfaces) { if (superName.equals("java/lang/Enum")) { className = name; } } @Override public FieldVisitor visitField(final int access, final String name, final String desc, final String signature, final Object value) { if (className != null && (access & 0x4000) != 0) { List<String> fieldNames = fields; if (fieldNames == null) { fieldNames = fields = newArrayList(); } fieldNames.add(name); } return null; } }, ClassReader.SKIP_CODE); if (className == null) return data; final String classDescriptor = Type.getObjectType(className).getDescriptor(); final ClassWriter writer = new ClassWriter(0); clazz.accept(new ClassVisitor(ASM4, writer) { @Override public MethodVisitor visitMethod(final int access, final String name, final String desc, final String signature, final String[] exceptions) { final MethodVisitor methodVisitor = super.visitMethod(access, name, desc, signature, exceptions); if (!name.equals("<clinit>")) { return methodVisitor; } return new MethodVisitor(ASM4, methodVisitor) { final Iterator<String> it = fields.iterator(); boolean active; String lastName; @Override public void visitTypeInsn(final int opcode, final String type) { if (!active && it.hasNext()) { // Initiate state machine if (opcode != NEW) throw new AssertionError("Unprepared for " + opcode + " on " + type + " in " + className); active = true; } super.visitTypeInsn(opcode, type); } @Override public void visitLdcInsn(final Object cst) { if (active && lastName == null) { if (!(cst instanceof String)) throw new AssertionError( "Unprepared for " + cst + " in " + className); // Switch the first constant in the Enum constructor super.visitLdcInsn(lastName = it.next()); } else { super.visitLdcInsn(cst); } } @Override public void visitFieldInsn(final int opcode, final String owner, final String name, final String desc) { if (opcode == PUTSTATIC && active && lastName != null && owner.equals(className) && desc.equals(classDescriptor) && name.equals(lastName)) { // Finish the current state machine active = false; lastName = null; } super.visitFieldInsn(opcode, owner, name, desc); } }; } }, ClassReader.EXPAND_FRAMES); final MutableObject<ZipEntry> key = pair.getLeft(); key.setValue(new ZipEntry(key.getValue().getName())); return writer.toByteArray(); } })); } for (final Pair<ZipEntry, Future<byte[]>> pair : fileEntries) { pair.getRight().get(); } input.close(); } fileCopy.get(); FileOutputStream fileOut = null; JarOutputStream jar = null; try { jar = new JarOutputStream(fileOut = new FileOutputStream(output)); for (final Pair<ZipEntry, Future<byte[]>> fileEntry : fileEntries) { jar.putNextEntry(fileEntry.getLeft()); jar.write(fileEntry.getRight().get()); } for (final Pair<MutableObject<ZipEntry>, Future<byte[]>> classEntry : classEntries) { final byte[] data = classEntry.getRight().get(); final ZipEntry entry = classEntry.getLeft().getValue(); entry.setSize(data.length); jar.putNextEntry(entry); jar.write(data); } } finally { if (jar != null) { try { jar.close(); } catch (final IOException ex) { } } if (fileOut != null) { try { fileOut.close(); } catch (final IOException ex) { } } } final Pair<Thread, Throwable> uncaught = this.uncaught; if (uncaught != null) throw new MojoExecutionException(String.format("Uncaught exception in %s", uncaught.getLeft()), uncaught.getRight()); }
From source file:com.cognifide.bdd.demo.jcr.JcrTest.java
public Map<String, Pair<String, Integer>> getPropertiesMap() { Map<String, Pair<String, Integer>> property = new HashMap<>(); Pair<String, Integer> entry = new MutablePair<>("value1", 1); property.put("property1", entry); return property; }
From source file:AIR.Common.xml.XmlReader.java
private boolean readToDescendant(String item) throws XmlReaderException, IOException { MutablePair<Content, Integer> alwaysTop = null; if (_stack.size() > 0) { alwaysTop = _stack.peek();//from w w w. ja v a 2 s.co m } while (_stack.size() != 0) { MutablePair<Content, Integer> topElement = _stack.peek(); if (topElement.getLeft().getCType() == CType.Element) { Element topElementNode = (Element) topElement.getLeft(); if (StringUtils.equals(item, topElementNode.getName())) return true; int nextChild = topElement.getRight() + 1; if (topElementNode.getChildren().size() > nextChild) { topElement.setRight(nextChild); Element nextTraversalNode = topElementNode.getChildren().get(nextChild); _stack.push(new MutablePair<Content, Integer>(nextTraversalNode, -1)); } else { // we do not want to pop the original top node (alwaysTop) as we are // only doing descendant. if (!alwaysTop.equals(topElement)) _stack.pop(); else break; } } } return false; }
From source file:hu.mta.sztaki.lpds.cloud.simulator.DeferredEvent.java
/** * Allows constructing objects that will receive an eventAction() call from * Timed after delay ticks./*from w w w.java2s .c o m*/ * * @param delay * the number of ticks that should pass before this deferred * event object's eventAction() will be called. */ public DeferredEvent(final long delay) { if (delay <= 0) { eventArrival = Timed.getFireCount(); eventAction(); received = true; return; } eventArrival = Timed.calcTimeJump(delay); MutablePair<Integer, DeferredEvent[]> simultaneousReceiverPairs = toSweep.get(eventArrival); if (simultaneousReceiverPairs == null) { simultaneousReceiverPairs = new MutablePair<Integer, DeferredEvent[]>(0, new DeferredEvent[5]); toSweep.put(eventArrival, simultaneousReceiverPairs); } int len = simultaneousReceiverPairs.getLeft(); DeferredEvent[] simultaneousReceivers = simultaneousReceiverPairs.getRight(); if (len == simultaneousReceivers.length) { DeferredEvent[] temp = new DeferredEvent[simultaneousReceivers.length * 2]; System.arraycopy(simultaneousReceivers, 0, temp, 0, len); simultaneousReceivers = temp; simultaneousReceiverPairs.setRight(temp); } simultaneousReceivers[len++] = this; simultaneousReceiverPairs.setLeft(len); if (!dispatcherSingleton.isSubscribed() || dispatcherSingleton.getNextEvent() > eventArrival) { dispatcherSingleton.updateDispatcher(); } }
From source file:com.datatorrent.lib.db.jdbc.JdbcPojoPollableOpeartorTest.java
@Test public void testRecovery() throws IOException { int operatorId = 1; when(windowDataManagerMock.getLargestCompletedWindow()).thenReturn(1L); when(windowDataManagerMock.retrieve(1)).thenReturn(new MutablePair<Integer, Integer>(0, 4)); insertEvents(10, true, 0);//from w w w. j a v a 2 s . c om JdbcStore store = new JdbcStore(); store.setDatabaseDriver(DB_DRIVER); store.setDatabaseUrl(URL); List<FieldInfo> fieldInfos = getFieldInfos(); Attribute.AttributeMap.DefaultAttributeMap portAttributes = new Attribute.AttributeMap.DefaultAttributeMap(); portAttributes.put(Context.PortContext.TUPLE_CLASS, TestPOJOEvent.class); TestPortContext tpc = new TestPortContext(portAttributes); Attribute.AttributeMap.DefaultAttributeMap partitionAttributeMap = new Attribute.AttributeMap.DefaultAttributeMap(); partitionAttributeMap.put(DAG.APPLICATION_ID, APP_ID); partitionAttributeMap.put(Context.DAGContext.APPLICATION_PATH, dir); OperatorContextTestHelper.TestIdOperatorContext context = new OperatorContextTestHelper.TestIdOperatorContext( operatorId, partitionAttributeMap); JdbcPOJOPollInputOperator inputOperator = new JdbcPOJOPollInputOperator(); inputOperator.setStore(store); inputOperator.setTableName(TABLE_POJO_NAME); inputOperator.setKey("id"); inputOperator.setFieldInfos(fieldInfos); inputOperator.setFetchSize(100); inputOperator.setBatchSize(100); inputOperator.lastEmittedRow = 0; //setting as not calling partition logic inputOperator.rangeQueryPair = new KeyValPair<Integer, Integer>(0, 8); inputOperator.outputPort.setup(tpc); inputOperator.setScheduledExecutorService(mockscheduler); inputOperator.setup(context); inputOperator.setWindowManager(windowDataManagerMock); inputOperator.activate(context); CollectorTestSink<Object> sink = new CollectorTestSink<>(); inputOperator.outputPort.setSink(sink); inputOperator.beginWindow(0); verify(mockscheduler, times(0)).scheduleAtFixedRate(any(Runnable.class), anyLong(), anyLong(), any(TimeUnit.class)); inputOperator.emitTuples(); inputOperator.endWindow(); inputOperator.beginWindow(1); verify(mockscheduler, times(1)).scheduleAtFixedRate(any(Runnable.class), anyLong(), anyLong(), any(TimeUnit.class)); }
From source file:com.ottogroup.bi.streaming.operator.json.aggregate.functions.IntegerContentAggregateFunctionTest.java
/** * Test case for {@link IntegerContentAggregateFunction#average(org.apache.commons.lang3.tuple.MutablePair, Integer)} * being provided null as input to new value parameter *///from ww w .j av a 2 s.c o m @Test public void testAverage_withNewValueNullInput() throws Exception { MutablePair<Integer, Integer> result = new IntegerContentAggregateFunction() .average(new MutablePair<Integer, Integer>(Integer.valueOf(125), Integer.valueOf(3)), null); Assert.assertEquals(Integer.valueOf(125), result.getLeft()); Assert.assertEquals(Integer.valueOf(3), result.getRight()); }
From source file:com.ottogroup.bi.streaming.operator.json.aggregate.functions.DoubleContentAggregateFunctionTest.java
/** * Test case for {@link DoubleContentAggregateFunction#average(org.apache.commons.lang3.tuple.MutablePair, Double)} * being provided null to value variable *//*from www . j a v a 2 s . c o m*/ @Test public void testAverage_withNullInputToValue() throws Exception { MutablePair<Double, Integer> result = new DoubleContentAggregateFunction() .average(new MutablePair<Double, Integer>(Double.valueOf(1.34), Integer.valueOf(4)), null); Assert.assertEquals(Double.valueOf(1.34), result.getLeft()); Assert.assertEquals(Integer.valueOf(4), result.getRight()); }
From source file:com.ottogroup.bi.streaming.operator.json.aggregate.functions.DoubleContentAggregateFunctionTest.java
/** * Test case for {@link DoubleContentAggregateFunction#average(org.apache.commons.lang3.tuple.MutablePair, Double)} * being provided valid input/* w ww . j av a 2 s . c o m*/ */ @Test public void testAverage_withValidInput() throws Exception { MutablePair<Double, Integer> result = new DoubleContentAggregateFunction().average( new MutablePair<Double, Integer>(Double.valueOf(1.34), Integer.valueOf(4)), Double.valueOf(8.22)); Assert.assertEquals(Double.valueOf(9.56), result.getLeft()); Assert.assertEquals(Integer.valueOf(5), result.getRight()); }