Java Code Examples for java.util.ArrayDeque#add()

The following examples show how to use java.util.ArrayDeque#add() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SunLight.java    From Cubes with MIT License 6 votes vote down vote up
public static void initialSunlight(Area area) {
  try (LightWorldSection worldSection = new LightWorldSection(area)) {
    ArrayDeque<LightNode> lightQueue = new ArrayDeque<>();
    int max = 15;
    for (int x = 0; x < SIZE_BLOCKS; x++) {
      for (int z = 0; z < SIZE_BLOCKS; z++) {
        int hmRef = getHeightMapRef(x, z);
        int h = area.heightmap[hmRef] + 1;

        int ref = getRef(x, h, z);
        for (int y = 0; y <= (area.maxY - h); y++) {
          int r = ref + (y * MAX_Y_OFFSET);
          area.light[r] = (byte) ((area.light[r] & 0xF) | (max << 4));
        }

        lightQueue.add(new LightNode(x + area.minBlockX, h, z + area.minBlockZ, max));
      }
    }
    propagateAdd(lightQueue, worldSection);
  }
}
 
Example 2
Source File: ArrayDequeTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * descendingIterator.remove() removes current element
 */
public void testDescendingIteratorRemove() {
    final ArrayDeque q = new ArrayDeque();
    final Random rng = new Random();
    for (int iters = 0; iters < 100; ++iters) {
        int max = rng.nextInt(5) + 2;
        int split = rng.nextInt(max - 1) + 1;
        for (int j = max; j >= 1; --j)
            q.add(new Integer(j));
        Iterator it = q.descendingIterator();
        for (int j = 1; j <= split; ++j)
            assertEquals(it.next(), new Integer(j));
        it.remove();
        assertEquals(it.next(), new Integer(split + 1));
        for (int j = 1; j <= split; ++j)
            q.remove(new Integer(j));
        it = q.descendingIterator();
        for (int j = split + 1; j <= max; ++j) {
            assertEquals(it.next(), new Integer(j));
            it.remove();
        }
        assertFalse(it.hasNext());
        assertTrue(q.isEmpty());
    }
}
 
Example 3
Source File: TestBase.java    From dfalex with Apache License 2.0 6 votes vote down vote up
int _countStates(DfaState<?>... starts)
{
    ArrayDeque<DfaState<?>> togo = new ArrayDeque<>();
    HashSet<DfaState<?>> checkSet = new HashSet<>();
    for (DfaState<?> start : starts)
    {
        if (checkSet.add(start))
        {
            togo.add(start);
        }
    }
    while(!togo.isEmpty())
    {
        DfaState<?> scanst = togo.removeFirst();
        scanst.enumerateTransitions((c1,c2,newstate)->{
            if (checkSet.add(newstate))
            {
                togo.add(newstate);
            }
        });
    }
    return checkSet.size();
}
 
Example 4
Source File: ArrayDequeTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * descendingIterator.remove() removes current element
 */
public void testDescendingIteratorRemove() {
    final ArrayDeque q = new ArrayDeque();
    final Random rng = new Random();
    for (int iters = 0; iters < 100; ++iters) {
        int max = rng.nextInt(5) + 2;
        int split = rng.nextInt(max - 1) + 1;
        for (int j = max; j >= 1; --j)
            q.add(new Integer(j));
        Iterator it = q.descendingIterator();
        for (int j = 1; j <= split; ++j)
            assertEquals(it.next(), new Integer(j));
        it.remove();
        assertEquals(it.next(), new Integer(split + 1));
        for (int j = 1; j <= split; ++j)
            q.remove(new Integer(j));
        it = q.descendingIterator();
        for (int j = split + 1; j <= max; ++j) {
            assertEquals(it.next(), new Integer(j));
            it.remove();
        }
        assertFalse(it.hasNext());
        assertTrue(q.isEmpty());
    }
}
 
Example 5
Source File: ArrayDequeTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void test_forEachRemaining_CME() throws Exception {
    ArrayDeque<String> adq = new ArrayDeque<>();
    adq.add("foo");

    // The ArrayDeque forEachRemaining implementation doesn't use a precise check
    // for concurrent modifications.
    adq.iterator().forEachRemaining(s -> adq.add(s));
}
 
