xyz.cloudbans.client.utils.httpclient.SerializerConsumer.java Source code

Java tutorial

Introduction

Here is the source code for xyz.cloudbans.client.utils.httpclient.SerializerConsumer.java

Source

/*
 * Copyright 2016 CloudBans (https://cloudbans.xyz)
 *
 *    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 xyz.cloudbans.client.utils.httpclient;

import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.client.methods.AsyncCharConsumer;
import org.apache.http.protocol.HttpContext;
import xyz.cloudbans.client.utils.serializer.Serializer;

import java.io.IOException;
import java.nio.CharBuffer;

public class SerializerConsumer<T> extends AsyncCharConsumer<T> {

    private final StringBuilder sb = new StringBuilder();
    private final Serializer serializer;
    private final Class<T> targetClass;

    public SerializerConsumer(Serializer serializer, Class<T> targetClass) {
        this.serializer = serializer;
        this.targetClass = targetClass;
    }

    @Override
    protected void onCharReceived(CharBuffer charBuffer, IOControl ioControl) throws IOException {
        sb.append(charBuffer.toString());
    }

    @Override
    protected void onResponseReceived(HttpResponse httpResponse) throws HttpException, IOException {
        // ToDo: ApiException on error?
    }

    @Override
    protected T buildResult(HttpContext httpContext) throws Exception {
        return serializer.deserialize(sb.toString(), targetClass);
    }

    public static <T> SerializerConsumer<T> create(Serializer serializer, Class<T> target) {
        return new SerializerConsumer<>(serializer, target);
    }
}