Search in sources :

Example 6 with Arrays

use of java.util.Arrays in project pravega by pravega.

the class RevisionDataStreamCommonTests method testGenericArrays.

/**
 * Tests the ability to encode and decode a generic array.
 */
@Test
public void testGenericArrays() throws Exception {
    val numbers = getAllOneBitNumbers(Long.SIZE);
    val toTest = Arrays.<Long[]>asList(null, new Long[0], numbers.toArray(new Long[numbers.size()]));
    for (Long[] value : toTest) {
        testEncodeDecode((os, v) -> os.writeArray(v, RevisionDataOutput::writeLong), is -> is.readArray(DataInput::readLong, Long[]::new), (s, v) -> s.getCollectionLength(v, e -> Long.BYTES), value, (s, t) -> Arrays.equals(s == null ? new Long[0] : s, t));
    }
}
Also used : lombok.val(lombok.val) Arrays(java.util.Arrays) EnhancedByteArrayOutputStream(io.pravega.common.io.EnhancedByteArrayOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ImmutableMap(com.google.common.collect.ImmutableMap) AssertExtensions(io.pravega.test.common.AssertExtensions) Collection(java.util.Collection) BiFunction(java.util.function.BiFunction) lombok.val(lombok.val) Cleanup(lombok.Cleanup) Test(org.junit.Test) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) BiPredicate(java.util.function.BiPredicate) Map(java.util.Map) DataInput(java.io.DataInput) Assert(org.junit.Assert) Collections(java.util.Collections) Test(org.junit.Test)

Example 7 with Arrays

use of java.util.Arrays in project pravega by pravega.

the class RevisionDataOutputStreamTests method testImpl.

private void testImpl(RevisionDataOutputStream impl, Supplier<ByteArraySegment> getWrittenData) throws Exception {
    final byte b = 123;
    final short sn = 1234;
    final int n = 123456;
    final long l = (long) Integer.MAX_VALUE + 1;
    final String s = getUTFString();
    final byte[] array = s.getBytes();
    int expectedLength = Byte.BYTES + Short.BYTES + Integer.BYTES + Long.BYTES + impl.getUTFLength(s) + array.length;
    if (impl.requiresExplicitLength()) {
        // Verify a few methods that shouldn't be allowed to run without setting length beforehand.
        Arrays.<AssertExtensions.RunnableWithException>asList(() -> impl.write(1), () -> impl.write(new byte[1], 0, 1), () -> impl.writeInt(1), () -> impl.writeShort(1), () -> impl.writeLong(1), () -> impl.writeUTF("test")).forEach(r -> AssertExtensions.assertThrows("write was allowed without setting length first.", r, ex -> ex instanceof IllegalStateException));
    }
    impl.length(expectedLength);
    impl.writeByte(b);
    impl.writeShort(sn);
    impl.writeInt(n);
    impl.writeLong(l);
    impl.writeUTF(s);
    impl.write(array);
    // Need to close so we flush any remaining stuff to the underlying stream.
    impl.close();
    // Verify the written data can be read back.
    @Cleanup val inputStream = RevisionDataInputStream.wrap(getWrittenData.get().getReader());
    Assert.assertEquals("Unexpected length read back.", expectedLength, inputStream.getLength());
    Assert.assertEquals("Unexpected byte read back.", b, inputStream.read());
    Assert.assertEquals("Unexpected short read back.", sn, inputStream.readShort());
    Assert.assertEquals("Unexpected int read back.", n, inputStream.readInt());
    Assert.assertEquals("Unexpected long read back.", l, inputStream.readLong());
    Assert.assertEquals("Unexpected string read back.", s, inputStream.readUTF());
    byte[] readArray = new byte[array.length];
    int readBytes = inputStream.read(readArray);
    Assert.assertEquals("Unexpected number of bytes read for array.", readArray.length, readBytes);
    Assert.assertArrayEquals("Unexpected array read back.", array, readArray);
    Assert.assertEquals("Not expecting any more data. ", -1, inputStream.read());
    AssertExtensions.assertThrows("Expecting EOF.", () -> inputStream.readFully(new byte[1]), ex -> ex instanceof EOFException);
}
Also used : OutputStream(java.io.OutputStream) Arrays(java.util.Arrays) EnhancedByteArrayOutputStream(io.pravega.common.io.EnhancedByteArrayOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) AssertExtensions(io.pravega.test.common.AssertExtensions) FixedByteArrayOutputStream(io.pravega.common.io.FixedByteArrayOutputStream) lombok.val(lombok.val) Cleanup(lombok.Cleanup) Test(org.junit.Test) EOFException(java.io.EOFException) Function(java.util.function.Function) Supplier(java.util.function.Supplier) ByteArraySegment(io.pravega.common.util.ByteArraySegment) ByteArrayInputStream(java.io.ByteArrayInputStream) SerializationException(io.pravega.common.io.SerializationException) Assert(org.junit.Assert) lombok.val(lombok.val) AssertExtensions(io.pravega.test.common.AssertExtensions) EOFException(java.io.EOFException) Cleanup(lombok.Cleanup)

