Search in sources :

Example 31 with BiConsumer

use of java.util.function.BiConsumer in project spring-cloud-gcp by spring-cloud.

the class MappingSpannerWriteConverter method attemptSetIterableValue.

private boolean attemptSetIterableValue(Iterable value, ValueBinder<WriteBuilder> valueBinder, SpannerPersistentProperty spannerPersistentProperty) {
    Class innerType = ConversionUtils.boxIfNeeded(spannerPersistentProperty.getColumnInnerType());
    if (innerType == null || !iterablePropertyType2ToMethodMap.containsKey(innerType)) {
        return false;
    }
    BiConsumer toMethod = iterablePropertyType2ToMethodMap.get(innerType);
    toMethod.accept(valueBinder, value);
    return true;
}
Also used : BiConsumer(java.util.function.BiConsumer)

Example 32 with BiConsumer

use of java.util.function.BiConsumer in project reactor-core by reactor.

the class MonoStreamCollectorTest method scanStreamCollectorSubscriber.

@Test
public void scanStreamCollectorSubscriber() {
    CoreSubscriber<List<String>> actual = new LambdaMonoSubscriber<>(null, e -> {
    }, null, null);
    Collector<String, ?, List<String>> collector = Collectors.toList();
    @SuppressWarnings("unchecked") BiConsumer<Integer, String> accumulator = (BiConsumer<Integer, String>) collector.accumulator();
    @SuppressWarnings("unchecked") Function<Integer, List<String>> finisher = (Function<Integer, List<String>>) collector.finisher();
    MonoStreamCollector.StreamCollectorSubscriber<String, Integer, List<String>> test = new MonoStreamCollector.StreamCollectorSubscriber<>(actual, 1, accumulator, finisher);
    Subscription parent = Operators.emptySubscription();
    test.onSubscribe(parent);
    assertThat(test.scan(Scannable.Attr.PREFETCH)).isEqualTo(Integer.MAX_VALUE);
    assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(parent);
    assertThat(test.scan(Scannable.Attr.ACTUAL)).isSameAs(actual);
    assertThat(test.scan(Scannable.Attr.TERMINATED)).isFalse();
    test.onError(new IllegalStateException("boom"));
    assertThat(test.scan(Scannable.Attr.TERMINATED)).isTrue();
    assertThat(test.scan(Scannable.Attr.CANCELLED)).isFalse();
    test.cancel();
    assertThat(test.scan(Scannable.Attr.CANCELLED)).isTrue();
}
Also used : Function(java.util.function.Function) List(java.util.List) Subscription(org.reactivestreams.Subscription) BiConsumer(java.util.function.BiConsumer) Test(org.junit.Test)

Example 33 with BiConsumer

use of java.util.function.BiConsumer in project keycloak by keycloak.

the class DefaultTokenManager method decodeClientJWT.

