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

io.appulse.epmd.java.server.command.server.handler.ResponseEncoder Maven / Gradle / Ivy

/*
 * Copyright 2018 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.appulse.epmd.java.server.command.server.handler;

import io.appulse.epmd.java.core.mapper.serializer.MessageSerializer;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;
import lombok.val;

/**
 *
 * @author Artem Labazin
 * @since 0.4.0
 */
@Slf4j
@Sharable
public class ResponseEncoder extends MessageToByteEncoder {

  private final MessageSerializer serializer = new MessageSerializer();

  @Override
  public void exceptionCaught (ChannelHandlerContext context, Throwable cause) throws Exception {
    val message = String.format("Error during channel connection with %s",
                                context.channel().remoteAddress().toString());

    log.error(message, cause);
    context.close();
  }

  @Override
  protected void encode (ChannelHandlerContext context, Object response, ByteBuf out) throws Exception {
    log.debug("Encoding message {} for {}", response, context.channel().remoteAddress());
    val bytes = serializer.serialize(response);
    log.debug("Output bytes:\n{}", bytes);
    out.writeBytes(bytes);
    log.debug("Message was sent");
  }
}