All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.amazonaws.services.sqs.executors.CompletedFutureSerializer Maven / Gradle / Ivy

Go to download

An Amazon SQS client that supports creating lightweight, automatically-deleted temporary queues, for use in common messaging patterns such as Request/Response. See http://aws.amazon.com/sqs.

The newest version!
package com.amazonaws.services.sqs.executors;

import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class CompletedFutureSerializer implements InvertibleFunction, String> {

    private static final char NORMAL_VALUE_PREFIX = '.';
    private static final char CANCELLED_PREFIX = 'C';
    private static final char EXCEPTION_PREFIX = 'E';
    
    private final InvertibleFunction resultSerializer;
    private final InvertibleFunction exceptionSerializer;
    
    public CompletedFutureSerializer(InvertibleFunction serializer) {
        this(serializer.compose(InvertibleFunction.uncheckedCast()),
             serializer.compose(InvertibleFunction.uncheckedCast()));
    }
    
    public CompletedFutureSerializer(InvertibleFunction resultSerializer,
                                              InvertibleFunction exceptionSerializer) {
        this.resultSerializer = resultSerializer;
        this.exceptionSerializer = exceptionSerializer;
    }
    
    @Override
    public String apply(Future future) {
        if (!future.isDone()) {
            throw new IllegalArgumentException();
        }
        try {
            return NORMAL_VALUE_PREFIX + resultSerializer.apply(future.get());
        } catch (InterruptedException e) {
            // Should never happen
            throw new IllegalStateException();
        } catch (ExecutionException e) {
            return EXCEPTION_PREFIX + exceptionSerializer.apply(e.getCause());
        } catch (CancellationException e) {
            return Character.toString(CANCELLED_PREFIX);
        }
    }
    
    @Override
    public Future unapply(String serialized) {
        CompletableFuture future = new CompletableFuture<>();
        String serializedValue = serialized.substring(1, serialized.length());
        switch (serialized.charAt(0)) {
        case NORMAL_VALUE_PREFIX:
            future.complete(resultSerializer.unapply(serializedValue));
            break;
        case CANCELLED_PREFIX:
            future.cancel(false);
            break;
        case EXCEPTION_PREFIX:
            future.completeExceptionally(exceptionSerializer.unapply(serializedValue));
            break;
        }
        return future;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy