io.dyn.net.protocol.LineProtocol.java Source code

Java tutorial

Introduction

Here is the source code for io.dyn.net.protocol.LineProtocol.java

Source

/*
 * Copyright (c) 2011-2012 by the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.dyn.net.protocol;

import java.nio.charset.Charset;

import io.dyn.core.Evented;
import io.dyn.core.handler.Handler;
import io.dyn.net.nio.Buffer;
import org.springframework.util.StringUtils;

/**
 * @author Jon Brisbin <jon@jbrisbin.com>
 */
public class LineProtocol extends AbstractProtocol<LineProtocol> {

    private static final String LF = "\n";

    protected Charset charsetEncoding = Charset.forName("ISO-8859-1");
    protected String newline = LF;
    protected String remainder;

    public LineProtocol() {
        super("line");
    }

    public LineProtocol(Charset charsetEncoding) {
        super("line");
        this.charsetEncoding = charsetEncoding;
    }

    @Override
    public String eventName() {
        return this.eventName;
    }

    public String newline() {
        return newline;
    }

    public LineProtocol newline(String newline) {
        this.newline = newline;
        return this;
    }

    @Override
    public <V extends Evented<? super V>> LineProtocol decode(Buffer buffer, V evented) {
        String line = charsetEncoding.decode(buffer.byteBuffer()).toString();
        if (null != remainder) {
            line = remainder + line;
            remainder = null;
        }
        boolean endsWithLF = line.endsWith(newline);
        String[] parts = StringUtils.tokenizeToStringArray(line, newline, false, false);

        int len = parts.length;
        for (int i = 0; i < len; i++) {
            if (i == len - 1 && !endsWithLF) {
                remainder = parts[i];
            } else {
                evented.event(eventName, parts[i].trim());
            }
        }

        return this;
    }

    @Override
    public <V extends Evented<? super V>> LineProtocol encode(V evented, final Buffer buffer) {
        evented.on(eventName, new Handler<String>() {
            @Override
            public void handle(String s, Object... args) {
                buffer.append(s);
                if (!s.endsWith(newline)) {
                    buffer.append(newline);
                }
            }
        });
        return this;
    }

}