View Javadoc
1   /*
2    *  Licensed to the Apache Software Foundation (ASF) under one
3    *  or more contributor license agreements.  See the NOTICE file
4    *  distributed with this work for additional information
5    *  regarding copyright ownership.  The ASF licenses this file
6    *  to you under the Apache License, Version 2.0 (the
7    *  "License"); you may not use this file except in compliance
8    *  with the License.  You may obtain a copy of the License at
9    *
10   *    http://www.apache.org/licenses/LICENSE-2.0
11   *
12   *  Unless required by applicable law or agreed to in writing,
13   *  software distributed under the License is distributed on an
14   *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   *  KIND, either express or implied.  See the License for the
16   *  specific language governing permissions and limitations
17   *  under the License.
18   *
19   */
20  package org.apache.directory.api.asn1.ber.tlv;
21  
22  
23  import org.apache.directory.api.i18n.I18n;
24  import org.apache.directory.api.util.Strings;
25  import org.slf4j.Logger;
26  import org.slf4j.LoggerFactory;
27  
28  
29  /**
30   * Parse and decode a Boolean value.
31   *
32   * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
33   */
34  public final class BooleanDecoder
35  {
36      /** The logger */
37      private static final Logger LOG = LoggerFactory.getLogger( BooleanDecoder.class );
38  
39  
40      /**
41       * Parse a Value containing a byte[] and send back a boolean.
42       *
43       * @param value The Value to parse
44       * @return A boolean.
45       * @throws BooleanDecoderException Thrown if the Value does not contains a boolean
46       */
47      public static boolean parse( BerValue value ) throws BooleanDecoderException
48      {
49          byte[] bytes = value.getData();
50  
51          if ( Strings.isEmpty( bytes ) )
52          {
53              throw new BooleanDecoderException( I18n.err( I18n.ERR_00034_0_BYTES_LONG_BOOLEAN ) );
54          }
55  
56          if ( bytes.length != 1 )
57          {
58              throw new BooleanDecoderException( I18n.err( I18n.ERR_00035_N_BYTES_LONG_BOOLEAN ) );
59          }
60  
61          if ( ( bytes[0] != 0 ) && ( bytes[0] != ( byte ) 0xFF ) )
62          {
63              LOG.warn( "A boolean must be encoded with a 0x00 or a 0xFF value" );
64          }
65  
66          return bytes[0] != 0;
67      }
68  }