001 /*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements. See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership. The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License. You may obtain a copy of the License at
009 *
010 * http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied. See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 *
019 */
020
021 package org.apache.directory.server.changepw.protocol;
022
023
024 import java.io.IOException;
025
026 import org.apache.directory.server.changepw.io.ChangePasswordErrorEncoder;
027 import org.apache.directory.server.changepw.io.ChangePasswordReplyEncoder;
028 import org.apache.directory.server.changepw.messages.ChangePasswordError;
029 import org.apache.directory.server.changepw.messages.ChangePasswordReply;
030 import org.apache.mina.core.buffer.IoBuffer;
031 import org.apache.mina.core.session.IoSession;
032 import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
033 import org.apache.mina.filter.codec.ProtocolEncoderOutput;
034
035
036 /**
037 * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
038 * @version $Rev: 549315 $, $Date: 2007-06-20 18:13:53 -0700 (Wed, 20 Jun 2007) $
039 */
040 public class ChangePasswordTcpEncoder extends ProtocolEncoderAdapter
041 {
042 ChangePasswordReplyEncoder replyEncoder = new ChangePasswordReplyEncoder();
043 ChangePasswordErrorEncoder errorEncoder = new ChangePasswordErrorEncoder();
044
045
046 public void encode( IoSession session, Object message, ProtocolEncoderOutput out ) throws IOException
047 {
048 IoBuffer buf = IoBuffer.allocate( 512 );
049
050 // make space for int length
051 buf.putInt( 0 );
052
053 if ( message instanceof ChangePasswordReply )
054 {
055 replyEncoder.encode( buf.buf(), ( ChangePasswordReply ) message );
056 }
057 else
058 {
059 if ( message instanceof ChangePasswordError )
060 {
061 errorEncoder.encode( buf.buf(), ( ChangePasswordError ) message );
062 }
063 }
064
065 // mark position
066 int pos = buf.position();
067
068 // length is the data minus 4 bytes for the pre-pended length
069 int recordLength = buf.position() - 4;
070
071 // write the length
072 buf.rewind();
073 buf.putInt( recordLength );
074
075 // set the position back before flipping the buffer
076 buf.position( pos );
077 buf.flip();
078
079 out.write( buf );
080 }
081 }