Example 8 with Arrays

use of java.util.Arrays in project graal by oracle.

the class IntegerSwitchNode method doReplace.

private void doReplace(ValueNode newValue, List<KeyData> newKeyDatas, ArrayList<AbstractBeginNode> newSuccessors, int newDefaultSuccessor, double newDefaultProbability) {
    /* Sort the new keys (invariant of the IntegerSwitchNode). */
    newKeyDatas.sort(Comparator.comparingInt(k -> k.key));
    /* Create the final data arrays. */
    int newKeyCount = newKeyDatas.size();
    int[] newKeys = new int[newKeyCount];
    double[] newKeyProbabilities = new double[newKeyCount + 1];
    int[] newKeySuccessors = new int[newKeyCount + 1];
    for (int i = 0; i < newKeyCount; i++) {
        KeyData keyData = newKeyDatas.get(i);
        newKeys[i] = keyData.key;
        newKeyProbabilities[i] = keyData.keyProbability;
        newKeySuccessors[i] = keyData.keySuccessor;
    }
    newKeySuccessors[newKeyCount] = newDefaultSuccessor;
    newKeyProbabilities[newKeyCount] = newDefaultProbability;
    /* Normalize new probabilities so that they sum up to 1. */
    double totalProbability = 0;
    for (double probability : newKeyProbabilities) {
        totalProbability += probability;
    }
    if (totalProbability > 0) {
        for (int i = 0; i < newKeyProbabilities.length; i++) {
            newKeyProbabilities[i] /= totalProbability;
        }
    } else {
        for (int i = 0; i < newKeyProbabilities.length; i++) {
            newKeyProbabilities[i] = 1.0 / newKeyProbabilities.length;
        }
    }
    /*
         * Collect dead successors. Successors have to be cleaned before adding the new node to the
         * graph.
         */
    List<AbstractBeginNode> deadSuccessors = successors.filter(s -> !newSuccessors.contains(s)).snapshot();
    successors.clear();
    /*
         * Create the new switch node. This is done before removing dead successors as `killCFG`
         * could edit some of the inputs (e.g., if `newValue` is a loop-phi of the loop that dies
         * while removing successors).
         */
    AbstractBeginNode[] successorsArray = newSuccessors.toArray(new AbstractBeginNode[newSuccessors.size()]);
    SwitchNode newSwitch = graph().add(new IntegerSwitchNode(newValue, successorsArray, newKeys, newKeyProbabilities, newKeySuccessors));
    /* Remove dead successors. */
    for (AbstractBeginNode successor : deadSuccessors) {
        GraphUtil.killCFG(successor);
    }
    /* Replace ourselves with the new switch */
    ((FixedWithNextNode) predecessor()).setNext(newSwitch);
    GraphUtil.killWithUnusedFloatingInputs(this);
}
Also used : DeoptimizationReason(jdk.vm.ci.meta.DeoptimizationReason) Arrays(java.util.Arrays) ConstantNode(org.graalvm.compiler.nodes.ConstantNode) DeoptimizationAction(jdk.vm.ci.meta.DeoptimizationAction) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) NodeLIRBuilderTool(org.graalvm.compiler.nodes.spi.NodeLIRBuilderTool) SimplifierTool(org.graalvm.compiler.graph.spi.SimplifierTool) IntegerStamp(org.graalvm.compiler.core.common.type.IntegerStamp) StampFactory(org.graalvm.compiler.core.common.type.StampFactory) JavaKind(jdk.vm.ci.meta.JavaKind) NodeClass(org.graalvm.compiler.graph.NodeClass) Map(java.util.Map) LoadIndexedNode(org.graalvm.compiler.nodes.java.LoadIndexedNode) IntegerBelowNode(org.graalvm.compiler.nodes.calc.IntegerBelowNode) NodeInfo(org.graalvm.compiler.nodeinfo.NodeInfo) GraphUtil(org.graalvm.compiler.nodes.util.GraphUtil) NodeView(org.graalvm.compiler.nodes.NodeView) AbstractBeginNode(org.graalvm.compiler.nodes.AbstractBeginNode) FixedGuardNode(org.graalvm.compiler.nodes.FixedGuardNode) PrimitiveStamp(org.graalvm.compiler.core.common.type.PrimitiveStamp) Stamp(org.graalvm.compiler.core.common.type.Stamp) LIRLowerable(org.graalvm.compiler.nodes.spi.LIRLowerable) JavaConstant(jdk.vm.ci.meta.JavaConstant) LogicNode(org.graalvm.compiler.nodes.LogicNode) ValueNode(org.graalvm.compiler.nodes.ValueNode) List(java.util.List) ConstantFieldProvider(org.graalvm.compiler.core.common.spi.ConstantFieldProvider) Simplifiable(org.graalvm.compiler.graph.spi.Simplifiable) Comparator(java.util.Comparator) FixedWithNextNode(org.graalvm.compiler.nodes.FixedWithNextNode) FixedWithNextNode(org.graalvm.compiler.nodes.FixedWithNextNode) AbstractBeginNode(org.graalvm.compiler.nodes.AbstractBeginNode)