Example 6
Source File: BlockLight.java    From Cubes with MIT License 5 votes vote down vote up
private static void tryPropagateRemove(ArrayDeque<LightNode> removeQueue, ArrayDeque<LightNode> addQueue, LightWorldSection w, int x, int y, int z, int l) {
  Area a = w.getArea(CoordinateConverter.area(x), CoordinateConverter.area(z));
  int ref = getRef(x - a.minBlockX, y, z - a.minBlockZ);
  if (!a.isReady() || y > a.maxY || !TransparencyManager.isTransparent(a.blocks[ref])) return;
  int p = a.light[ref] & 0xF;
  if (p != 0 && p < l) {
    a.light[ref] = (byte) (a.light[ref] & 0xF0); // same as ((a.light[ref] & 0xF0) | 0)
    a.updateRender(y / SIZE_BLOCKS);
    a.modify();
    removeQueue.add(new LightNode(x, y, z, p));
  } else if (p >= l) {
    addQueue.add(new LightNode(x, y, z, p));
  }
}
 
Example 7
Source File: SunLight.java    From Cubes with MIT License 5 votes vote down vote up
private static void tryPropagateRemove(ArrayDeque<LightNode> removeQueue, ArrayDeque<LightNode> addQueue, LightWorldSection w, int x, int y, int z, int l) {
  Area a = w.getArea(CoordinateConverter.area(x), CoordinateConverter.area(z));
  int ref = getRef(x - a.minBlockX, y, z - a.minBlockZ);
  if (!a.isReady() || y > a.maxY || !TransparencyManager.isTransparent(a.blocks[ref])) return;
  int p = ((a.light[ref] >> 4) & 0xF);
  if (p != 0 && p < l) {
    a.light[ref] = (byte) (a.light[ref] & 0xF); // same as ((a.light[ref] & 0xF0) | (0 << 4))
    a.updateRender(y / SIZE_BLOCKS);
    a.modify();
    removeQueue.add(new LightNode(x, y, z, p));
  } else if (p >= l) {
    addQueue.add(new LightNode(x, y, z, p));
  }
}
 
Example 8
Source File: LinkageCheckTask.java    From cloud-opensource-java with Apache License 2.0 5 votes vote down vote up
private String dependencyPathToArtifacts(
    ResolvedComponentResult componentResult, Set<ClassPathEntry> classPathEntries) {

  ImmutableSet<String> targetCoordinates =
      classPathEntries.stream()
          .map(ClassPathEntry::getArtifact)
          .map(Artifacts::toCoordinates)
          .collect(toImmutableSet());

  StringBuilder output = new StringBuilder();

  ArrayDeque<ResolvedComponentResult> stack = new ArrayDeque<>();
  stack.add(componentResult);

  ImmutableListMultimap.Builder<String, String> coordinatesToDependencyPaths =
      ImmutableListMultimap.builder();

  recordDependencyPaths(coordinatesToDependencyPaths, stack, targetCoordinates);

  ImmutableListMultimap<String, String> dependencyPaths = coordinatesToDependencyPaths.build();
  for (String coordinates : dependencyPaths.keySet()) {
    output.append(coordinates + " is at:\n");
    for (String dependencyPath : dependencyPaths.get(coordinates)) {
      output.append("  " + dependencyPath + "\n");
    }
  }

  return output.toString();
}
 
Example 9
Source File: WordBreakCompoundRewriter.java    From querqy with Apache License 2.0 5 votes vote down vote up
protected void compound(final Term term) {

        if (!previousTerms.isEmpty()) {
            boolean reverseCompound = false;

            // calculate the compounds based on term and the previous term,
            // also possibly including its predecessor if the term before was a "compound reversal" trigger
            final Iterator<Term> previousTermsIterator = new TermsFromFieldIterator(previousTerms.descendingIterator(),
                    term.getField());

            Term previousTerm = null;
            while (previousTermsIterator.hasNext() && previousTerm == null) {
                final Term maybePreviousTerm = previousTermsIterator.next();
                if (isReverseCompoundTriggerWord(maybePreviousTerm)) {
                    reverseCompound = true;
                } else {
                    previousTerm = maybePreviousTerm;
                }
            }

            if (previousTerm != null) {
                final ArrayDeque<Term> compoundTerms = new ArrayDeque<>(2);
                compoundTerms.add(previousTerm);
                compoundTerms.add(term);

                try {
                    addCompounds(compoundTerms, false);
                    if (reverseCompound || alwaysAddReverseCompounds) {
                        addCompounds(compoundTerms, true);
                    }
                } catch (final IOException e) {
                    throw new RuntimeException("Error while compounding " + term, e);
                }
            }

        }
    }
 
