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
021package org.apache.directory.server.dns.io.encoder;
022
023
024import org.apache.directory.api.util.Strings;
025import org.apache.directory.server.dns.messages.QuestionRecord;
026import org.apache.directory.server.dns.messages.RecordClass;
027import org.apache.directory.server.dns.messages.RecordType;
028import org.apache.mina.core.buffer.IoBuffer;
029
030
031/**
032 * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
033 */
034public class QuestionRecordEncoder
035{
036    /**
037     * Encodes the {@link QuestionRecord} into the {@link IoBuffer}.
038     *
039     * @param out
040     * @param question
041     */
042    public void put( IoBuffer out, QuestionRecord question )
043    {
044        encodeDomainName( out, question.getDomainName() );
045        encodeRecordType( out, question.getRecordType() );
046        encodeRecordClass( out, question.getRecordClass() );
047    }
048
049
050    private void encodeDomainName( IoBuffer byteBuffer, String domainName )
051    {
052        if ( !Strings.isEmpty( domainName ) )
053        {
054            String[] labels = domainName.split( "\\." );
055        
056
057            for ( String label : labels )
058            {
059                byteBuffer.put( ( byte ) label.length() );
060    
061                char[] characters = label.toCharArray();
062                
063                for ( char c : characters )
064                {
065                    byteBuffer.put( ( byte ) c );
066                }
067            }
068        }
069
070        byteBuffer.put( ( byte ) 0x00 );
071    }
072
073
074    private void encodeRecordType( IoBuffer byteBuffer, RecordType recordType )
075    {
076        byteBuffer.putShort( recordType.convert() );
077    }
078
079
080    private void encodeRecordClass( IoBuffer byteBuffer, RecordClass recordClass )
081    {
082        byteBuffer.putShort( recordClass.convert() );
083    }
084}