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

com.lambdaworks.redis.output.MultiOutput Maven / Gradle / Ivy

There is a newer version: 3.40.2
Show newest version
// Copyright (C) 2011 - Will Glozer.  All rights reserved.

package com.lambdaworks.redis.output;

import com.lambdaworks.redis.RedisException;
import com.lambdaworks.redis.codec.RedisCodec;
import com.lambdaworks.redis.protocol.Command;
import com.lambdaworks.redis.protocol.CommandOutput;

import java.nio.ByteBuffer;
import java.util.*;

/**
 * Output of all commands within a MULTI block.
 *
 * @author Will Glozer
 */
public class MultiOutput extends CommandOutput> {
    private Queue> queue;

    public MultiOutput(RedisCodec codec) {
        super(codec, new ArrayList());
        queue = new LinkedList>();
    }

    public void add(Command cmd) {
        queue.add(cmd);
    }

    public void cancel() {
        for (Command c : queue) {
            c.cancel();
        }
    }

    @Override
    public void set(long integer) {
        queue.peek().getOutput().set(integer);
    }

    @Override
    public void set(ByteBuffer bytes) {
        queue.peek().getOutput().set(bytes);
    }

    @Override
    public void setError(ByteBuffer error) {
        CommandOutput output = queue.isEmpty() ? this : queue.peek().getOutput();
        output.setError(decodeAscii(error));
    }

    @Override
    public void complete(int depth) {
        if (depth == 1) {
            Command cmd = queue.remove();
            CommandOutput o = cmd.getOutput();
            output.add(!o.hasError() ? o.get() : new RedisException(o.getError()));
            cmd.complete();
        } else if (depth == 0 && !queue.isEmpty()) {
            for (Command cmd : queue) {
                cmd.complete();
            }
        }
    }
}