Example 10
Source File: BoundarySkewedDistribution.java    From QuickTheories with Apache License 2.0 5 votes vote down vote up
private ArrayDeque<long[]> findBoundaries(Strategy config, Gen<T> gen) {
  ArrayDeque<long[]> ordered = new ArrayDeque<>(); 
  PrecursorDataPair<T> startPoint = generate(gen, config, new long[0]);  
  ordered.add(startPoint.precursor().shrinkTarget());
  ordered.add(startPoint.precursor().minLimit());
  ordered.add(startPoint.precursor().maxLimit());   
  return ordered;
}
 
Example 11
Source File: Solution8.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 5 votes vote down vote up
public int[] maxSlidingWindow(int[] nums, int k) {
    int len = nums.length;
    // 特判
    if (len == 0) {
        return new int[]{};
    }
    // 结果集
    List<Integer> res = new ArrayList<>();
    // 滑动窗口,注意:保存的是索引值
    ArrayDeque<Integer> deque = new ArrayDeque<>(k);

    for (int i = 0; i < len; i++) {
        // 当元素从左边界滑出的时候,如果它恰恰好是滑动窗口的最大值
        // 那么将它弹出
        if (i >= k && i - k == deque.getFirst()) {
            deque.pollFirst();
        }

        // 如果滑动窗口非空,新进来的数比队列里已经存在的数还要大
        // 则说明已经存在数一定不会是滑动窗口的最大值(它们毫无出头之日)
        // 将它们弹出
        while (!deque.isEmpty() && nums[deque.peekLast()] <= nums[i]) {
            deque.pollLast();
        }
        deque.add(i);
        // 队首一定是滑动窗口的最大值的索引
        if (i >= k - 1) {
            res.add(nums[deque.peekFirst()]);
        }
    }

    int size = res.size();
    int[] result = new int[size];

    for (int i = 0; i < size; i++) {
        result[i] = res.get(i);
    }
    return result;
}
 
Example 12
Source File: ArrayDequeTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * isEmpty is true before add, false after
 */
public void testEmpty() {
    ArrayDeque q = new ArrayDeque();
    assertTrue(q.isEmpty());
    q.add(new Integer(1));
    assertFalse(q.isEmpty());
    q.add(new Integer(2));
    q.removeFirst();
    q.removeFirst();
    assertTrue(q.isEmpty());
}
 
Example 13
Source File: Interpreter.java    From Quicksql with MIT License 4 votes vote down vote up
public void send(Row row) throws InterruptedException {
  for (ArrayDeque<Row> queue : queues) {
    queue.add(row);
  }
}
 
Example 14
Source File: NinjaActionsHelper.java    From bazel with Apache License 2.0 4 votes vote down vote up
void createNinjaActions() throws GenericParsingException {
  // Traverse the action graph starting from the targets, specified by the user.
  // Only create the required actions.
  Set<PathFragment> visitedPaths = Sets.newHashSet();
  Set<NinjaTarget> visitedTargets = Sets.newHashSet();
  visitedPaths.addAll(pathsToBuild);
  ArrayDeque<PathFragment> queue = new ArrayDeque<>(pathsToBuild);
  Consumer<Collection<PathFragment>> enqueuer =
      paths -> {
        for (PathFragment input : paths) {
          if (visitedPaths.add(input)) {
            queue.add(input);
          }
        }
      };
  while (!queue.isEmpty()) {
    PathFragment fragment = queue.remove();
    NinjaTarget target = targetsMap.get(fragment);
    if (target != null) {
      // If the output is already created by a symlink action created from specifying that
      // file in output_root_inputs attribute of the ninja_graph rule, do not create other
      // actions that output that same file, since that will result in an action conflict.
      if (!outputRootInputsSymlinks.contains(fragment)) {
        if (visitedTargets.add(target)) {
          createNinjaAction(target);
        }
        enqueuer.accept(target.getAllInputs());
      } else {
        // Sanity check that the Ninja action we're skipping (because its outputs are already
        // being symlinked using output_root_inputs) has only symlink outputs specified in
        // output_root_inputs. Otherwise we might skip some other outputs.
        List<PathFragment> outputsInOutputRootInputsSymlinks = new ArrayList<>();
        List<PathFragment> outputsNotInOutputRootInputsSymlinks = new ArrayList<>();
        for (PathFragment output : target.getAllOutputs()) {
          if (outputRootInputsSymlinks.contains(output)) {
            outputsInOutputRootInputsSymlinks.add(output);
          } else {
            outputsNotInOutputRootInputsSymlinks.add(output);
          }
        }
        if (!outputsNotInOutputRootInputsSymlinks.isEmpty()) {
          throw new GenericParsingException(
              "Ninja target "
                  + target.getRuleName()
                  + " has "
                  + "outputs in output_root_inputs and other outputs not in output_root_inputs:\n"
                  + "Outputs in output_root_inputs:\n  "
                  + Joiner.on("  \n").join(outputsInOutputRootInputsSymlinks)
                  + "\nOutputs not in output_root_inputs:\n  "
                  + Joiner.on("  \n").join(outputsNotInOutputRootInputsSymlinks));
        }
      }
    } else {
      PhonyTarget phonyTarget = phonyTargets.get(fragment);
      // Phony target can be null, if the path in neither regular or phony target,
      // but the source file.
      if (phonyTarget != null) {
        phonyTarget.visitExplicitInputs(phonyTargets, enqueuer::accept);
      }
    }
  }
}
 
Example 15
Source File: QueryParameterAttribute.java    From quarkus with Apache License 2.0 4 votes vote down vote up
@Override
public void writeAttribute(final RoutingContext exchange, final String newValue) throws ReadOnlyAttributeException {
    final ArrayDeque<String> value = new ArrayDeque<>();
    value.add(newValue);
    exchange.queryParams().set(parameter, value);
}
 
Example 16
Source File: MultipleInputStreamTaskTest.java    From flink with Apache License 2.0 4 votes vote down vote up
/**
 * This test verifies that checkpoint barriers and barrier buffers work correctly with
 * concurrent checkpoint barriers where one checkpoint is "overtaking" another checkpoint, i.e.
 * some inputs receive barriers from an earlier checkpoint, thereby blocking,
 * then all inputs receive barriers from a later checkpoint.
 */
@Test
public void testOvertakingCheckpointBarriers() throws Exception {
	try (StreamTaskMailboxTestHarness<String> testHarness =
		new MultipleInputStreamTaskTestHarnessBuilder<>(MultipleInputStreamTask::new, BasicTypeInfo.STRING_TYPE_INFO)
			.addInput(BasicTypeInfo.STRING_TYPE_INFO, 2)
			.addInput(BasicTypeInfo.INT_TYPE_INFO, 2)
			.addInput(BasicTypeInfo.DOUBLE_TYPE_INFO, 2)
			.setupOutputForSingletonOperatorChain(new MapToStringMultipleInputOperatorFactory())
			.build()) {
		ArrayDeque<Object> expectedOutput = new ArrayDeque<>();
		long initialTime = 0L;

		testHarness.processEvent(new CheckpointBarrier(0, 0, CheckpointOptions.forCheckpointWithDefaultLocation()), 0, 0);

		// These elements should be forwarded, since we did not yet receive a checkpoint barrier
		// on that input, only add to same input, otherwise we would not know the ordering
		// of the output since the Task might read the inputs in any order
		testHarness.processElement(new StreamRecord<>("Witam-0-1", initialTime), 0, 1);
		testHarness.processElement(new StreamRecord<>(42, initialTime), 1, 1);
		testHarness.processElement(new StreamRecord<>(1.0d, initialTime), 2, 1);
		expectedOutput.add(new StreamRecord<>("Witam-0-1", initialTime));
		expectedOutput.add(new StreamRecord<>("42", initialTime));
		expectedOutput.add(new StreamRecord<>("1.0", initialTime));

		// we should not yet see the barrier, only the two elements from non-blocked input

		assertThat(testHarness.getOutput(), contains(expectedOutput.toArray()));

		// Now give a later barrier to all inputs, this should unblock the first channel
		testHarness.processEvent(new CheckpointBarrier(1, 1, CheckpointOptions.forCheckpointWithDefaultLocation()), 0, 1);
		testHarness.processEvent(new CheckpointBarrier(1, 1, CheckpointOptions.forCheckpointWithDefaultLocation()), 1, 0);
		testHarness.processEvent(new CheckpointBarrier(1, 1, CheckpointOptions.forCheckpointWithDefaultLocation()), 1, 1);
		testHarness.processEvent(new CheckpointBarrier(1, 1, CheckpointOptions.forCheckpointWithDefaultLocation()), 2, 0);
		testHarness.processEvent(new CheckpointBarrier(1, 1, CheckpointOptions.forCheckpointWithDefaultLocation()), 2, 1);
		testHarness.processEvent(new CheckpointBarrier(1, 1, CheckpointOptions.forCheckpointWithDefaultLocation()), 0, 0);

		expectedOutput.add(new CancelCheckpointMarker(0));
		expectedOutput.add(new CheckpointBarrier(1, 1, CheckpointOptions.forCheckpointWithDefaultLocation()));

		assertThat(testHarness.getOutput(), contains(expectedOutput.toArray()));

		// Then give the earlier barrier, these should be ignored
		testHarness.processEvent(new CheckpointBarrier(0, 0, CheckpointOptions.forCheckpointWithDefaultLocation()), 0, 1);
		testHarness.processEvent(new CheckpointBarrier(0, 0, CheckpointOptions.forCheckpointWithDefaultLocation()), 1, 0);
		testHarness.processEvent(new CheckpointBarrier(0, 0, CheckpointOptions.forCheckpointWithDefaultLocation()), 1, 1);
		testHarness.processEvent(new CheckpointBarrier(0, 0, CheckpointOptions.forCheckpointWithDefaultLocation()), 2, 0);
		testHarness.processEvent(new CheckpointBarrier(0, 0, CheckpointOptions.forCheckpointWithDefaultLocation()), 2, 1);

		testHarness.waitForTaskCompletion();
		assertThat(testHarness.getOutput(), contains(expectedOutput.toArray()));
	}
}
 