@Override
public <T> T decodeClientJWT(String jwt, ClientModel client, BiConsumer<JOSE, ClientModel> jwtValidator, Class<T> clazz) {
    if (jwt == null) {
        return null;
    }
    JOSE joseToken = JOSEParser.parse(jwt);
    jwtValidator.accept(joseToken, client);
    if (joseToken instanceof JWE) {
        try {
            Optional<KeyWrapper> activeKey;
            String kid = joseToken.getHeader().getKeyId();
            Stream<KeyWrapper> keys = session.keys().getKeysStream(session.getContext().getRealm());
            if (kid == null) {
                activeKey = keys.filter(k -> KeyUse.ENC.equals(k.getUse()) && k.getPublicKey() != null).sorted(Comparator.comparingLong(KeyWrapper::getProviderPriority).reversed()).findFirst();
            } else {
                activeKey = keys.filter(k -> KeyUse.ENC.equals(k.getUse()) && k.getKid().equals(kid)).findAny();
            }
            JWE jwe = JWE.class.cast(joseToken);
            Key privateKey = activeKey.map(KeyWrapper::getPrivateKey).orElseThrow(() -> new RuntimeException("Could not find private key for decrypting token"));
            jwe.getKeyStorage().setDecryptionKey(privateKey);
            byte[] content = jwe.verifyAndDecodeJwe().getContent();
            try {
                JOSE jws = JOSEParser.parse(new String(content));
                if (jws instanceof JWSInput) {
                    jwtValidator.accept(jws, client);
                    return verifyJWS(client, clazz, (JWSInput) jws);
                }
            } catch (Exception ignore) {
            // try to decrypt content as is
            }
            return JsonSerialization.readValue(content, clazz);
        } catch (IOException cause) {
            throw new RuntimeException("Failed to deserialize JWT", cause);
        } catch (JWEException cause) {
            throw new RuntimeException("Failed to decrypt JWT", cause);
        }
    }
    return verifyJWS(client, clazz, (JWSInput) joseToken);
}
Also used : KeyWrapper(org.keycloak.crypto.KeyWrapper) ClientModel(org.keycloak.models.ClientModel) KeycloakModelUtils(org.keycloak.models.utils.KeycloakModelUtils) LogoutToken(org.keycloak.representations.LogoutToken) Logger(org.jboss.logging.Logger) SignatureSignerContext(org.keycloak.crypto.SignatureSignerContext) Constants(org.keycloak.models.Constants) Algorithm(org.keycloak.crypto.Algorithm) JWEEncryptionProvider(org.keycloak.jose.jwe.enc.JWEEncryptionProvider) Function(java.util.function.Function) Supplier(java.util.function.Supplier) Token(org.keycloak.Token) SignatureProvider(org.keycloak.crypto.SignatureProvider) TokenUtil(org.keycloak.util.TokenUtil) UserModel(org.keycloak.models.UserModel) ContentEncryptionProvider(org.keycloak.crypto.ContentEncryptionProvider) JWEAlgorithmProvider(org.keycloak.jose.jwe.alg.JWEAlgorithmProvider) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) OIDCAdvancedConfigWrapper(org.keycloak.protocol.oidc.OIDCAdvancedConfigWrapper) BiConsumer(java.util.function.BiConsumer) TokenManager(org.keycloak.models.TokenManager) JOSEParser(org.keycloak.jose.JOSEParser) RealmModel(org.keycloak.models.RealmModel) JWE(org.keycloak.jose.jwe.JWE) JWK(org.keycloak.jose.jwk.JWK) Predicate(java.util.function.Predicate) JWEException(org.keycloak.jose.jwe.JWEException) PublicKeyStorageManager(org.keycloak.keys.loader.PublicKeyStorageManager) KeycloakSession(org.keycloak.models.KeycloakSession) IOException(java.io.IOException) CekManagementProvider(org.keycloak.crypto.CekManagementProvider) TokenCategory(org.keycloak.TokenCategory) JsonSerialization(org.keycloak.util.JsonSerialization) Key(java.security.Key) OIDCConfigAttributes(org.keycloak.protocol.oidc.OIDCConfigAttributes) Stream(java.util.stream.Stream) KeyUse(org.keycloak.crypto.KeyUse) PrivateKey(java.security.PrivateKey) OIDCLoginProtocol(org.keycloak.protocol.oidc.OIDCLoginProtocol) Optional(java.util.Optional) JOSE(org.keycloak.jose.JOSE) Comparator(java.util.Comparator) ClientSignatureVerifierProvider(org.keycloak.crypto.ClientSignatureVerifierProvider) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JWEException(org.keycloak.jose.jwe.JWEException) IOException(java.io.IOException) JWEException(org.keycloak.jose.jwe.JWEException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) KeyWrapper(org.keycloak.crypto.KeyWrapper) JOSE(org.keycloak.jose.JOSE) JWE(org.keycloak.jose.jwe.JWE) Key(java.security.Key) PrivateKey(java.security.PrivateKey)

Example 34 with BiConsumer

use of java.util.function.BiConsumer in project graal by oracle.

the class MemoryFileSystem method newByteChannel.

@Override
public SeekableByteChannel newByteChannel(Path path, Set<? extends OpenOption> options, FileAttribute<?>... attrs) throws IOException {
    if (options.contains(StandardOpenOption.APPEND) && options.contains(StandardOpenOption.READ)) {
        throw new IllegalArgumentException("READ + APPEND not allowed.");
    }
    if (options.contains(StandardOpenOption.SYNC) || options.contains(StandardOpenOption.DSYNC)) {
        throw new IllegalArgumentException("Not supported yet.");
    }
    final Path absolutePath = toAbsolutePath(path);
    final Path parentPath = absolutePath.getParent();
    if (parentPath == null) {
        throw new IOException(path.toString() + " is a directory.");
    }
    boolean read = options.contains(StandardOpenOption.READ);
    boolean write = options.contains(StandardOpenOption.WRITE);
    boolean append = options.contains(StandardOpenOption.APPEND);
    if (!read && !write) {
        if (append) {
            write = true;
        } else {
            read = true;
        }
    }
    final Map.Entry<Long, Map<String, Long>> e = readDir(parentPath);
    final long parentInode = e.getKey();
    final Map<String, Long> parentDirents = e.getValue();
    final String fileName = absolutePath.getFileName().toString();
    Long inode = parentDirents.get(fileName);
    if (inode == null) {
        if (!options.contains(StandardOpenOption.WRITE) || !(options.contains(StandardOpenOption.CREATE) || options.contains(StandardOpenOption.CREATE_NEW))) {
            throw new NoSuchFileException(path.toString());
        }
        if (!inodes.get(parentInode).permissions.contains(AccessMode.WRITE)) {
            throw new IOException("Read only dir: " + path);
        }
        inode = nextInode++;
        inodes.put(inode, FileInfo.newBuilder(FileType.FILE).permissions(attrs).build());
        blocks.put(inode, EMPTY);
        parentDirents.put(fileName, inode);
        writeDir(parentInode, parentDirents);
    } else {
        if (options.contains(StandardOpenOption.CREATE_NEW)) {
            throw new FileAlreadyExistsException(path.toString());
        }
        final FileInfo fileInfo = inodes.get(inode);
        if (!fileInfo.isFile()) {
            throw new IOException(path.toString() + " is a directory.");
        }
        if (read && !fileInfo.permissions.contains(AccessMode.READ)) {
            throw new IOException("Cannot read: " + path);
        }
        if (write && !fileInfo.permissions.contains(AccessMode.WRITE)) {
            throw new IOException("Read only: " + path);
        }
    }
    final boolean deleteOnClose = options.contains(StandardOpenOption.DELETE_ON_CLOSE);
    final byte[] origData = blocks.get(inode);
    final byte[] data = write && options.contains(StandardOpenOption.TRUNCATE_EXISTING) ? EMPTY : Arrays.copyOf(origData, origData.length);
    final long inodeFin = inode;
    final BiConsumer<byte[], Long> syncAction = new BiConsumer<byte[], Long>() {

        @Override
        public void accept(byte[] t, Long u) {
            blocks.put(inodeFin, Arrays.copyOf(t, (int) u.longValue()));
        }
    };
    final boolean readFin = read;
    final boolean writeFin = write;
    final BiConsumer<byte[], Long> metaSyncAction = new BiConsumer<byte[], Long>() {

        @Override
        public void accept(byte[] t, Long u) {
            final long time = System.currentTimeMillis();
            final FileInfo fileInfo = inodes.get(inodeFin);
            if (readFin) {
                fileInfo.atime = time;
            }
            if (writeFin) {
                fileInfo.mtime = time;
            }
        }
    };
    final BiConsumer<byte[], Long> closeAction = new BiConsumer<byte[], Long>() {

        @Override
        public void accept(byte[] t, Long u) {
            if (deleteOnClose) {
                try {
                    delete(absolutePath);
                } catch (IOException ioe) {
                    sthrow(ioe);
                }
            } else {
                syncAction.accept(t, u);
                metaSyncAction.accept(t, u);
            }
        }

        @SuppressWarnings("unchecked")
        private <E extends Throwable> void sthrow(Throwable t) throws E {
            throw (E) t;
        }
    };
    return new ChannelImpl(data, closeAction, read, write, append);
}
Also used : Path(java.nio.file.Path) FileAlreadyExistsException(java.nio.file.FileAlreadyExistsException) NoSuchFileException(java.nio.file.NoSuchFileException) IOException(java.io.IOException) HashMap(java.util.HashMap) Map(java.util.Map) AbstractMap(java.util.AbstractMap) BiConsumer(java.util.function.BiConsumer)