Example 9 with Arrays

use of java.util.Arrays in project arctic-sea by 52North.

the class AbstractCapabilitiesBaseTypeDecoder method parseServiceIdentification.

private OwsServiceIdentification parseServiceIdentification(ServiceIdentification serviceIdentification) {
    if (serviceIdentification == null) {
        return null;
    }
    OwsCode serviceType = parseCode(serviceIdentification.getServiceType());
    Set<String> serviceTypeVersion = Optional.ofNullable(serviceIdentification.getServiceTypeVersionArray()).map(Arrays::stream).orElseGet(Stream::empty).collect(toSet());
    Set<String> fees = Optional.ofNullable(serviceIdentification.getFees()).map(Collections::singleton).orElseGet(Collections::emptySet);
    Set<URI> profiles = Optional.ofNullable(serviceIdentification.getProfileArray()).map(Arrays::stream).orElseGet(Stream::empty).map(URI::create).collect(toSet());
    Set<String> accessConstraints = Optional.ofNullable(serviceIdentification.getAccessConstraintsArray()).map(Arrays::stream).orElseGet(Stream::empty).collect(toSet());
    MultilingualString title = new MultilingualString();
    MultilingualString abstrakt = new MultilingualString();
    Optional.ofNullable(serviceIdentification.getTitleArray()).map(Arrays::stream).orElseGet(Stream::empty).map(this::parseLanguageString).forEach(title::addLocalization);
    Optional.ofNullable(serviceIdentification.getAbstractArray()).map(Arrays::stream).orElseGet(Stream::empty).map(this::parseLanguageString).forEach(abstrakt::addLocalization);
    Set<OwsKeyword> keywords = Optional.ofNullable(serviceIdentification.getKeywordsArray()).map(Arrays::stream).orElseGet(Stream::empty).flatMap(this::parseKeyword).filter(Objects::nonNull).collect(toSet());
    return new OwsServiceIdentification(serviceType, serviceTypeVersion, profiles, fees, accessConstraints, title, abstrakt, keywords);
}
Also used : OwsCode(org.n52.shetland.ogc.ows.OwsCode) LocalizedString(org.n52.janmayen.i18n.LocalizedString) MultilingualString(org.n52.janmayen.i18n.MultilingualString) OwsLanguageString(org.n52.shetland.ogc.ows.OwsLanguageString) OwsServiceIdentification(org.n52.shetland.ogc.ows.OwsServiceIdentification) URI(java.net.URI) OwsKeyword(org.n52.shetland.ogc.ows.OwsKeyword) Stream(java.util.stream.Stream) MultilingualString(org.n52.janmayen.i18n.MultilingualString) Arrays(java.util.Arrays) Collections(java.util.Collections)

Example 10 with Arrays

use of java.util.Arrays in project arctic-sea by 52North.

the class AbstractCapabilitiesBaseTypeDecoder method parseAddress.

private OwsAddress parseAddress(AddressType address) {
    if (address == null) {
        return null;
    }
    List<String> deliveryPoint = Optional.ofNullable(address.getDeliveryPointArray()).map(Arrays::stream).orElseGet(Stream::empty).map(Strings::emptyToNull).filter(Objects::nonNull).collect(toList());
    List<String> electronicMailAddress = Optional.ofNullable(address.getElectronicMailAddressArray()).map(Arrays::stream).orElseGet(Stream::empty).map(Strings::emptyToNull).filter(Objects::nonNull).collect(toList());
    String city = address.getCity();
    String administrativeArea = address.getAdministrativeArea();
    String postalCode = address.getPostalCode();
    String country = address.getCountry();
    return new OwsAddress(deliveryPoint, city, administrativeArea, postalCode, country, electronicMailAddress);
}
Also used : OwsAddress(org.n52.shetland.ogc.ows.OwsAddress) LocalizedString(org.n52.janmayen.i18n.LocalizedString) MultilingualString(org.n52.janmayen.i18n.MultilingualString) OwsLanguageString(org.n52.shetland.ogc.ows.OwsLanguageString) Arrays(java.util.Arrays) Strings(com.google.common.base.Strings)

Aggregations

Arrays (java.util.Arrays)69 List (java.util.List)45 ArrayList (java.util.ArrayList)39 Map (java.util.Map)31 Test (org.junit.Test)23 Collections (java.util.Collections)21 HashMap (java.util.HashMap)18 Collectors (java.util.stream.Collectors)14 Set (java.util.Set)12 Function (java.util.function.Function)12 Stream (java.util.stream.Stream)12 IOException (java.io.IOException)11 TimeUnit (java.util.concurrent.TimeUnit)11 Optional (java.util.Optional)9 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)9 AtomicReference (java.util.concurrent.atomic.AtomicReference)9 Logger (org.slf4j.Logger)9 LoggerFactory (org.slf4j.LoggerFactory)9 HashSet (java.util.HashSet)7 ByteArrayOutputStream (java.io.ByteArrayOutputStream)6