Example 17
Source File: RecordWriterTest.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
/**
 * The results of emitting records via BroadcastPartitioner or broadcasting records directly are the same,
 * that is all the target channels can receive the whole outputs.
 *
 * @param isBroadcastEmit whether using {@link RecordWriter#broadcastEmit(IOReadableWritable)} or not
 */
private void emitRecordWithBroadcastPartitionerOrBroadcastEmitRecord(boolean isBroadcastEmit) throws Exception {
	final int numberOfChannels = 4;
	final int bufferSize = 32;
	final int numValues = 8;
	final int serializationLength = 4;

	@SuppressWarnings("unchecked")
	final Queue<BufferConsumer>[] queues = new Queue[numberOfChannels];
	for (int i = 0; i < numberOfChannels; i++) {
		queues[i] = new ArrayDeque<>();
	}

	final TestPooledBufferProvider bufferProvider = new TestPooledBufferProvider(Integer.MAX_VALUE, bufferSize);
	final ResultPartitionWriter partitionWriter = new CollectingPartitionWriter(queues, bufferProvider);
	final ChannelSelector selector = new OutputEmitter(ShipStrategyType.BROADCAST, 0);
	final RecordWriter<SerializationTestType> writer = RecordWriter.createRecordWriter(partitionWriter, selector, 0, "test");
	final RecordDeserializer<SerializationTestType> deserializer = new SpillingAdaptiveSpanningRecordDeserializer<>(
		new String[]{ tempFolder.getRoot().getAbsolutePath() });

	final ArrayDeque<SerializationTestType> serializedRecords = new ArrayDeque<>();
	final Iterable<SerializationTestType> records = Util.randomRecords(numValues, SerializationTestTypeFactory.INT);
	for (SerializationTestType record : records) {
		serializedRecords.add(record);

		if (isBroadcastEmit) {
			writer.broadcastEmit(record);
		} else {
			writer.emit(record);
		}
	}

	final int requiredBuffers = numValues / (bufferSize / (4 + serializationLength));
	for (int i = 0; i < numberOfChannels; i++) {
		assertEquals(requiredBuffers, queues[i].size());

		final ArrayDeque<SerializationTestType> expectedRecords = serializedRecords.clone();
		int assertRecords = 0;
		for (int j = 0; j < requiredBuffers; j++) {
			Buffer buffer = buildSingleBuffer(queues[i].remove());
			deserializer.setNextBuffer(buffer);

			assertRecords += DeserializationUtils.deserializeRecords(expectedRecords, deserializer);
		}
		Assert.assertEquals(numValues, assertRecords);
	}
}
 
