001/*
002 * Copyright 2016-2024 Ping Identity Corporation
003 * All Rights Reserved.
004 */
005/*
006 * Copyright 2016-2024 Ping Identity Corporation
007 *
008 * Licensed under the Apache License, Version 2.0 (the "License");
009 * you may not use this file except in compliance with the License.
010 * You may obtain a copy of the License at
011 *
012 *    http://www.apache.org/licenses/LICENSE-2.0
013 *
014 * Unless required by applicable law or agreed to in writing, software
015 * distributed under the License is distributed on an "AS IS" BASIS,
016 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
017 * See the License for the specific language governing permissions and
018 * limitations under the License.
019 */
020/*
021 * Copyright (C) 2016-2024 Ping Identity Corporation
022 *
023 * This program is free software; you can redistribute it and/or modify
024 * it under the terms of the GNU General Public License (GPLv2 only)
025 * or the terms of the GNU Lesser General Public License (LGPLv2.1 only)
026 * as published by the Free Software Foundation.
027 *
028 * This program is distributed in the hope that it will be useful,
029 * but WITHOUT ANY WARRANTY; without even the implied warranty of
030 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
031 * GNU General Public License for more details.
032 *
033 * You should have received a copy of the GNU General Public License
034 * along with this program; if not, see <http://www.gnu.org/licenses>.
035 */
036package com.unboundid.util;
037
038
039
040import java.io.BufferedReader;
041import java.io.Closeable;
042import java.io.File;
043import java.io.FileReader;
044import java.io.IOException;
045import java.text.ParseException;
046import java.util.concurrent.atomic.AtomicLong;
047
048import com.unboundid.ldap.sdk.DN;
049import com.unboundid.ldap.sdk.LDAPException;
050import com.unboundid.ldap.sdk.ResultCode;
051
052import static com.unboundid.util.UtilityMessages.*;
053
054
055
056/**
057 * This class provides a mechanism for reading DNs from a file.  The file is
058 * expected to have one DN per line.  Blank lines and lines beginning with the
059 * octothorpe (#) character will be ignored.  Lines may contain just the raw DN,
060 * or they may start with "dn:" followed by an optional space and the DN, or
061 * "dn::" followed by an optional space and the base64-encoded representation of
062 * the DN.
063 */
064@ThreadSafety(level=ThreadSafetyLevel.COMPLETELY_THREADSAFE)
065public final class DNFileReader
066       implements Closeable
067{
068  // A counter used to keep track of the line number for information read from
069  // the file.
070  @NotNull private final AtomicLong lineNumberCounter;
071
072  // The reader to use to read the DNs.
073  @NotNull private final BufferedReader reader;
074
075  // The file from which the DNs are being read.
076  @NotNull private final File dnFile;
077
078
079
080  /**
081   * Creates a new DN file reader that will read from the file with the
082   * specified path.
083   *
084   * @param  path  The path to the file to be read.  It must not be {@code null}
085   *               and the file must exist.
086   *
087   * @throws  IOException  If a problem is encountered while opening the file
088   *                       for reading.
089   */
090  public DNFileReader(@NotNull final String path)
091         throws IOException
092  {
093    this(new File(path));
094  }
095
096
097
098  /**
099   * Creates a new DN file reader that will read from the specified file.
100   *
101   * @param  dnFile  The file to be read.  It must not be {@code null} and the
102   *                 file must exist.
103   *
104   * @throws  IOException  If a problem is encountered while opening the file
105   *                       for reading.
106   */
107  public DNFileReader(@NotNull final File dnFile)
108         throws IOException
109  {
110    this.dnFile = dnFile;
111
112    reader = new BufferedReader(new FileReader(dnFile));
113    lineNumberCounter = new AtomicLong(0L);
114  }
115
116
117
118  /**
119   * Reads the next DN from the file.
120   *
121   * @return  The DN read from the file, or {@code null} if there are no more
122   *          DNs to be read.
123   *
124   * @throws  IOException  If a problem is encountered while trying to read from
125   *                       the file.
126   *
127   * @throws  LDAPException  If data read from the file can't be parsed as a DN.
128   */
129  @Nullable()
130  public DN readDN()
131         throws IOException, LDAPException
132  {
133    while (true)
134    {
135      final long lineNumber;
136      final String line;
137      synchronized (this)
138      {
139        line = reader.readLine();
140        lineNumber = lineNumberCounter.incrementAndGet();
141      }
142
143      if (line == null)
144      {
145        return null;
146      }
147
148      final String trimmedLine = line.trim();
149      if (trimmedLine.isEmpty() || trimmedLine.startsWith("#"))
150      {
151        continue;
152      }
153
154      String dnString = trimmedLine;
155      if (trimmedLine.charAt(2) == ':')
156      {
157        final String lowerLine = StaticUtils.toLowerCase(trimmedLine);
158        if (lowerLine.startsWith("dn::"))
159        {
160          final String base64String = line.substring(4).trim();
161
162          try
163          {
164            dnString = Base64.decodeToString(base64String);
165          }
166          catch (final ParseException pe)
167          {
168            Debug.debugException(pe);
169            throw new LDAPException(ResultCode.DECODING_ERROR,
170                 ERR_DN_FILE_READER_CANNOT_BASE64_DECODE.get(base64String,
171                      lineNumber, dnFile.getAbsolutePath(), pe.getMessage()),
172                 pe);
173          }
174        }
175        else if (lowerLine.startsWith("dn:"))
176        {
177          dnString = line.substring(3).trim();
178        }
179      }
180
181      try
182      {
183        return new DN(dnString);
184      }
185      catch (final LDAPException le)
186      {
187        Debug.debugException(le);
188        throw new LDAPException(ResultCode.INVALID_DN_SYNTAX,
189             ERR_DN_FILE_READER_CANNOT_PARSE_DN.get(dnString, lineNumber,
190                  dnFile.getAbsolutePath(), le.getMessage()),
191             le);
192      }
193    }
194  }
195
196
197
198  /**
199   * Closes this DN file reader.
200   *
201   * @throws  IOException  If a problem is encountered while closing the reader.
202   */
203  @Override()
204  public void close()
205         throws IOException
206  {
207    reader.close();
208  }
209}