Example 35 with BiConsumer

use of java.util.function.BiConsumer in project sonar-java by SonarSource.

the class ProgramState method cleanupConstraints.

public ProgramState cleanupConstraints(Collection<SymbolicValue> protectedSymbolicValues) {
    class CleanAction implements BiConsumer<SymbolicValue, ConstraintsByDomain> {

        boolean newProgramState = false;

        PMap<SymbolicValue, ConstraintsByDomain> newConstraints = constraints;

        PMap<SymbolicValue, Integer> newReferences = references;

        @Override
        public void accept(SymbolicValue symbolicValue, ConstraintsByDomain constraintPMap) {
            constraintPMap.forEach((domain, constraint) -> {
                if (!protectedSymbolicValues.contains(symbolicValue) && !isReachable(symbolicValue, newReferences) && isDisposable(symbolicValue, constraint) && !inStack(stack, symbolicValue)) {
                    newProgramState = true;
                    ConstraintsByDomain removed = newConstraints.get(symbolicValue).remove(domain);
                    if (removed.isEmpty()) {
                        newConstraints = newConstraints.remove(symbolicValue);
                    } else {
                        newConstraints = newConstraints.put(symbolicValue, removed);
                    }
                    newReferences = newReferences.remove(symbolicValue);
                }
            });
        }
    }
    CleanAction cleanAction = new CleanAction();
    constraints.forEach(cleanAction);
    return cleanAction.newProgramState ? new ProgramState(values, cleanAction.newReferences, cleanAction.newConstraints, visitedPoints, stack, exitSymbolicValue) : this;
}
Also used : ConstraintsByDomain(org.sonar.java.se.constraint.ConstraintsByDomain) PMap(org.sonar.java.collections.PMap) SymbolicValue(org.sonar.java.se.symbolicvalues.SymbolicValue) BinarySymbolicValue(org.sonar.java.se.symbolicvalues.BinarySymbolicValue) RelationalSymbolicValue(org.sonar.java.se.symbolicvalues.RelationalSymbolicValue) BiConsumer(java.util.function.BiConsumer)

Aggregations

BiConsumer (java.util.function.BiConsumer)264 Test (org.junit.Test)111 List (java.util.List)109 Map (java.util.Map)79 IOException (java.io.IOException)78 ArrayList (java.util.ArrayList)74 Consumer (java.util.function.Consumer)71 HashMap (java.util.HashMap)66 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)54 Collectors (java.util.stream.Collectors)53 CountDownLatch (java.util.concurrent.CountDownLatch)52 Collections (java.util.Collections)46 Set (java.util.Set)46 Collection (java.util.Collection)45 Arrays (java.util.Arrays)44 TimeUnit (java.util.concurrent.TimeUnit)43 Function (java.util.function.Function)43 Assert (org.junit.Assert)43 Optional (java.util.Optional)41 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)35