Example 18
Source File: DefaultFormFactory.java    From crnk-framework with Apache License 2.0 4 votes vote down vote up
private void buildElement(PresentationEnvironment env, FormElements elements, ArrayDeque<MetaAttribute> attributePath) {
	MetaAttribute lastAttribute = attributePath.getLast();
	MetaType type = lastAttribute.getType();
	if (isIgnored(attributePath, env)) {
		return;
	}

	String label = PresentationBuilderUtils.getLabel(attributePath);

	if (type instanceof MetaDataObject && !lastAttribute.isAssociation()) {
		for (MetaAttribute nestedAttribute : type.asDataObject().getAttributes()) {
			if (!attributePath.contains(nestedAttribute)) {
				ArrayDeque nestedPath = new ArrayDeque();
				nestedPath.addAll(attributePath);
				nestedPath.add(nestedAttribute);
				buildElement(env, elements, nestedPath);
			}
		}
	} else {
		PresentationEnvironment elementEnv = env.clone();
		elementEnv.setAttributePath(attributePath);
		elementEnv.setAcceptedTypes(Arrays.asList(PresentationType.FORM_ELEMENT, PresentationType.DISPLAY));
		elementEnv.setType(type);
		PresentationElement element = env.createElement(elementEnv);

		PathSpec pathSpec = PathSpec.of(attributePath.stream().map(it -> it.getName()).collect(Collectors.toList()));

		//String valuePath =  PresentationBuilderUtils.getValuePath(attributePath);
		String id = pathSpec.toString(); //valuePath.join(valuePath, '.');

		FormElement formElement = new FormElement();
		formElement.setId(id);
		formElement.setComponentId("form");
		formElement.setLabel(label);
		formElement.setAttributePath(pathSpec);
		formElement.setEditable(env.isEditable());
		formElement.setComponent(element);
		//column.setEditComponent();
		// column.setFilter
		// column.setWidth
		// column.setTyleClass
		elements.add(formElement);
	}
}
 
Example 19
Source File: SpanningRecordSerializationTest.java    From flink with Apache License 2.0 4 votes vote down vote up
/**
 * Iterates over the provided records and tests whether {@link SpanningRecordSerializer} and {@link RecordDeserializer}
 * interact as expected.
 *
 * <p>Only a single {@link MemorySegment} will be allocated.
 *
 * @param records records to test
 * @param segmentSize size for the {@link MemorySegment}
 */
private static void testSerializationRoundTrip(
		Iterable<SerializationTestType> records,
		int segmentSize,
		RecordSerializer<SerializationTestType> serializer,
		RecordDeserializer<SerializationTestType> deserializer)
	throws Exception {
	final ArrayDeque<SerializationTestType> serializedRecords = new ArrayDeque<>();

	// -------------------------------------------------------------------------------------------------------------

	BufferAndSerializerResult serializationResult = setNextBufferForSerializer(serializer, segmentSize);

	int numRecords = 0;
	for (SerializationTestType record : records) {

		serializedRecords.add(record);

		numRecords++;

		// serialize record
		serializer.serializeRecord(record);
		if (serializer.copyToBufferBuilder(serializationResult.getBufferBuilder()).isFullBuffer()) {
			// buffer is full => start deserializing
			deserializer.setNextBuffer(serializationResult.buildBuffer());

			numRecords -= DeserializationUtils.deserializeRecords(serializedRecords, deserializer);

			// move buffers as long as necessary (for long records)
			while ((serializationResult = setNextBufferForSerializer(serializer, segmentSize)).isFullBuffer()) {
				deserializer.setNextBuffer(serializationResult.buildBuffer());
			}
		}
	}

	// deserialize left over records
	deserializer.setNextBuffer(serializationResult.buildBuffer());

	while (!serializedRecords.isEmpty()) {
		SerializationTestType expected = serializedRecords.poll();

		SerializationTestType actual = expected.getClass().newInstance();
		RecordDeserializer.DeserializationResult result = deserializer.getNextRecord(actual);

		Assert.assertTrue(result.isFullRecord());
		Assert.assertEquals(expected, actual);
		numRecords--;
	}

	// assert that all records have been serialized and deserialized
	Assert.assertEquals(0, numRecords);
	Assert.assertFalse(serializer.hasSerializedData());
	Assert.assertFalse(deserializer.hasUnfinishedData());
}
 
Example 20
Source File: Interpreter.java    From calcite with Apache License 2.0 4 votes vote down vote up
public void send(Row row) throws InterruptedException {
  for (ArrayDeque<Row> queue : queues) {
    queue.add(row);
  }
}