From 08a8540072a370b4e7e9604eb97818dcfd4d74c6 Mon Sep 17 00:00:00 2001
From: Gaetan Boismal <gaetan.boismal@forgerock.com>
Date: Mon, 31 Oct 2016 14:00:38 +0000
Subject: [PATCH] OPENDJ-2773 Remove duplicated server tools
---
opendj-server-legacy/src/test/java/org/opends/server/extensions/FingerprintCertificateMapperTestCase.java | 33
opendj-server-legacy/src/test/java/org/opends/server/extensions/SubjectAttributeToUserAttributeCertificateMapperTestCase.java | 48
opendj-server-legacy/src/main/java/org/opends/server/extensions/TripleDESPasswordStorageScheme.java | 10
opendj-server-legacy/src/test/java/org/opends/server/controls/PersistentSearchControlTest.java | 6
opendj-dsml-servlet/src/main/java/org/opends/dsml/protocol/DSMLServlet.java | 8
opendj-server-legacy/src/main/java/org/opends/server/tools/StopDS.java | 2
opendj-server-legacy/src/test/java/org/opends/server/extensions/AnonymousSASLMechanismHandlerTestCase.java | 9
opendj-server-legacy/src/test/java/org/opends/server/extensions/PlainSASLMechanismHandlerTestCase.java | 11
opendj-server-legacy/src/test/java/org/opends/server/extensions/TraditionalWorkQueueTestCase.java | 5
opendj-server-legacy/src/main/java/org/opends/server/extensions/SaltedSHA512PasswordStorageScheme.java | 10
opendj-server-legacy/pom.xml | 6
opendj-server-legacy/src/test/java/org/opends/server/core/AddOperationTestCase.java | 15
opendj-server-legacy/src/test/java/org/opends/server/plugins/SevenBitCleanPluginTestCase.java | 36
opendj-server-legacy/src/main/java/org/opends/server/protocols/ldap/SearchResultEntryProtocolOp.java | 2
opendj-server-legacy/src/test/java/org/opends/server/tasks/LockdownModeTaskTestCase.java | 28
opendj-server-legacy/src/main/java/org/opends/server/extensions/Base64PasswordStorageScheme.java | 4
opendj-server-legacy/src/test/java/org/opends/server/extensions/SubjectDNToUserAttributeCertificateMapperTestCase.java | 38
opendj-core/src/test/java/org/forgerock/opendj/ldap/TestBase64.java | 190 +++++
opendj-server-legacy/src/main/java/org/opends/server/extensions/SaltedMD5PasswordStorageScheme.java | 8
opendj-server-legacy/src/test/java/org/opends/server/extensions/ExternalSASLMechanismHandlerTestCase.java | 42
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/task/ResetUserPasswordTask.java | 82 +
opendj-core/src/main/java/org/forgerock/opendj/ldap/Base64.java | 22
opendj-server-legacy/src/test/java/org/opends/server/protocols/ldap/TestAddRequestProtocolOp.java | 6
opendj-server-legacy/src/main/java/org/opends/server/extensions/PKCS5S2PasswordStorageScheme.java | 8
opendj-server-legacy/src/test/java/org/opends/server/replication/ChangeNumberControlPluginTestCase.java | 186 +++--
opendj-server-legacy/src/main/java/org/opends/server/extensions/BlowfishPasswordStorageScheme.java | 10
opendj-server-legacy/src/test/java/org/opends/server/authorization/dseecompat/ReferencesTestCase.java | 4
opendj-server-legacy/src/test/java/org/opends/server/extensions/StartTLSExtendedOperationTestCase.java | 26
opendj-server-legacy/src/test/java/org/opends/server/protocols/ldap/LDAPBinaryOptionTestCase.java | 25
opendj-server-legacy/src/main/java/org/opends/server/types/NullOutputStream.java | 10
opendj-server-legacy/src/test/java/org/opends/server/schema/CollationMatchingRuleTest.java | 6
opendj-server-legacy/src/main/java/org/opends/server/extensions/SaltedSHA384PasswordStorageScheme.java | 8
opendj-server-legacy/src/test/java/org/opends/server/backends/LDIFBackendTestCase.java | 14
opendj-server-legacy/src/test/java/org/opends/server/authorization/dseecompat/AciTestCase.java | 104 +-
opendj-server-legacy/src/test/java/org/opends/server/authorization/dseecompat/AciTests.java | 53 -
opendj-server-legacy/src/test/java/org/opends/server/types/PrivilegeTestCase.java | 18
opendj-server-legacy/src/main/java/org/opends/server/extensions/RC4PasswordStorageScheme.java | 10
opendj-server-legacy/src/test/java/org/opends/server/core/BindOperationTestCase.java | 28
opendj-server-legacy/src/main/java/org/opends/server/extensions/AESPasswordStorageScheme.java | 6
opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/ReplicationRepairControlTest.java | 15
opendj-server-legacy/src/test/java/org/opends/server/replication/InitOnLineTest.java | 5
opendj-server-legacy/src/main/java/org/opends/server/extensions/PBKDF2PasswordStorageScheme.java | 8
opendj-server-legacy/src/test/java/org/opends/server/core/GroupManagerTestCase.java | 9
opendj-server-legacy/src/test/java/org/opends/server/core/TestModifyDNOperation.java | 7
opendj-server-legacy/src/main/java/org/opends/server/types/BackupInfo.java | 6
opendj-server-legacy/src/test/java/org/opends/server/core/SearchOperationTestCase.java | 9
opendj-server-legacy/src/test/java/org/opends/server/tools/ArgumentParserToolsTestCase.java | 48 -
opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/HistoricalTest.java | 5
opendj-server-legacy/src/main/java/org/opends/server/util/LDIFReader.java | 5
opendj-server-legacy/src/test/java/org/opends/server/extensions/DigestMD5SASLMechanismHandlerTestCase.java | 39
opendj-server-legacy/src/main/java/org/opends/server/extensions/SHA1PasswordStorageScheme.java | 4
opendj-server-legacy/src/test/java/org/opends/server/core/PasswordPolicyTestCase.java | 47
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/datamodel/BinaryValue.java | 4
opendj-server-legacy/src/main/java/org/opends/server/tools/ConfigureWindowsService.java | 2
opendj-server-legacy/src/test/java/org/opends/server/core/SubentryManagerTestCase.java | 11
opendj-server-legacy/src/test/java/org/opends/server/tasks/AllowedTaskTestCase.java | 11
opendj-server-legacy/src/main/java/org/opends/server/config/ConfigurationHandler.java | 40
opendj-server-legacy/src/test/java/org/opends/server/extensions/UserDefinedVirtualAttributeProviderTestCase.java | 15
opendj-server-legacy/src/main/java/org/opends/server/loggers/TextAuditLogPublisher.java | 2
opendj-server-legacy/src/main/java/org/opends/server/protocols/ldap/AddRequestProtocolOp.java | 4
opendj-server-legacy/src/test/java/org/opends/server/extensions/CRAMMD5SASLMechanismHandlerTestCase.java | 25
opendj-server-legacy/src/test/java/org/opends/server/types/EntrySchemaCheckingTestCase.java | 47
opendj-server-legacy/src/test/java/org/opends/server/extensions/PasswordModifyExtendedOperationTestCase.java | 99 +-
opendj-server-legacy/src/test/java/org/opends/server/TestCaseUtils.java | 36
opendj-server-legacy/src/test/java/org/opends/server/core/DeleteOperationTestCase.java | 9
opendj-server-legacy/src/main/java/org/opends/server/extensions/MD5PasswordStorageScheme.java | 4
opendj-server-legacy/src/main/java/org/opends/server/crypto/CryptoManagerImpl.java | 4
opendj-server-legacy/src/main/java/org/opends/server/util/LDIFWriter.java | 1
opendj-server-legacy/src/test/java/org/opends/server/api/PasswordValidatorTestCase.java | 21
opendj-server-legacy/src/test/java/org/opends/server/replication/server/MonitorTest.java | 6
opendj-server-legacy/src/test/java/org/opends/server/types/SearchFilterTests.java | 4
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/ViewEntryPanel.java | 2
opendj-server-legacy/src/test/java/org/opends/server/core/RejectUnauthReqTests.java | 46
opendj-server-legacy/src/test/java/org/opends/server/backends/SchemaBackendTestCase.java | 7
opendj-server-legacy/src/test/java/org/opends/server/core/ModifyOperationTestCase.java | 21
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/JavaPropertiesPanel.java | 4
/dev/null | 202 -----
opendj-server-legacy/src/test/java/org/opends/server/authorization/dseecompat/TargetControlTestCase.java | 5
opendj-server-legacy/src/main/java/org/opends/server/schema/SchemaFilesWriter.java | 4
opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/NewBaseDNPanel.java | 13
opendj-server-legacy/src/main/java/org/opends/server/extensions/SaltedSHA256PasswordStorageScheme.java | 8
opendj-server-legacy/src/test/java/org/opends/server/controls/MatchedValuesControlTest.java | 4
opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPAuthenticationHandler.java | 2
opendj-server-legacy/src/main/java/org/opends/server/extensions/SaltedSHA1PasswordStorageScheme.java | 10
84 files changed, 997 insertions(+), 1,020 deletions(-)
diff --git a/opendj-core/src/main/java/org/forgerock/opendj/ldap/Base64.java b/opendj-core/src/main/java/org/forgerock/opendj/ldap/Base64.java
index 93f5e5a..aa0b5ee 100644
--- a/opendj-core/src/main/java/org/forgerock/opendj/ldap/Base64.java
+++ b/opendj-core/src/main/java/org/forgerock/opendj/ldap/Base64.java
@@ -12,7 +12,7 @@
* information: "Portions Copyright [year] [name of copyright owner]".
*
* Copyright 2006-2009 Sun Microsystems, Inc.
- * Portions copyright 2012-2015 ForgeRock AS.
+ * Portions copyright 2012-2016 ForgeRock AS.
*/
package org.forgerock.opendj.ldap;
@@ -34,7 +34,7 @@
* For example, the JDK encoder does not handle array/offset/len parameters, and
* the decoder ignores invalid Base64 data.
*/
-final class Base64 {
+public final class Base64 {
/**
* The set of characters that may be used in base64-encoded values.
*/
@@ -53,7 +53,7 @@
* @throws NullPointerException
* If {@code base64} was {@code null}.
*/
- static ByteString decode(final String base64) {
+ public static ByteString decode(final String base64) {
Reject.ifNull(base64);
// The encoded value must have length that is a multiple of four
@@ -307,7 +307,21 @@
* @throws NullPointerException
* If {@code bytes} was {@code null}.
*/
- static String encode(final ByteSequence bytes) {
+ public static String encode(final byte[] bytes) {
+ return encode(ByteString.wrap(bytes));
+ }
+
+
+ /**
+ * Encodes the provided data as a base64 string.
+ *
+ * @param bytes
+ * The data to be encoded.
+ * @return The base64 encoded representation of {@code bytes}.
+ * @throws NullPointerException
+ * If {@code bytes} was {@code null}.
+ */
+ public static String encode(final ByteSequence bytes) {
Reject.ifNull(bytes);
if (bytes.isEmpty()) {
diff --git a/opendj-core/src/test/java/org/forgerock/opendj/ldap/TestBase64.java b/opendj-core/src/test/java/org/forgerock/opendj/ldap/TestBase64.java
new file mode 100644
index 0000000..3f4ad0a
--- /dev/null
+++ b/opendj-core/src/test/java/org/forgerock/opendj/ldap/TestBase64.java
@@ -0,0 +1,190 @@
+/*
+ * The contents of this file are subject to the terms of the Common Development and
+ * Distribution License (the License). You may not use this file except in compliance with the
+ * License.
+ *
+ * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
+ * specific language governing permission and limitations under the License.
+ *
+ * When distributing Covered Software, include this CDDL Header Notice in each file and include
+ * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
+ * Header, with the fields enclosed by brackets [] replaced by your own identifying
+ * information: "Portions Copyright [year] [name of copyright owner]".
+ *
+ * Copyright 2016 ForgeRock AS.
+ */
+package org.forgerock.opendj.ldap;
+
+import static org.fest.assertions.Assertions.*;
+
+import org.forgerock.i18n.LocalizedIllegalArgumentException;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+/** This class defines a set of tests for the {@link org.forgerock.opendj.ldap.Base64} class. */
+public final class TestBase64 extends SdkTestCase {
+ /** Look up table for converting hex chars to byte values. */
+ private static final byte[] HEX_TO_BYTE = { -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1,
+ -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1 - 1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 };
+
+ /**
+ * Base 64 valid test data provider.
+ *
+ * @return Returns an array of decoded and valid encoded base64 data.
+ */
+ @DataProvider(name = "validData")
+ public Object[][] createValidData() {
+ return new Object[][] {
+ { "", "" },
+ { "00", "AA==" },
+ { "01", "AQ==" },
+ { "02", "Ag==" },
+ { "03", "Aw==" },
+ { "04", "BA==" },
+ { "05", "BQ==" },
+ { "06", "Bg==" },
+ { "07", "Bw==" },
+ { "0000", "AAA=" },
+ { "000000", "AAAA" },
+ { "00000000", "AAAAAA==" },
+ {
+ "000102030405060708090a0b0c0d0e0f"
+ + "101112131415161718191a1b1c1d1e1f"
+ + "202122232425262728292a2b2c2d2e2f"
+ + "303132333435363738393a3b3c3d3e3f"
+ + "404142434445464748494a4b4c4d4e4f"
+ + "505152535455565758595a5b5c5d5e5f"
+ + "606162636465666768696a6b6c6d6e6f"
+ + "707172737475767778797a7b7c7d7e7f"
+ + "808182838485868788898a8b8c8d8e8f"
+ + "909192939495969798999a9b9c9d9e9f"
+ + "a0a1a2a3a4a5a6a7a8a9aaabacadaeaf"
+ + "b0b1b2b3b4b5b6b7b8b9babbbcbdbebf"
+ + "c0c1c2c3c4c5c6c7c8c9cacbcccdcecf"
+ + "d0d1d2d3d4d5d6d7d8d9dadbdcdddedf"
+ + "e0e1e2e3e4e5e6e7e8e9eaebecedeeef"
+ + "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
+
+ "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4v"
+ + "MDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5f"
+ + "YGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6P"
+ + "kJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/"
+ + "wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v"
+ + "8PHy8/T19vf4+fr7/P3+/w=="
+ },
+ };
+ }
+
+ /**
+ * Base 64 invalid test data provider.
+ *
+ * @return Returns an array of invalid encoded base64 data.
+ */
+ @DataProvider(name = "invalidData")
+ public Object[][] createInvalidData() {
+ // FIXME: fix cases ==== and ==x=
+
+ return new Object[][] { { "=" }, { "==" }, { "===" }, { "A" },
+ { "AA" }, { "AAA" }, { "AA`=" }, { "AA~=" }, { "AA!=" },
+ { "AA@=" }, { "AA#=" }, { "AA$=" }, { "AA%=" }, { "AA^=" },
+ { "AA*=" }, { "AA(=" }, { "AA)=" }, { "AA_=" }, { "AA-=" },
+ { "AA{=" }, { "AA}=" }, { "AA|=" }, { "AA[=" }, { "AA]=" },
+ { "AA\\=" }, { "AA;=" }, { "AA'=" }, { "AA\"=" }, { "AA:=" },
+ { "AA,=" }, { "AA.=" }, { "AA<=" }, { "AA>=" }, { "AA?=" },
+ { "AA;=" } };
+ }
+
+ /**
+ * Tests the encode method.
+ *
+ * @param hexData
+ * The decoded hex data.
+ * @param encodedData
+ * The encoded data.
+ * @throws Exception
+ * If the test failed unexpectedly.
+ */
+ @Test(dataProvider = "validData")
+ public void testEncode(final String hexData, final String encodedData) throws Exception {
+ assertThat(Base64.encode(getBytes(hexData))).isEqualTo(encodedData);
+ }
+
+ /**
+ * Tests the decode method against valid data.
+ *
+ * @param hexData
+ * The decoded hex data.
+ * @param encodedData
+ * The encoded data.
+ * @throws Exception
+ * If the test failed unexpectedly.
+ */
+ @Test(dataProvider = "validData")
+ public void testDecodeValidData(final String hexData, final String encodedData) throws Exception {
+ assertThat(Base64.decode(encodedData).toByteArray()).isEqualTo(getBytes(hexData));
+ }
+
+ /**
+ * Tests the decode method against invalid data.
+ *
+ * @param encodedData
+ * The invalid encoded data.
+ * @throws Exception
+ * If the test failed unexpectedly.
+ */
+ @Test(dataProvider = "invalidData",
+ expectedExceptions = LocalizedIllegalArgumentException.class,
+ expectedExceptionsMessageRegExp = ".*cannot be base64-decoded.*")
+ public void testDecodeInvalidData(String encodedData) throws Exception {
+ Base64.decode(encodedData).toByteArray();
+ }
+
+ /**
+ * Decode a hex string to a byte-array.
+ *
+ * @param hexData
+ * The string of hex.
+ * @return Returns the decoded byte array.
+ */
+ private byte[] getBytes(String hexData) {
+ int sz = hexData.length();
+
+ if (sz % 2 != 0) {
+ throw new IllegalArgumentException("Hex string does not contain an even number of hex digits");
+ }
+
+ byte[] bytes = new byte[sz / 2];
+
+ for (int i = 0, j = 0; i < sz; i += 2, j++) {
+ int c = hexData.codePointAt(i);
+ if ((c & 0x7f) != c) {
+ throw new IllegalArgumentException("Hex string contains non-hex digits");
+ }
+
+ byte b1 = HEX_TO_BYTE[c];
+ if (b1 < 0) {
+ throw new IllegalArgumentException("Hex string contains non-hex digits");
+ }
+
+ c = hexData.codePointAt(i + 1);
+ if ((c & 0x7f) != c) {
+ throw new IllegalArgumentException("Hex string contains non-hex digits");
+ }
+
+ byte b2 = HEX_TO_BYTE[c];
+ if (b2 < 0) {
+ throw new IllegalArgumentException("Hex string contains non-hex digits");
+ }
+
+ bytes[j] = (byte) ((b1 << 4) | b2);
+ }
+
+ return bytes;
+ }
+}
diff --git a/opendj-dsml-servlet/src/main/java/org/opends/dsml/protocol/DSMLServlet.java b/opendj-dsml-servlet/src/main/java/org/opends/dsml/protocol/DSMLServlet.java
index b00def0..dd2fee7 100644
--- a/opendj-dsml-servlet/src/main/java/org/opends/dsml/protocol/DSMLServlet.java
+++ b/opendj-dsml-servlet/src/main/java/org/opends/dsml/protocol/DSMLServlet.java
@@ -31,7 +31,6 @@
import java.io.OutputStream;
import java.io.StringReader;
import java.net.URL;
-import java.text.ParseException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
@@ -72,6 +71,8 @@
import javax.xml.validation.SchemaFactory;
import org.forgerock.i18n.LocalizableMessage;
+import org.forgerock.i18n.LocalizedIllegalArgumentException;
+import org.forgerock.opendj.ldap.Base64;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.DereferenceAliasesPolicy;
import org.forgerock.opendj.ldap.SearchScope;
@@ -89,7 +90,6 @@
import org.opends.server.tools.SSLConnectionException;
import org.opends.server.tools.SSLConnectionFactory;
import org.opends.server.types.LDAPException;
-import org.opends.server.util.Base64;
import org.w3c.dom.Document;
import org.xml.sax.Attributes;
import org.xml.sax.EntityResolver;
@@ -379,7 +379,7 @@
authenticationInHeader = true;
String authorization = headerVal.substring(6).trim();
try {
- String unencoded = new String(Base64.decode(authorization));
+ String unencoded = new String(Base64.decode(authorization).toByteArray());
int colon = unencoded.indexOf(':');
if (colon > 0) {
if (useHTTPAuthzID)
@@ -395,7 +395,7 @@
}
bindPassword = unencoded.substring(colon + 1);
}
- } catch (ParseException ex) {
+ } catch (final LocalizedIllegalArgumentException ex) {
// user/DN:password parsing error
batchResponses.add(
createErrorResponse(objFactory,
diff --git a/opendj-server-legacy/pom.xml b/opendj-server-legacy/pom.xml
index d876762..bdeee94 100644
--- a/opendj-server-legacy/pom.xml
+++ b/opendj-server-legacy/pom.xml
@@ -105,6 +105,12 @@
</dependency>
<dependency>
+ <groupId>org.forgerock.opendj</groupId>
+ <artifactId>opendj-ldap-toolkit</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
+ <dependency>
<groupId>org.forgerock</groupId>
<artifactId>forgerock-build-tools</artifactId>
</dependency>
diff --git a/opendj-server-legacy/resource/bin/base64 b/opendj-server-legacy/resource/bin/base64
deleted file mode 100644
index 1a087f5..0000000
--- a/opendj-server-legacy/resource/bin/base64
+++ /dev/null
@@ -1,27 +0,0 @@
-#!/bin/sh
-#
-# The contents of this file are subject to the terms of the Common Development and
-# Distribution License (the License). You may not use this file except in compliance with the
-# License.
-#
-# You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
-# specific language governing permission and limitations under the License.
-#
-# When distributing Covered Software, include this CDDL Header Notice in each file and include
-# the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
-# Header, with the fields enclosed by brackets [] replaced by your own identifying
-# information: "Portions Copyright [year] [name of copyright owner]".
-#
-# Copyright 2008 Sun Microsystems, Inc.
-# Portions Copyright 2011 ForgeRock AS.
-
-
-# This script may be used to display the status panel.
-OPENDJ_INVOKE_CLASS="org.opends.server.util.Base64"
-export OPENDJ_INVOKE_CLASS
-
-SCRIPT_NAME="base64"
-export SCRIPT_NAME
-
-SCRIPT_DIR=`dirname "${0}"`
-"${SCRIPT_DIR}/../lib/_client-script.sh" "${@}"
diff --git a/opendj-server-legacy/resource/bin/base64.bat b/opendj-server-legacy/resource/bin/base64.bat
deleted file mode 100644
index b79973e..0000000
--- a/opendj-server-legacy/resource/bin/base64.bat
+++ /dev/null
@@ -1,23 +0,0 @@
-
-@echo off
-rem The contents of this file are subject to the terms of the Common Development and
-rem Distribution License (the License). You may not use this file except in compliance with the
-rem License.
-rem
-rem You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
-rem specific language governing permission and limitations under the License.
-rem
-rem When distributing Covered Software, include this CDDL Header Notice in each file and include
-rem the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
-rem Header, with the fields enclosed by brackets [] replaced by your own identifying
-rem information: "Portions Copyright [year] [name of copyright owner]".
-rem
-rem Copyright 2006-2008 Sun Microsystems, Inc.
-rem Portions Copyright 2011 ForgeRock AS.
-
-setlocal
-
-set OPENDJ_INVOKE_CLASS="org.opends.server.util.Base64"
-set SCRIPT_NAME=base64
-call "%~dp0\..\lib\_client-script.bat" %*
-
diff --git a/opendj-server-legacy/resource/bin/ldapcompare b/opendj-server-legacy/resource/bin/ldapcompare
deleted file mode 100644
index 7f63f32..0000000
--- a/opendj-server-legacy/resource/bin/ldapcompare
+++ /dev/null
@@ -1,27 +0,0 @@
-#!/bin/sh
-#
-# The contents of this file are subject to the terms of the Common Development and
-# Distribution License (the License). You may not use this file except in compliance with the
-# License.
-#
-# You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
-# specific language governing permission and limitations under the License.
-#
-# When distributing Covered Software, include this CDDL Header Notice in each file and include
-# the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
-# Header, with the fields enclosed by brackets [] replaced by your own identifying
-# information: "Portions Copyright [year] [name of copyright owner]".
-#
-# Copyright 2006-2008 Sun Microsystems, Inc.
-# Portions Copyright 2011 ForgeRock AS.
-
-
-# This script may be used to perform LDAP compare operations.
-OPENDJ_INVOKE_CLASS="org.opends.server.tools.LDAPCompare"
-export OPENDJ_INVOKE_CLASS
-
-SCRIPT_NAME="ldapcompare"
-export SCRIPT_NAME
-
-SCRIPT_DIR=`dirname "${0}"`
-"${SCRIPT_DIR}/../lib/_client-script.sh" "${@}"
diff --git a/opendj-server-legacy/resource/bin/ldapcompare.bat b/opendj-server-legacy/resource/bin/ldapcompare.bat
deleted file mode 100644
index b7f0377..0000000
--- a/opendj-server-legacy/resource/bin/ldapcompare.bat
+++ /dev/null
@@ -1,23 +0,0 @@
-
-@echo off
-rem The contents of this file are subject to the terms of the Common Development and
-rem Distribution License (the License). You may not use this file except in compliance with the
-rem License.
-rem
-rem You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
-rem specific language governing permission and limitations under the License.
-rem
-rem When distributing Covered Software, include this CDDL Header Notice in each file and include
-rem the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
-rem Header, with the fields enclosed by brackets [] replaced by your own identifying
-rem information: "Portions Copyright [year] [name of copyright owner]".
-rem
-rem Copyright 2006-2008 Sun Microsystems, Inc.
-rem Portions Copyright 2011 ForgeRock AS.
-
-setlocal
-
-set OPENDJ_INVOKE_CLASS="org.opends.server.tools.LDAPCompare"
-set SCRIPT_NAME=ldapcompare
-call "%~dp0\..\lib\_client-script.bat" %*
-
diff --git a/opendj-server-legacy/resource/bin/ldapdelete b/opendj-server-legacy/resource/bin/ldapdelete
deleted file mode 100644
index 855aa07..0000000
--- a/opendj-server-legacy/resource/bin/ldapdelete
+++ /dev/null
@@ -1,27 +0,0 @@
-#!/bin/sh
-#
-# The contents of this file are subject to the terms of the Common Development and
-# Distribution License (the License). You may not use this file except in compliance with the
-# License.
-#
-# You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
-# specific language governing permission and limitations under the License.
-#
-# When distributing Covered Software, include this CDDL Header Notice in each file and include
-# the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
-# Header, with the fields enclosed by brackets [] replaced by your own identifying
-# information: "Portions Copyright [year] [name of copyright owner]".
-#
-# Copyright 2006-2008 Sun Microsystems, Inc.
-# Portions Copyright 2011 ForgeRock AS.
-
-
-# This script may be used to perform LDAP delete operations.
-OPENDJ_INVOKE_CLASS="org.opends.server.tools.LDAPDelete"
-export OPENDJ_INVOKE_CLASS
-
-SCRIPT_NAME="ldapdelete"
-export SCRIPT_NAME
-
-SCRIPT_DIR=`dirname "${0}"`
-"${SCRIPT_DIR}/../lib/_client-script.sh" "${@}"
diff --git a/opendj-server-legacy/resource/bin/ldapdelete.bat b/opendj-server-legacy/resource/bin/ldapdelete.bat
deleted file mode 100644
index 271086e..0000000
--- a/opendj-server-legacy/resource/bin/ldapdelete.bat
+++ /dev/null
@@ -1,23 +0,0 @@
-
-@echo off
-rem The contents of this file are subject to the terms of the Common Development and
-rem Distribution License (the License). You may not use this file except in compliance with the
-rem License.
-rem
-rem You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
-rem specific language governing permission and limitations under the License.
-rem
-rem When distributing Covered Software, include this CDDL Header Notice in each file and include
-rem the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
-rem Header, with the fields enclosed by brackets [] replaced by your own identifying
-rem information: "Portions Copyright [year] [name of copyright owner]".
-rem
-rem Copyright 2006-2008 Sun Microsystems, Inc.
-rem Portions Copyright 2011 ForgeRock AS.
-
-setlocal
-
-set OPENDJ_INVOKE_CLASS="org.opends.server.tools.LDAPDelete"
-set SCRIPT_NAME=ldapdelete
-call "%~dp0\..\lib\_client-script.bat" %*
-
diff --git a/opendj-server-legacy/resource/bin/ldapmodify b/opendj-server-legacy/resource/bin/ldapmodify
deleted file mode 100644
index 076f537..0000000
--- a/opendj-server-legacy/resource/bin/ldapmodify
+++ /dev/null
@@ -1,28 +0,0 @@
-#!/bin/sh
-#
-# The contents of this file are subject to the terms of the Common Development and
-# Distribution License (the License). You may not use this file except in compliance with the
-# License.
-#
-# You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
-# specific language governing permission and limitations under the License.
-#
-# When distributing Covered Software, include this CDDL Header Notice in each file and include
-# the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
-# Header, with the fields enclosed by brackets [] replaced by your own identifying
-# information: "Portions Copyright [year] [name of copyright owner]".
-#
-# Copyright 2006-2008 Sun Microsystems, Inc.
-# Portions Copyright 2011 ForgeRock AS.
-
-
-# This script may be used to perform LDAP add, delete, modify, and modify DN
-# operations.
-OPENDJ_INVOKE_CLASS="org.opends.server.tools.LDAPModify"
-export OPENDJ_INVOKE_CLASS
-
-SCRIPT_NAME="ldapmodify"
-export SCRIPT_NAME
-
-SCRIPT_DIR=`dirname "${0}"`
-"${SCRIPT_DIR}/../lib/_client-script.sh" "${@}"
diff --git a/opendj-server-legacy/resource/bin/ldapmodify.bat b/opendj-server-legacy/resource/bin/ldapmodify.bat
deleted file mode 100644
index 34826d9..0000000
--- a/opendj-server-legacy/resource/bin/ldapmodify.bat
+++ /dev/null
@@ -1,23 +0,0 @@
-
-@echo off
-rem The contents of this file are subject to the terms of the Common Development and
-rem Distribution License (the License). You may not use this file except in compliance with the
-rem License.
-rem
-rem You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
-rem specific language governing permission and limitations under the License.
-rem
-rem When distributing Covered Software, include this CDDL Header Notice in each file and include
-rem the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
-rem Header, with the fields enclosed by brackets [] replaced by your own identifying
-rem information: "Portions Copyright [year] [name of copyright owner]".
-rem
-rem Copyright 2006-2008 Sun Microsystems, Inc.
-rem Portions Copyright 2011 ForgeRock AS.
-
-setlocal
-
-set OPENDJ_INVOKE_CLASS="org.opends.server.tools.LDAPModify"
-set SCRIPT_NAME=ldapmodify
-call "%~dp0\..\lib\_client-script.bat" %*
-
diff --git a/opendj-server-legacy/resource/bin/ldappasswordmodify b/opendj-server-legacy/resource/bin/ldappasswordmodify
deleted file mode 100644
index 59500df..0000000
--- a/opendj-server-legacy/resource/bin/ldappasswordmodify
+++ /dev/null
@@ -1,27 +0,0 @@
-#!/bin/sh
-#
-# The contents of this file are subject to the terms of the Common Development and
-# Distribution License (the License). You may not use this file except in compliance with the
-# License.
-#
-# You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
-# specific language governing permission and limitations under the License.
-#
-# When distributing Covered Software, include this CDDL Header Notice in each file and include
-# the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
-# Header, with the fields enclosed by brackets [] replaced by your own identifying
-# information: "Portions Copyright [year] [name of copyright owner]".
-#
-# Copyright 2006-2008 Sun Microsystems, Inc.
-# Portions Copyright 2011 ForgeRock AS.
-
-
-# This script may be used to perform LDAP password modify operations.
-OPENDJ_INVOKE_CLASS="org.opends.server.tools.LDAPPasswordModify"
-export OPENDJ_INVOKE_CLASS
-
-SCRIPT_NAME="ldappasswordmodify"
-export SCRIPT_NAME
-
-SCRIPT_DIR=`dirname "${0}"`
-"${SCRIPT_DIR}/../lib/_client-script.sh" "${@}"
diff --git a/opendj-server-legacy/resource/bin/ldappasswordmodify.bat b/opendj-server-legacy/resource/bin/ldappasswordmodify.bat
deleted file mode 100644
index 472d187..0000000
--- a/opendj-server-legacy/resource/bin/ldappasswordmodify.bat
+++ /dev/null
@@ -1,23 +0,0 @@
-
-@echo off
-rem The contents of this file are subject to the terms of the Common Development and
-rem Distribution License (the License). You may not use this file except in compliance with the
-rem License.
-rem
-rem You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
-rem specific language governing permission and limitations under the License.
-rem
-rem When distributing Covered Software, include this CDDL Header Notice in each file and include
-rem the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
-rem Header, with the fields enclosed by brackets [] replaced by your own identifying
-rem information: "Portions Copyright [year] [name of copyright owner]".
-rem
-rem Copyright 2006-2008 Sun Microsystems, Inc.
-rem Portions Copyright 2011 ForgeRock AS.
-
-setlocal
-
-set OPENDJ_INVOKE_CLASS="org.opends.server.tools.LDAPPasswordModify"
-set SCRIPT_NAME=ldappasswordmodify
-call "%~dp0\..\lib\_client-script.bat" %*
-
diff --git a/opendj-server-legacy/resource/bin/ldapsearch b/opendj-server-legacy/resource/bin/ldapsearch
deleted file mode 100644
index cc5fde6..0000000
--- a/opendj-server-legacy/resource/bin/ldapsearch
+++ /dev/null
@@ -1,27 +0,0 @@
-#!/bin/sh
-#
-# The contents of this file are subject to the terms of the Common Development and
-# Distribution License (the License). You may not use this file except in compliance with the
-# License.
-#
-# You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
-# specific language governing permission and limitations under the License.
-#
-# When distributing Covered Software, include this CDDL Header Notice in each file and include
-# the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
-# Header, with the fields enclosed by brackets [] replaced by your own identifying
-# information: "Portions Copyright [year] [name of copyright owner]".
-#
-# Copyright 2006-2008 Sun Microsystems, Inc.
-# Portions Copyright 2011 ForgeRock AS.
-
-
-# This script may be used to perform LDAP search operations.
-OPENDJ_INVOKE_CLASS="org.opends.server.tools.LDAPSearch"
-export OPENDJ_INVOKE_CLASS
-
-SCRIPT_NAME="ldapsearch"
-export SCRIPT_NAME
-
-SCRIPT_DIR=`dirname "${0}"`
-"${SCRIPT_DIR}/../lib/_client-script.sh" "${@}"
diff --git a/opendj-server-legacy/resource/bin/ldapsearch.bat b/opendj-server-legacy/resource/bin/ldapsearch.bat
deleted file mode 100644
index a4ef975..0000000
--- a/opendj-server-legacy/resource/bin/ldapsearch.bat
+++ /dev/null
@@ -1,23 +0,0 @@
-
-@echo off
-rem The contents of this file are subject to the terms of the Common Development and
-rem Distribution License (the License). You may not use this file except in compliance with the
-rem License.
-rem
-rem You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
-rem specific language governing permission and limitations under the License.
-rem
-rem When distributing Covered Software, include this CDDL Header Notice in each file and include
-rem the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
-rem Header, with the fields enclosed by brackets [] replaced by your own identifying
-rem information: "Portions Copyright [year] [name of copyright owner]".
-rem
-rem Copyright 2006-2008 Sun Microsystems, Inc.
-rem Portions Copyright 2011 ForgeRock AS.
-
-setlocal
-
-set OPENDJ_INVOKE_CLASS="org.opends.server.tools.LDAPSearch"
-set SCRIPT_NAME=ldapsearch
-call "%~dp0\..\lib\_client-script.bat" %*
-
diff --git a/opendj-server-legacy/resource/bin/ldif-diff b/opendj-server-legacy/resource/bin/ldif-diff
deleted file mode 100644
index 353a74f..0000000
--- a/opendj-server-legacy/resource/bin/ldif-diff
+++ /dev/null
@@ -1,27 +0,0 @@
-#!/bin/sh
-#
-# The contents of this file are subject to the terms of the Common Development and
-# Distribution License (the License). You may not use this file except in compliance with the
-# License.
-#
-# You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
-# specific language governing permission and limitations under the License.
-#
-# When distributing Covered Software, include this CDDL Header Notice in each file and include
-# the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
-# Header, with the fields enclosed by brackets [] replaced by your own identifying
-# information: "Portions Copyright [year] [name of copyright owner]".
-#
-# Copyright 2006-2009 Sun Microsystems, Inc.
-# Portions Copyright 2011 ForgeRock AS.
-
-
-# This script may be used to compare the contents of two LDIF files.
-OPENDJ_INVOKE_CLASS="org.opends.server.tools.LDIFDiff"
-export OPENDJ_INVOKE_CLASS
-
-SCRIPT_NAME="ldif-diff"
-export SCRIPT_NAME
-
-SCRIPT_DIR=`dirname "${0}"`
-"${SCRIPT_DIR}/../lib/_server-script.sh" "${@}"
diff --git a/opendj-server-legacy/resource/bin/ldif-diff.bat b/opendj-server-legacy/resource/bin/ldif-diff.bat
deleted file mode 100644
index 4b3b4bf..0000000
--- a/opendj-server-legacy/resource/bin/ldif-diff.bat
+++ /dev/null
@@ -1,24 +0,0 @@
-
-@echo off
-rem The contents of this file are subject to the terms of the Common Development and
-rem Distribution License (the License). You may not use this file except in compliance with the
-rem License.
-rem
-rem You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
-rem specific language governing permission and limitations under the License.
-rem
-rem When distributing Covered Software, include this CDDL Header Notice in each file and include
-rem the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
-rem Header, with the fields enclosed by brackets [] replaced by your own identifying
-rem information: "Portions Copyright [year] [name of copyright owner]".
-rem
-rem Copyright 2006-2009 Sun Microsystems, Inc.
-rem Portions Copyright 2011 ForgeRock AS.
-
-setlocal
-
-set OPENDJ_INVOKE_CLASS="org.opends.server.tools.LDIFDiff"
-set SCRIPT_NAME=ldif-diff
-call "%~dp0\..\lib\_server-script.bat" %*
-
-
diff --git a/opendj-server-legacy/resource/bin/ldifmodify b/opendj-server-legacy/resource/bin/ldifmodify
deleted file mode 100644
index efcdd7b..0000000
--- a/opendj-server-legacy/resource/bin/ldifmodify
+++ /dev/null
@@ -1,27 +0,0 @@
-#!/bin/sh
-#
-# The contents of this file are subject to the terms of the Common Development and
-# Distribution License (the License). You may not use this file except in compliance with the
-# License.
-#
-# You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
-# specific language governing permission and limitations under the License.
-#
-# When distributing Covered Software, include this CDDL Header Notice in each file and include
-# the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
-# Header, with the fields enclosed by brackets [] replaced by your own identifying
-# information: "Portions Copyright [year] [name of copyright owner]".
-#
-# Copyright 2006-2008 Sun Microsystems, Inc.
-# Portions Copyright 2011 ForgeRock AS.
-
-
-# This script may be used to alter the contents of an LDIF file.
-OPENDJ_INVOKE_CLASS="org.opends.server.tools.LDIFModify"
-export OPENDJ_INVOKE_CLASS
-
-SCRIPT_NAME="ldifmodify"
-export SCRIPT_NAME
-
-SCRIPT_DIR=`dirname "${0}"`
-"${SCRIPT_DIR}/../lib/_server-script.sh" "${@}"
diff --git a/opendj-server-legacy/resource/bin/ldifmodify.bat b/opendj-server-legacy/resource/bin/ldifmodify.bat
deleted file mode 100644
index 3bffa0f..0000000
--- a/opendj-server-legacy/resource/bin/ldifmodify.bat
+++ /dev/null
@@ -1,23 +0,0 @@
-
-@echo off
-rem The contents of this file are subject to the terms of the Common Development and
-rem Distribution License (the License). You may not use this file except in compliance with the
-rem License.
-rem
-rem You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
-rem specific language governing permission and limitations under the License.
-rem
-rem When distributing Covered Software, include this CDDL Header Notice in each file and include
-rem the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
-rem Header, with the fields enclosed by brackets [] replaced by your own identifying
-rem information: "Portions Copyright [year] [name of copyright owner]".
-rem
-rem Copyright 2006-2008 Sun Microsystems, Inc.
-rem Portions Copyright 2011 ForgeRock AS.
-
-setlocal
-
-set OPENDJ_INVOKE_CLASS="org.opends.server.tools.LDIFModify"
-set SCRIPT_NAME=ldifmodify
-call "%~dp0\..\lib\_server-script.bat" %*
-
diff --git a/opendj-server-legacy/resource/bin/ldifsearch b/opendj-server-legacy/resource/bin/ldifsearch
deleted file mode 100644
index 3438a2f..0000000
--- a/opendj-server-legacy/resource/bin/ldifsearch
+++ /dev/null
@@ -1,27 +0,0 @@
-#!/bin/sh
-#
-# The contents of this file are subject to the terms of the Common Development and
-# Distribution License (the License). You may not use this file except in compliance with the
-# License.
-#
-# You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
-# specific language governing permission and limitations under the License.
-#
-# When distributing Covered Software, include this CDDL Header Notice in each file and include
-# the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
-# Header, with the fields enclosed by brackets [] replaced by your own identifying
-# information: "Portions Copyright [year] [name of copyright owner]".
-#
-# Copyright 2006-2008 Sun Microsystems, Inc.
-# Portions Copyright 2011 ForgeRock AS.
-
-
-# This script may be used to perform searches in an LDIF file.
-OPENDJ_INVOKE_CLASS="org.opends.server.tools.LDIFSearch"
-export OPENDJ_INVOKE_CLASS
-
-SCRIPT_NAME="ldifsearch"
-export SCRIPT_NAME
-
-SCRIPT_DIR=`dirname "${0}"`
-"${SCRIPT_DIR}/../lib/_server-script.sh" "${@}"
diff --git a/opendj-server-legacy/resource/bin/ldifsearch.bat b/opendj-server-legacy/resource/bin/ldifsearch.bat
deleted file mode 100644
index dff7939..0000000
--- a/opendj-server-legacy/resource/bin/ldifsearch.bat
+++ /dev/null
@@ -1,23 +0,0 @@
-
-@echo off
-rem The contents of this file are subject to the terms of the Common Development and
-rem Distribution License (the License). You may not use this file except in compliance with the
-rem License.
-rem
-rem You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
-rem specific language governing permission and limitations under the License.
-rem
-rem When distributing Covered Software, include this CDDL Header Notice in each file and include
-rem the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
-rem Header, with the fields enclosed by brackets [] replaced by your own identifying
-rem information: "Portions Copyright [year] [name of copyright owner]".
-rem
-rem Copyright 2006-2008 Sun Microsystems, Inc.
-rem Portions Copyright 2011 ForgeRock AS.
-
-setlocal
-
-set OPENDJ_INVOKE_CLASS="org.opends.server.tools.LDIFSearch"
-set SCRIPT_NAME=ldifsearch
-call "%~dp0\..\lib\_server-script.bat" %*
-
diff --git a/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/datamodel/BinaryValue.java b/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/datamodel/BinaryValue.java
index 2ef06b1..2bda377 100644
--- a/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/datamodel/BinaryValue.java
+++ b/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/datamodel/BinaryValue.java
@@ -21,7 +21,7 @@
import java.text.ParseException;
import java.util.Objects;
-import org.opends.server.util.Base64;
+import org.forgerock.opendj.ldap.Base64;
/**
* Class used to represent Binary Values. This is required in particular
@@ -123,7 +123,7 @@
{
if (bytes == null && base64 != null)
{
- bytes = Base64.decode(base64);
+ bytes = Base64.decode(base64).toByteArray();
}
return bytes;
}
diff --git a/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/task/ResetUserPasswordTask.java b/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/task/ResetUserPasswordTask.java
index 54c03e5..6d625be 100644
--- a/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/task/ResetUserPasswordTask.java
+++ b/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/task/ResetUserPasswordTask.java
@@ -32,9 +32,14 @@
import org.forgerock.opendj.ldap.DN;
import org.forgerock.opendj.ldap.Filter;
import org.forgerock.opendj.ldap.LdapException;
+import org.forgerock.opendj.ldap.requests.PasswordModifyExtendedRequest;
+import org.forgerock.opendj.ldap.requests.Requests;
import org.forgerock.opendj.ldap.requests.SearchRequest;
+import org.forgerock.opendj.ldap.responses.PasswordModifyExtendedResult;
import org.forgerock.opendj.ldap.responses.SearchResultEntry;
import org.forgerock.opendj.ldif.ConnectionEntryReader;
+import org.forgerock.util.promise.ExceptionHandler;
+import org.forgerock.util.promise.ResultHandler;
import org.opends.admin.ads.util.ConnectionWrapper;
import org.opends.guitools.controlpanel.browser.BrowserController;
import org.opends.guitools.controlpanel.browser.ConnectionWithControls;
@@ -43,7 +48,6 @@
import org.opends.guitools.controlpanel.datamodel.ControlPanelInfo;
import org.opends.guitools.controlpanel.ui.ProgressDialog;
import org.opends.guitools.controlpanel.ui.nodes.BasicNode;
-import org.opends.server.tools.LDAPPasswordModify;
/** The task called when we want to reset the password of the user. */
public class ResetUserPasswordTask extends Task
@@ -176,39 +180,61 @@
{
state = State.RUNNING;
lastException = null;
- try
- {
- List<String> arguments = getCommandLineArguments();
- String[] args = arguments.toArray(new String[arguments.size()]);
-
- returnCode = LDAPPasswordModify.mainPasswordModify(args, false,
- outPrintStream, errorPrintStream);
-
- if (returnCode != 0)
+ final ConnectionWrapper connectionWrapper = useAdminCtx ? getInfo().getConnection()
+ : getInfo().getUserDataConnection();
+ if (!isServerRunning() || connectionWrapper == null)
{
+ // Fail fast impossible to connect to the server.
state = State.FINISHED_WITH_ERROR;
}
+ final PasswordModifyExtendedRequest passwordModifyRequest = Requests.newPasswordModifyExtendedRequest();
+ if (currentPassword == null)
+ {
+ passwordModifyRequest.setUserIdentity("dn: " + dn);
+ }
else
{
- if (lastException == null && currentPassword != null)
- {
- // The connections must be updated, just update the environment, which
- // is what we use to clone connections and to launch scripts.
- // The environment will also be used if we want to reconnect.
- rebind(getInfo().getConnection());
- if (getInfo().getUserDataConnection() != null)
- {
- rebind(getInfo().getUserDataConnection());
- }
- }
- state = State.FINISHED_SUCCESSFULLY;
+ passwordModifyRequest.setOldPassword(currentPassword);
}
- }
- catch (Throwable t)
- {
- lastException = t;
- state = State.FINISHED_WITH_ERROR;
- }
+ passwordModifyRequest.setNewPassword(newPassword);
+ connectionWrapper.getConnection()
+ .extendedRequestAsync(passwordModifyRequest)
+ .thenOnResultOrException(
+ new ResultHandler<PasswordModifyExtendedResult>()
+ {
+ @Override
+ public void handleResult(final PasswordModifyExtendedResult passwordModifyExtendedResult)
+ {
+ if (lastException == null && currentPassword != null)
+ {
+ try
+ {
+ // The connections must be updated, just update the environment, which
+ // is what we use to clone connections and to launch scripts.
+ // The environment will also be used if we want to reconnect.
+ rebind(getInfo().getConnection());
+ if (getInfo().getUserDataConnection() != null)
+ {
+ rebind(getInfo().getUserDataConnection());
+ }
+ }
+ catch (final LdapException e)
+ {
+ lastException = e;
+ state = State.FINISHED_WITH_ERROR;
+ }
+ }
+ state = State.FINISHED_SUCCESSFULLY;
+ }
+ },
+ new ExceptionHandler<LdapException>()
+ {
+ @Override
+ public void handleException(final LdapException e)
+ {
+ state = State.FINISHED_WITH_ERROR;
+ }
+ });
}
private void rebind(ConnectionWrapper conn) throws LdapException
diff --git a/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/JavaPropertiesPanel.java b/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/JavaPropertiesPanel.java
index d4e8751..61c1024 100644
--- a/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/JavaPropertiesPanel.java
+++ b/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/JavaPropertiesPanel.java
@@ -109,14 +109,14 @@
"list-backends", "manage-account", "manage-tasks", "restore.online",
"stop-ds", "status", "control-panel", "uninstall", "setup",
"backup.offline", "encode-password", "export-ldif.offline",
- "ldif-diff", "ldifmodify", "ldifsearch", "makeldif",
+ "ldifdiff", "ldifmodify", "ldifsearch", "makeldif",
"rebuild-index", "restore.offline", "upgrade",
"verify-index", "backendstat"
);
private final Set<String> relevantScriptNames = newHashSet(
"start-ds", "import-ldif.offline", "backup.offline",
"export-ldif.offline",
- "ldif-diff", "makeldif", "rebuild-index", "restore.offline",
+ "ldifdiff", "makeldif", "rebuild-index", "restore.offline",
"verify-index", "backendstat"
);
diff --git a/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/NewBaseDNPanel.java b/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/NewBaseDNPanel.java
index 0011ec2..02ff31e 100644
--- a/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/NewBaseDNPanel.java
+++ b/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/NewBaseDNPanel.java
@@ -86,7 +86,6 @@
import org.opends.server.tools.BackendTypeHelper;
import org.opends.server.tools.BackendTypeHelper.BackendTypeUIAdapter;
import org.opends.server.tools.ImportLDIF;
-import org.opends.server.tools.LDAPModify;
import org.opends.server.tools.makeldif.EntryWriter;
import org.opends.server.tools.makeldif.MakeLDIFException;
import org.opends.server.tools.makeldif.TemplateEntry;
@@ -839,7 +838,6 @@
else
{
// If we are not local, we use ldapmodify to update the contents.
- args.add("-a");
args.add("-f");
args.add(ldifFile);
}
@@ -1197,16 +1195,9 @@
}
try
{
- if (isServerRunning())
+ if (isServerRunning() && (isLocal() || importLDIF))
{
- if (isLocal() || importLDIF)
- {
- returnCode = ImportLDIF.mainImportLDIF(args, false, outPrintStream, errorPrintStream);
- }
- else
- {
- returnCode = LDAPModify.mainModify(args, false, outPrintStream, errorPrintStream);
- }
+ returnCode = ImportLDIF.mainImportLDIF(args, false, outPrintStream, errorPrintStream);
}
else
{
diff --git a/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/ViewEntryPanel.java b/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/ViewEntryPanel.java
index 16304a4..cca69ec 100644
--- a/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/ViewEntryPanel.java
+++ b/opendj-server-legacy/src/main/java/org/opends/guitools/controlpanel/ui/ViewEntryPanel.java
@@ -38,6 +38,7 @@
import org.forgerock.opendj.ldap.AVA;
import org.forgerock.opendj.ldap.Attribute;
import org.forgerock.opendj.ldap.AttributeDescription;
+import org.forgerock.opendj.ldap.Base64;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.DN;
import org.forgerock.opendj.ldap.Entry;
@@ -55,7 +56,6 @@
import org.opends.server.schema.SchemaConstants;
import org.opends.server.types.OpenDsException;
import org.forgerock.opendj.ldap.schema.Schema;
-import org.opends.server.util.Base64;
/**
* Abstract class containing code shared by the different LDAP entry view
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/config/ConfigurationHandler.java b/opendj-server-legacy/src/main/java/org/opends/server/config/ConfigurationHandler.java
index 2644cad..fdd8b96 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/config/ConfigurationHandler.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/config/ConfigurationHandler.java
@@ -26,6 +26,7 @@
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
+import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
@@ -36,7 +37,6 @@
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
-import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -80,6 +80,8 @@
import org.forgerock.opendj.ldap.schema.Schema;
import org.forgerock.opendj.ldap.schema.SchemaBuilder;
import org.forgerock.opendj.ldif.EntryReader;
+import org.forgerock.opendj.ldif.LDIF;
+import org.forgerock.opendj.ldif.LDIFChangeRecordReader;
import org.forgerock.opendj.ldif.LDIFEntryReader;
import org.forgerock.opendj.ldif.LDIFEntryWriter;
import org.forgerock.util.Utils;
@@ -89,16 +91,12 @@
import org.opends.server.core.SearchOperation;
import org.opends.server.core.ServerContext;
import org.opends.server.schema.GeneralizedTimeSyntax;
-import org.opends.server.tools.LDIFModify;
import org.opends.server.types.DirectoryEnvironmentConfig;
import org.opends.server.types.DirectoryException;
import org.opends.server.types.ExistingFileBehavior;
import org.opends.server.types.InitializationException;
import org.opends.server.types.LDIFExportConfig;
-import org.opends.server.types.LDIFImportConfig;
import org.opends.server.util.LDIFException;
-import org.opends.server.util.LDIFReader;
-import org.opends.server.util.LDIFWriter;
import org.opends.server.util.TimeThread;
/**
@@ -1576,33 +1574,17 @@
*/
private void applyChangesFile(File sourceFile, File changesFile) throws IOException, LDIFException
{
- // Create the appropriate LDIF readers and writer.
- LDIFImportConfig sourceImportCfg = new LDIFImportConfig(sourceFile.getAbsolutePath());
- sourceImportCfg.setValidateSchema(false);
- LDIFImportConfig changesImportCfg = new LDIFImportConfig(changesFile.getAbsolutePath());
- changesImportCfg.setValidateSchema(false);
-
- String tempFile = changesFile.getAbsolutePath() + ".tmp";
- LDIFExportConfig exportConfig = new LDIFExportConfig(tempFile, ExistingFileBehavior.OVERWRITE);
-
- List<LocalizableMessage> errorList = new LinkedList<>();
- boolean successful;
- try (LDIFReader sourceReader = new LDIFReader(sourceImportCfg);
- LDIFReader changesReader = new LDIFReader(changesImportCfg);
- LDIFWriter targetWriter = new LDIFWriter(exportConfig))
+ final String tempFilePath = changesFile.getAbsolutePath() + ".tmp";
+ try (final LDIFEntryReader sourceReader = new LDIFEntryReader(new FileReader(sourceFile));
+ final LDIFChangeRecordReader changeRecordReader = new LDIFChangeRecordReader(new FileReader(changesFile));
+ final LDIFEntryWriter ldifWriter = new LDIFEntryWriter(new FileWriter(tempFilePath)))
{
- // Apply the changes and make sure there were no errors.
- successful = LDIFModify.modifyLDIF(sourceReader, changesReader, targetWriter, errorList);
+ LDIF.copyTo(LDIF.patch(sourceReader, changeRecordReader), ldifWriter);
}
-
- if (!successful)
+ catch (final IOException e)
{
- for (LocalizableMessage s : errorList)
- {
- logger.error(ERR_CONFIG_ERROR_APPLYING_STARTUP_CHANGE, s);
- }
- throw new LDIFException(ERR_CONFIG_UNABLE_TO_APPLY_CHANGES_FILE.get(Utils.joinAsString("; ", errorList)));
+ throw new LDIFException(ERR_CONFIG_UNABLE_TO_APPLY_CHANGES_FILE.get(e.getLocalizedMessage()));
}
// Move the current config file out of the way and replace it with the updated version.
@@ -1612,7 +1594,7 @@
oldSource.delete();
}
sourceFile.renameTo(oldSource);
- new File(tempFile).renameTo(sourceFile);
+ new File(tempFilePath).renameTo(sourceFile);
// Move the changes file out of the way so it doesn't get applied again.
File newChanges = new File(changesFile.getAbsolutePath() + ".applied");
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/crypto/CryptoManagerImpl.java b/opendj-server-legacy/src/main/java/org/opends/server/crypto/CryptoManagerImpl.java
index d4a8f43..06e9de5 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/crypto/CryptoManagerImpl.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/crypto/CryptoManagerImpl.java
@@ -67,6 +67,7 @@
import org.forgerock.opendj.config.server.ConfigChangeResult;
import org.forgerock.opendj.config.server.ConfigException;
import org.forgerock.opendj.config.server.ConfigurationChangeListener;
+import org.forgerock.opendj.ldap.Base64;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.DN;
import org.forgerock.opendj.ldap.ModificationType;
@@ -108,7 +109,6 @@
import org.opends.server.types.InitializationException;
import org.opends.server.types.Modification;
import org.opends.server.types.SearchResultEntry;
-import org.opends.server.util.Base64;
import org.opends.server.util.SelectableCertificateKeyManager;
import org.opends.server.util.ServerConstants;
import org.opends.server.util.StaticUtils;
@@ -385,7 +385,7 @@
"jucN34MZwvzbmFHT/leUu3/cpykbGM9HL2QUX7iKvv2LJVqexhj7CLoXxZP" +
"oNL+HHKW0vi5/7W5KwOZsPqKI2SdYV7nDqTZklm5ZP0gmIuNO6mTqBRtC2D" +
"lplX1Iq+BrQJAmteiPtwhdZD+EIghe51CaseImjlLlY2ZK8w==";
- final byte[] certificate = Base64.decode(certificateBase64);
+ final byte[] certificate = Base64.decode(certificateBase64).toByteArray();
final String keyID = getInstanceKeyID(certificate);
final SecretKey macKey = macCryptoManager.generateKeyEntry(
requestedMACAlgorithm,
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/extensions/AESPasswordStorageScheme.java b/opendj-server-legacy/src/main/java/org/opends/server/extensions/AESPasswordStorageScheme.java
index 81ca447..41ef8fa 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/extensions/AESPasswordStorageScheme.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/extensions/AESPasswordStorageScheme.java
@@ -17,6 +17,7 @@
package org.opends.server.extensions;
import org.forgerock.i18n.LocalizableMessage;
+import org.forgerock.opendj.ldap.Base64;
import org.forgerock.opendj.server.config.server.AESPasswordStorageSchemeCfg;
import org.opends.server.api.PasswordStorageScheme;
import org.forgerock.opendj.config.server.ConfigException;
@@ -26,7 +27,6 @@
import org.forgerock.opendj.ldap.ResultCode;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.ByteSequence;
-import org.opends.server.util.Base64;
import java.util.Arrays;
@@ -153,7 +153,7 @@
{
ByteString decryptedPassword =
ByteString.wrap(cryptoManager.decrypt(
- Base64.decode(storedPassword.toString())));
+ Base64.decode(storedPassword.toString()).toByteArray()));
return plaintextPassword.equals(decryptedPassword);
}
catch (Exception e)
@@ -177,7 +177,7 @@
try
{
byte[] decryptedPassword =
- cryptoManager.decrypt(Base64.decode(storedPassword.toString()));
+ cryptoManager.decrypt(Base64.decode(storedPassword.toString()).toByteArray());
return ByteString.wrap(decryptedPassword);
}
catch (Exception e)
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/extensions/Base64PasswordStorageScheme.java b/opendj-server-legacy/src/main/java/org/opends/server/extensions/Base64PasswordStorageScheme.java
index 7fa3e77..91be997 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/extensions/Base64PasswordStorageScheme.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/extensions/Base64PasswordStorageScheme.java
@@ -17,6 +17,7 @@
package org.opends.server.extensions;
import org.forgerock.i18n.LocalizableMessage;
+import org.forgerock.opendj.ldap.Base64;
import org.forgerock.opendj.server.config.server.Base64PasswordStorageSchemeCfg;
import org.opends.server.api.PasswordStorageScheme;
import org.forgerock.opendj.config.server.ConfigException;
@@ -25,7 +26,6 @@
import org.forgerock.opendj.ldap.ResultCode;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.ByteSequence;
-import org.opends.server.util.Base64;
import static org.opends.messages.ExtensionMessages.*;
import static org.opends.server.extensions.ExtensionsConstants.*;
@@ -106,7 +106,7 @@
{
try
{
- return ByteString.wrap(Base64.decode(storedPassword.toString()));
+ return ByteString.wrap(Base64.decode(storedPassword.toString()).toByteArray());
}
catch (Exception e)
{
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/extensions/BlowfishPasswordStorageScheme.java b/opendj-server-legacy/src/main/java/org/opends/server/extensions/BlowfishPasswordStorageScheme.java
index 5241a11..93953ea 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/extensions/BlowfishPasswordStorageScheme.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/extensions/BlowfishPasswordStorageScheme.java
@@ -17,6 +17,7 @@
package org.opends.server.extensions;
import org.forgerock.i18n.LocalizableMessage;
+import org.forgerock.opendj.ldap.Base64;
import org.forgerock.opendj.server.config.server.BlowfishPasswordStorageSchemeCfg;
import org.opends.server.api.PasswordStorageScheme;
import org.forgerock.opendj.config.server.ConfigException;
@@ -26,7 +27,6 @@
import org.forgerock.opendj.ldap.ResultCode;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.ByteSequence;
-import org.opends.server.util.Base64;
import java.util.Arrays;
@@ -152,10 +152,8 @@
{
try
{
- ByteString decryptedPassword =
- ByteString.wrap(cryptoManager.decrypt(
- Base64.decode(storedPassword.toString())));
- return plaintextPassword.equals(decryptedPassword);
+ return plaintextPassword.equals(ByteString.wrap(
+ cryptoManager.decrypt(Base64.decode(storedPassword.toString()).toByteArray())));
}
catch (Exception e)
{
@@ -178,7 +176,7 @@
try
{
byte[] decryptedPassword =
- cryptoManager.decrypt(Base64.decode(storedPassword.toString()));
+ cryptoManager.decrypt(Base64.decode(storedPassword.toString()).toByteArray());
return ByteString.wrap(decryptedPassword);
}
catch (Exception e)
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/extensions/MD5PasswordStorageScheme.java b/opendj-server-legacy/src/main/java/org/opends/server/extensions/MD5PasswordStorageScheme.java
index f4be75e..4f9f0b4 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/extensions/MD5PasswordStorageScheme.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/extensions/MD5PasswordStorageScheme.java
@@ -20,6 +20,7 @@
import java.util.Arrays;
import org.forgerock.i18n.LocalizableMessage;
+import org.forgerock.opendj.ldap.Base64;
import org.forgerock.opendj.server.config.server.MD5PasswordStorageSchemeCfg;
import org.opends.server.api.PasswordStorageScheme;
import org.forgerock.opendj.config.server.ConfigException;
@@ -29,7 +30,6 @@
import org.forgerock.opendj.ldap.ResultCode;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.ByteSequence;
-import org.opends.server.util.Base64;
import static org.opends.messages.ExtensionMessages.*;
import static org.opends.server.extensions.ExtensionsConstants.*;
@@ -210,7 +210,7 @@
try
{
storedPWDigestBytes =
- ByteString.wrap(Base64.decode(storedPassword.toString()));
+ ByteString.wrap(Base64.decode(storedPassword.toString()).toByteArray());
}
catch (Exception e)
{
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/extensions/PBKDF2PasswordStorageScheme.java b/opendj-server-legacy/src/main/java/org/opends/server/extensions/PBKDF2PasswordStorageScheme.java
index ff5f40c..7a31d25 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/extensions/PBKDF2PasswordStorageScheme.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/extensions/PBKDF2PasswordStorageScheme.java
@@ -27,6 +27,7 @@
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.i18n.slf4j.LocalizedLogger;
import org.forgerock.opendj.config.server.ConfigException;
+import org.forgerock.opendj.ldap.Base64;
import org.forgerock.opendj.ldap.ByteSequence;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.ResultCode;
@@ -37,7 +38,6 @@
import org.forgerock.opendj.config.server.ConfigChangeResult;
import org.opends.server.types.DirectoryException;
import org.opends.server.types.InitializationException;
-import org.opends.server.util.Base64;
import static org.opends.messages.ExtensionMessages.*;
import static org.opends.server.extensions.ExtensionsConstants.*;
@@ -155,7 +155,7 @@
}
final int iterations = Integer.parseInt(stored.substring(0, pos));
- byte[] decodedBytes = Base64.decode(stored.substring(pos + 1));
+ byte[] decodedBytes = Base64.decode(stored.substring(pos + 1)).toByteArray();
final int saltLength = decodedBytes.length - SHA1_LENGTH;
if (saltLength <= 0)
@@ -214,8 +214,8 @@
throw new Exception();
}
int iterations = Integer.parseInt(authInfo.substring(0, pos));
- byte[] saltBytes = Base64.decode(authInfo.substring(pos + 1));
- byte[] digestBytes = Base64.decode(authValue);
+ byte[] saltBytes = Base64.decode(authInfo.substring(pos + 1)).toByteArray();
+ byte[] digestBytes = Base64.decode(authValue).toByteArray();
return encodeAndMatch(plaintextPassword, saltBytes, digestBytes, iterations);
}
catch (Exception e)
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/extensions/PKCS5S2PasswordStorageScheme.java b/opendj-server-legacy/src/main/java/org/opends/server/extensions/PKCS5S2PasswordStorageScheme.java
index e7ff89b..9af5cfc 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/extensions/PKCS5S2PasswordStorageScheme.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/extensions/PKCS5S2PasswordStorageScheme.java
@@ -26,6 +26,7 @@
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.i18n.slf4j.LocalizedLogger;
+import org.forgerock.opendj.ldap.Base64;
import org.forgerock.opendj.ldap.ByteSequence;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.ResultCode;
@@ -34,7 +35,6 @@
import org.opends.server.core.DirectoryServer;
import org.opends.server.types.DirectoryException;
import org.opends.server.types.InitializationException;
-import org.opends.server.util.Base64;
import static org.opends.messages.ExtensionMessages.*;
import static org.opends.server.extensions.ExtensionsConstants.*;
@@ -126,7 +126,7 @@
try
{
String stored = storedPassword.toString();
- byte[] decodedBytes = Base64.decode(stored);
+ byte[] decodedBytes = Base64.decode(stored).toByteArray();
if (decodedBytes.length != NUM_SALT_BYTES + SHA1_LENGTH)
{
@@ -183,8 +183,8 @@
throw new Exception();
}
int iterations = Integer.parseInt(authInfo.substring(0, pos));
- byte[] saltBytes = Base64.decode(authInfo.substring(pos + 1));
- byte[] digestBytes = Base64.decode(authValue);
+ byte[] saltBytes = Base64.decode(authInfo.substring(pos + 1)).toByteArray();
+ byte[] digestBytes = Base64.decode(authValue).toByteArray();
return encodeAndMatch(plaintextPassword, saltBytes, digestBytes, iterations);
}
catch (Exception e)
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/extensions/RC4PasswordStorageScheme.java b/opendj-server-legacy/src/main/java/org/opends/server/extensions/RC4PasswordStorageScheme.java
index ba400ee..ec70b93 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/extensions/RC4PasswordStorageScheme.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/extensions/RC4PasswordStorageScheme.java
@@ -17,6 +17,7 @@
package org.opends.server.extensions;
import org.forgerock.i18n.LocalizableMessage;
+import org.forgerock.opendj.ldap.Base64;
import org.forgerock.opendj.server.config.server.RC4PasswordStorageSchemeCfg;
import org.opends.server.api.PasswordStorageScheme;
import org.forgerock.opendj.config.server.ConfigException;
@@ -26,7 +27,6 @@
import org.forgerock.opendj.ldap.ResultCode;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.ByteSequence;
-import org.opends.server.util.Base64;
import java.util.Arrays;
@@ -152,10 +152,8 @@
{
try
{
- ByteString decryptedPassword =
- ByteString.wrap(cryptoManager.decrypt(
- Base64.decode(storedPassword.toString())));
- return plaintextPassword.equals(decryptedPassword);
+ return plaintextPassword.equals(ByteString.wrap(
+ cryptoManager.decrypt(Base64.decode(storedPassword.toString()).toByteArray())));
}
catch (Exception e)
{
@@ -178,7 +176,7 @@
try
{
byte[] decryptedPassword =
- cryptoManager.decrypt(Base64.decode(storedPassword.toString()));
+ cryptoManager.decrypt(Base64.decode(storedPassword.toString()).toByteArray());
return ByteString.wrap(decryptedPassword);
}
catch (Exception e)
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/extensions/SHA1PasswordStorageScheme.java b/opendj-server-legacy/src/main/java/org/opends/server/extensions/SHA1PasswordStorageScheme.java
index 0ac70e3..fcb0728 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/extensions/SHA1PasswordStorageScheme.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/extensions/SHA1PasswordStorageScheme.java
@@ -20,6 +20,7 @@
import java.util.Arrays;
import org.forgerock.i18n.LocalizableMessage;
+import org.forgerock.opendj.ldap.Base64;
import org.forgerock.opendj.server.config.server.SHA1PasswordStorageSchemeCfg;
import org.opends.server.api.PasswordStorageScheme;
import org.forgerock.opendj.config.server.ConfigException;
@@ -29,7 +30,6 @@
import org.forgerock.opendj.ldap.ResultCode;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.ByteSequence;
-import org.opends.server.util.Base64;
import static org.opends.messages.ExtensionMessages.*;
import static org.opends.server.extensions.ExtensionsConstants.*;
@@ -210,7 +210,7 @@
try
{
storedPWDigestBytes =
- ByteString.wrap(Base64.decode(storedPassword.toString()));
+ ByteString.wrap(Base64.decode(storedPassword.toString()).toByteArray());
}
catch (Exception e)
{
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/extensions/SaltedMD5PasswordStorageScheme.java b/opendj-server-legacy/src/main/java/org/opends/server/extensions/SaltedMD5PasswordStorageScheme.java
index 794e991..d19fd89 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/extensions/SaltedMD5PasswordStorageScheme.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/extensions/SaltedMD5PasswordStorageScheme.java
@@ -21,6 +21,7 @@
import java.util.Random;
import org.forgerock.i18n.LocalizableMessage;
+import org.forgerock.opendj.ldap.Base64;
import org.forgerock.opendj.server.config.server.SaltedMD5PasswordStorageSchemeCfg;
import org.opends.server.api.PasswordStorageScheme;
import org.forgerock.opendj.config.server.ConfigException;
@@ -30,7 +31,6 @@
import org.forgerock.opendj.ldap.ResultCode;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.ByteSequence;
-import org.opends.server.util.Base64;
import static org.opends.messages.ExtensionMessages.*;
import static org.opends.server.extensions.ExtensionsConstants.*;
@@ -222,7 +222,7 @@
int saltLength = 0;
try
{
- byte[] decodedBytes = Base64.decode(storedPassword.toString());
+ byte[] decodedBytes = Base64.decode(storedPassword.toString()).toByteArray();
saltLength = decodedBytes.length - MD5_LENGTH;
if (saltLength <= 0)
@@ -343,8 +343,8 @@
byte[] digestBytes;
try
{
- saltBytes = Base64.decode(authInfo);
- digestBytes = Base64.decode(authValue);
+ saltBytes = Base64.decode(authInfo).toByteArray();
+ digestBytes = Base64.decode(authValue).toByteArray();
}
catch (Exception e)
{
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/extensions/SaltedSHA1PasswordStorageScheme.java b/opendj-server-legacy/src/main/java/org/opends/server/extensions/SaltedSHA1PasswordStorageScheme.java
index e9325e7..2fcb41e 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/extensions/SaltedSHA1PasswordStorageScheme.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/extensions/SaltedSHA1PasswordStorageScheme.java
@@ -21,6 +21,7 @@
import java.util.Random;
import org.forgerock.i18n.LocalizableMessage;
+import org.forgerock.opendj.ldap.Base64;
import org.forgerock.opendj.server.config.server.SaltedSHA1PasswordStorageSchemeCfg;
import org.opends.server.api.PasswordStorageScheme;
import org.forgerock.opendj.config.server.ConfigException;
@@ -30,7 +31,6 @@
import org.forgerock.opendj.ldap.ResultCode;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.ByteSequence;
-import org.opends.server.util.Base64;
import static org.opends.messages.ExtensionMessages.*;
import static org.opends.server.extensions.ExtensionsConstants.*;
@@ -222,7 +222,7 @@
int saltLength = 0;
try
{
- byte[] decodedBytes = Base64.decode(storedPassword.toString());
+ byte[] decodedBytes = Base64.decode(storedPassword.toString()).toByteArray();
saltLength = decodedBytes.length - SHA1_LENGTH;
if (saltLength <= 0)
@@ -343,8 +343,8 @@
byte[] digestBytes;
try
{
- saltBytes = Base64.decode(authInfo);
- digestBytes = Base64.decode(authValue);
+ saltBytes = Base64.decode(authInfo).toByteArray();
+ digestBytes = Base64.decode(authValue).toByteArray();
}
catch (Exception e)
{
@@ -450,6 +450,6 @@
Arrays.fill(passwordPlusSalt, (byte) 0);
return "{" + STORAGE_SCHEME_NAME_SALTED_SHA_1 + "}" +
- Base64.encode(digestPlusSalt);
+ Base64.encode(digestPlusSalt);
}
}
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/extensions/SaltedSHA256PasswordStorageScheme.java b/opendj-server-legacy/src/main/java/org/opends/server/extensions/SaltedSHA256PasswordStorageScheme.java
index d7e89ff..fe76457 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/extensions/SaltedSHA256PasswordStorageScheme.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/extensions/SaltedSHA256PasswordStorageScheme.java
@@ -21,6 +21,7 @@
import java.util.Random;
import org.forgerock.i18n.LocalizableMessage;
+import org.forgerock.opendj.ldap.Base64;
import org.forgerock.opendj.server.config.server.SaltedSHA256PasswordStorageSchemeCfg;
import org.opends.server.api.PasswordStorageScheme;
import org.forgerock.opendj.config.server.ConfigException;
@@ -30,7 +31,6 @@
import org.forgerock.opendj.ldap.ResultCode;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.ByteSequence;
-import org.opends.server.util.Base64;
import static org.opends.messages.ExtensionMessages.*;
import static org.opends.server.extensions.ExtensionsConstants.*;
@@ -226,7 +226,7 @@
try
{
- byte[] decodedBytes = Base64.decode(storedPassword.toString());
+ byte[] decodedBytes = Base64.decode(storedPassword.toString()).toByteArray();
saltLength = decodedBytes.length - SHA256_LENGTH;
if (saltLength <= 0)
@@ -347,8 +347,8 @@
byte[] digestBytes;
try
{
- saltBytes = Base64.decode(authInfo);
- digestBytes = Base64.decode(authValue);
+ saltBytes = Base64.decode(authInfo).toByteArray();
+ digestBytes = Base64.decode(authValue).toByteArray();
}
catch (Exception e)
{
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/extensions/SaltedSHA384PasswordStorageScheme.java b/opendj-server-legacy/src/main/java/org/opends/server/extensions/SaltedSHA384PasswordStorageScheme.java
index 50c475d..b2f7bac 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/extensions/SaltedSHA384PasswordStorageScheme.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/extensions/SaltedSHA384PasswordStorageScheme.java
@@ -21,6 +21,7 @@
import java.util.Random;
import org.forgerock.i18n.LocalizableMessage;
+import org.forgerock.opendj.ldap.Base64;
import org.forgerock.opendj.server.config.server.SaltedSHA384PasswordStorageSchemeCfg;
import org.opends.server.api.PasswordStorageScheme;
import org.forgerock.opendj.config.server.ConfigException;
@@ -30,7 +31,6 @@
import org.forgerock.opendj.ldap.ResultCode;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.ByteSequence;
-import org.opends.server.util.Base64;
import static org.opends.messages.ExtensionMessages.*;
import static org.opends.server.extensions.ExtensionsConstants.*;
@@ -226,7 +226,7 @@
try
{
- byte[] decodedBytes = Base64.decode(storedPassword.toString());
+ byte[] decodedBytes = Base64.decode(storedPassword.toString()).toByteArray();
saltLength = decodedBytes.length - SHA384_LENGTH;
if (saltLength <= 0)
@@ -347,8 +347,8 @@
byte[] digestBytes;
try
{
- saltBytes = Base64.decode(authInfo);
- digestBytes = Base64.decode(authValue);
+ saltBytes = Base64.decode(authInfo).toByteArray();
+ digestBytes = Base64.decode(authValue).toByteArray();
}
catch (Exception e)
{
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/extensions/SaltedSHA512PasswordStorageScheme.java b/opendj-server-legacy/src/main/java/org/opends/server/extensions/SaltedSHA512PasswordStorageScheme.java
index 7157206..a344c72 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/extensions/SaltedSHA512PasswordStorageScheme.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/extensions/SaltedSHA512PasswordStorageScheme.java
@@ -21,6 +21,7 @@
import java.util.Random;
import org.forgerock.i18n.LocalizableMessage;
+import org.forgerock.opendj.ldap.Base64;
import org.forgerock.opendj.server.config.server.SaltedSHA512PasswordStorageSchemeCfg;
import org.opends.server.api.PasswordStorageScheme;
import org.forgerock.opendj.config.server.ConfigException;
@@ -30,7 +31,6 @@
import org.forgerock.opendj.ldap.ResultCode;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.ByteSequence;
-import org.opends.server.util.Base64;
import static org.opends.messages.ExtensionMessages.*;
import static org.opends.server.extensions.ExtensionsConstants.*;
@@ -226,7 +226,7 @@
try
{
- byte[] decodedBytes = Base64.decode(storedPassword.toString());
+ byte[] decodedBytes = Base64.decode(storedPassword.toString()).toByteArray();
saltLength = decodedBytes.length - SHA512_LENGTH;
if (saltLength <= 0)
@@ -347,8 +347,8 @@
byte[] digestBytes;
try
{
- saltBytes = Base64.decode(authInfo);
- digestBytes = Base64.decode(authValue);
+ saltBytes = Base64.decode(authInfo).toByteArray();
+ digestBytes = Base64.decode(authValue).toByteArray();
}
catch (Exception e)
{
@@ -455,6 +455,6 @@
Arrays.fill(passwordPlusSalt, (byte) 0);
return "{" + STORAGE_SCHEME_NAME_SALTED_SHA_512 + "}" +
- Base64.encode(digestPlusSalt);
+ Base64.encode(digestPlusSalt);
}
}
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/extensions/TripleDESPasswordStorageScheme.java b/opendj-server-legacy/src/main/java/org/opends/server/extensions/TripleDESPasswordStorageScheme.java
index 5e62d94..7d74e1a 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/extensions/TripleDESPasswordStorageScheme.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/extensions/TripleDESPasswordStorageScheme.java
@@ -17,6 +17,7 @@
package org.opends.server.extensions;
import org.forgerock.i18n.LocalizableMessage;
+import org.forgerock.opendj.ldap.Base64;
import org.forgerock.opendj.server.config.server.TripleDESPasswordStorageSchemeCfg;
import org.opends.server.api.PasswordStorageScheme;
import org.forgerock.opendj.config.server.ConfigException;
@@ -26,7 +27,6 @@
import org.forgerock.opendj.ldap.ResultCode;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.ByteSequence;
-import org.opends.server.util.Base64;
import java.util.Arrays;
@@ -152,10 +152,8 @@
{
try
{
- ByteString decryptedPassword =
- ByteString.wrap(cryptoManager.decrypt(
- Base64.decode(storedPassword.toString())));
- return plaintextPassword.equals(decryptedPassword);
+ return plaintextPassword.equals(ByteString.wrap(
+ cryptoManager.decrypt(Base64.decode(storedPassword.toString()).toByteArray())));
}
catch (Exception e)
{
@@ -178,7 +176,7 @@
try
{
byte[] decryptedPassword =
- cryptoManager.decrypt(Base64.decode(storedPassword.toString()));
+ cryptoManager.decrypt(Base64.decode(storedPassword.toString()).toByteArray());
return ByteString.wrap(decryptedPassword);
}
catch (Exception e)
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/loggers/TextAuditLogPublisher.java b/opendj-server-legacy/src/main/java/org/opends/server/loggers/TextAuditLogPublisher.java
index 80d4c84..9ef0318 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/loggers/TextAuditLogPublisher.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/loggers/TextAuditLogPublisher.java
@@ -28,6 +28,7 @@
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.opendj.config.server.ConfigChangeResult;
import org.forgerock.opendj.config.server.ConfigException;
+import org.forgerock.opendj.ldap.Base64;
import org.forgerock.opendj.ldap.ByteSequence;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.DN;
@@ -45,7 +46,6 @@
import org.opends.server.types.InitializationException;
import org.opends.server.types.Modification;
import org.opends.server.types.Operation;
-import org.opends.server.util.Base64;
import org.opends.server.util.StaticUtils;
import org.opends.server.util.TimeThread;
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/protocols/ldap/AddRequestProtocolOp.java b/opendj-server-legacy/src/main/java/org/opends/server/protocols/ldap/AddRequestProtocolOp.java
index 40a6c4d..4e27cef 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/protocols/ldap/AddRequestProtocolOp.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/protocols/ldap/AddRequestProtocolOp.java
@@ -12,7 +12,7 @@
* information: "Portions Copyright [year] [name of copyright owner]".
*
* Copyright 2006-2008 Sun Microsystems, Inc.
- * Portions Copyright 2013-2015 ForgeRock AS.
+ * Portions Copyright 2013-2016 ForgeRock AS.
*/
package org.opends.server.protocols.ldap;
@@ -23,9 +23,9 @@
import org.forgerock.i18n.slf4j.LocalizedLogger;
import org.forgerock.opendj.io.ASN1Writer;
+import org.forgerock.opendj.ldap.Base64;
import org.forgerock.opendj.ldap.ByteString;
import org.opends.server.types.RawAttribute;
-import org.opends.server.util.Base64;
import static org.opends.server.protocols.ldap.LDAPConstants.*;
import static org.opends.server.util.ServerConstants.*;
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/protocols/ldap/SearchResultEntryProtocolOp.java b/opendj-server-legacy/src/main/java/org/opends/server/protocols/ldap/SearchResultEntryProtocolOp.java
index 35a7b1c..dd609db 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/protocols/ldap/SearchResultEntryProtocolOp.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/protocols/ldap/SearchResultEntryProtocolOp.java
@@ -31,6 +31,7 @@
import org.forgerock.opendj.io.ASN1Writer;
import org.forgerock.opendj.ldap.AttributeDescription;
+import org.forgerock.opendj.ldap.Base64;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.DN;
import org.forgerock.opendj.ldap.schema.AttributeType;
@@ -41,7 +42,6 @@
import org.opends.server.types.Entry;
import org.opends.server.types.LDAPException;
import org.opends.server.types.SearchResultEntry;
-import org.opends.server.util.Base64;
/**
* This class defines the structures and methods for an LDAP search result entry
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/schema/SchemaFilesWriter.java b/opendj-server-legacy/src/main/java/org/opends/server/schema/SchemaFilesWriter.java
index 77491e1..b75c069 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/schema/SchemaFilesWriter.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/schema/SchemaFilesWriter.java
@@ -57,6 +57,7 @@
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.i18n.slf4j.LocalizedLogger;
import org.forgerock.opendj.ldap.AVA;
+import org.forgerock.opendj.ldap.Base64;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.DN;
import org.forgerock.opendj.ldap.ModificationType;
@@ -79,7 +80,6 @@
import org.opends.server.types.InitializationException;
import org.opends.server.types.LDIFExportConfig;
import org.opends.server.types.Modification;
-import org.opends.server.util.Base64;
import org.opends.server.util.BuildVersion;
import org.opends.server.util.LDIFException;
import org.opends.server.util.LDIFWriter;
@@ -481,7 +481,7 @@
// See OPENDJ-2792: the definition of the ds-cfg-csv-delimiter-char attribute type
// had a space accidentally added after the closing parenthesis.
// This was unfortunately interpreted as base64
- definition = ByteString.wrap(Base64.decode(definition.substring(2).trim())).toString();
+ definition = ByteString.wrap(Base64.decode(definition.substring(2).trim()).toByteArray()).toString();
}
else if (definition.startsWith(":"))
{
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/tools/ConfigureWindowsService.java b/opendj-server-legacy/src/main/java/org/opends/server/tools/ConfigureWindowsService.java
index 70609fa..e59ccdf 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/tools/ConfigureWindowsService.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/tools/ConfigureWindowsService.java
@@ -576,7 +576,7 @@
*/
public static int serviceState()
{
- return serviceState(NullOutputStream.printStream(), NullOutputStream.printStream());
+ return serviceState(NullOutputStream.nullPrintStream(), NullOutputStream.nullPrintStream());
}
/**
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPAuthenticationHandler.java b/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPAuthenticationHandler.java
index 1657009..6fe6ae3 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPAuthenticationHandler.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPAuthenticationHandler.java
@@ -56,6 +56,7 @@
import org.forgerock.i18n.LocalizableMessageDescriptor.Arg0;
import org.forgerock.i18n.LocalizableMessageDescriptor.Arg1;
import org.forgerock.i18n.LocalizableMessageDescriptor.Arg2;
+import org.forgerock.opendj.ldap.Base64;
import org.forgerock.opendj.ldap.ByteSequence;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.DecodeException;
@@ -66,7 +67,6 @@
import org.opends.server.protocols.ldap.LDAPMessage;
import org.opends.server.types.Control;
import org.opends.server.types.LDAPException;
-import org.opends.server.util.Base64;
import com.forgerock.opendj.cli.ClientException;
import com.forgerock.opendj.cli.ConsoleApplication;
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPCompare.java b/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPCompare.java
deleted file mode 100644
index 46c1dcd..0000000
--- a/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPCompare.java
+++ /dev/null
@@ -1,944 +0,0 @@
-/*
- * The contents of this file are subject to the terms of the Common Development and
- * Distribution License (the License). You may not use this file except in compliance with the
- * License.
- *
- * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
- * specific language governing permission and limitations under the License.
- *
- * When distributing Covered Software, include this CDDL Header Notice in each file and include
- * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
- * Header, with the fields enclosed by brackets [] replaced by your own identifying
- * information: "Portions Copyright [year] [name of copyright owner]".
- *
- * Copyright 2006-2010 Sun Microsystems, Inc.
- * Portions Copyright 2012-2016 ForgeRock AS.
- */
-package org.opends.server.tools;
-
-import static com.forgerock.opendj.cli.ArgumentConstants.*;
-import static com.forgerock.opendj.cli.CliMessages.INFO_DESCRIPTION_BINDPASSWORDFILE;
-import static com.forgerock.opendj.cli.Utils.*;
-import static com.forgerock.opendj.cli.CommonArguments.*;
-import static org.opends.messages.ToolMessages.*;
-import static org.opends.server.protocols.ldap.LDAPResultCode.*;
-import static org.opends.server.util.cli.LDAPConnectionArgumentParser.*;
-
-import java.io.BufferedReader;
-import java.io.FileReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.io.PrintStream;
-import java.io.Reader;
-import java.text.ParseException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import org.forgerock.i18n.LocalizableMessage;
-import org.forgerock.opendj.ldap.ByteString;
-import org.forgerock.opendj.ldap.DecodeException;
-import org.opends.server.controls.LDAPAssertionRequestControl;
-import org.opends.server.core.DirectoryServer;
-import org.opends.server.core.DirectoryServer.DirectoryServerVersionHandler;
-import org.opends.server.protocols.ldap.CompareRequestProtocolOp;
-import org.opends.server.protocols.ldap.CompareResponseProtocolOp;
-import org.opends.server.protocols.ldap.LDAPFilter;
-import org.opends.server.protocols.ldap.LDAPMessage;
-import org.opends.server.protocols.ldap.ProtocolOp;
-import org.opends.server.types.Control;
-import org.opends.server.types.LDAPException;
-import org.opends.server.types.NullOutputStream;
-import org.opends.server.util.Base64;
-import com.forgerock.opendj.cli.ArgumentException;
-import com.forgerock.opendj.cli.ArgumentParser;
-import com.forgerock.opendj.cli.BooleanArgument;
-import com.forgerock.opendj.cli.CliConstants;
-import com.forgerock.opendj.cli.ClientException;
-import com.forgerock.opendj.cli.FileBasedArgument;
-import com.forgerock.opendj.cli.IntegerArgument;
-import com.forgerock.opendj.cli.StringArgument;
-
-/**
- * This class provides a tool that can be used to issue compare requests to the
- * Directory Server.
- */
-public class LDAPCompare
-{
- /** The fully-qualified name of this class. */
- private static final String CLASS_NAME =
- "org.opends.server.tools.LDAPCompare";
-
-
- /** The message ID counter to use for requests. */
- private final AtomicInteger nextMessageID;
-
- /** The print stream to use for standard error. */
- private final PrintStream err;
- /** The print stream to use for standard output. */
- private final PrintStream out;
-
- /** Tells whether the command-line is being executed in script friendly mode or not. */
- private boolean isScriptFriendly;
-
-
- /**
- * Constructor for the LDAPCompare object.
- *
- * @param nextMessageID The message ID counter to use for requests.
- * @param out The print stream to use for standard output.
- * @param err The print stream to use for standard error.
- */
- public LDAPCompare(AtomicInteger nextMessageID, PrintStream out,
- PrintStream err)
- {
- this.nextMessageID = nextMessageID;
- this.out = out;
- this.err = err;
- }
-
- /**
- * Execute the compare request in the specified list of DNs.
- *
- * @param connection The connection to execute the request on.
- * @param attributeType The attribute type to compare.
- * @param attributeVal The attribute value to compare.
- * @param lines The list of DNs to compare the attribute in.
- * @param compareOptions The constraints for the compare request.
- * @return the LDAP result code for the operation
- *
- * @throws IOException If a problem occurs while communicating with the
- * Directory Server.
- *
- * @throws LDAPException If the server returns an error response.
- */
- public int readAndExecute(LDAPConnection connection, String attributeType,
- byte[] attributeVal, List<String> lines,
- LDAPCompareOptions compareOptions)
- throws IOException, LDAPException
- {
- int aggResultCode = SUCCESS;
- for(String line : lines)
- {
- int resultCode =
- executeCompare(connection, attributeType, attributeVal, line,
- compareOptions);
- aggResultCode = aggregateResultCode(aggResultCode, resultCode);
- }
- return aggResultCode;
- }
-
-
- /**
- * Read the specified DNs from the given reader
- * (file or stdin) and execute the given compare request.
- *
- * @param connection The connection to execute the request on.
- * @param attributeType The attribute type to compare.
- * @param attributeVal The attribute value to compare.
- * @param reader The reader to read the list of DNs from.
- * @param compareOptions The constraints for the compare request.
- * @return the LDAP result code for the operation
- *
- * @throws IOException If a problem occurs while communicating with the
- * Directory Server.
- *
- * @throws LDAPException If the server returns an error response.
- */
- public int readAndExecute(LDAPConnection connection, String attributeType,
- byte[] attributeVal, Reader reader,
- LDAPCompareOptions compareOptions)
- throws IOException, LDAPException
- {
- int aggResultCode = 0;
- BufferedReader in = new BufferedReader(reader);
- String line = null;
-
- while ((line = in.readLine()) != null)
- {
- int resultCode =
- executeCompare(connection, attributeType, attributeVal, line,
- compareOptions);
- aggResultCode = aggregateResultCode(aggResultCode, resultCode);
- }
- in.close();
- return aggResultCode;
- }
-
-
- /**
- * Aggregates a new result code to the existing aggregated result codes. This
- * method always overwrites the {@link LDAPResultCode#SUCCESS} and
- * {@link LDAPResultCode#COMPARE_TRUE} result codes with the new result code.
- * Then
- *
- * @param aggResultCodes
- * the aggregated result codes (a.k.a "accumulator")
- * @param newResultCode
- * the new result code to aggregate
- * @return the new aggregated result code
- */
- int aggregateResultCode(int aggResultCodes, int newResultCode)
- {
- if (aggResultCodes == SUCCESS || aggResultCodes == COMPARE_TRUE)
- {
- aggResultCodes = newResultCode;
- }
- else if (aggResultCodes == COMPARE_FALSE && newResultCode != COMPARE_TRUE)
- {
- aggResultCodes = newResultCode;
- }
- return aggResultCodes;
- }
-
-
- /**
- * Execute the compare request for the specified DN entry.
- *
- * @param connection The connection to execute the request on.
- * @param attributeType The attribute type to compare.
- * @param attributeVal The attribute value to compare.
- * @param line The DN to compare attribute in.
- * @param compareOptions The constraints for the compare request.
- * @return the LDAP result code for the operation
- *
- * @throws IOException If a problem occurs while communicating with the
- * Directory Server.
- *
- * @throws LDAPException If the server returns an error response.
- */
- private int executeCompare(LDAPConnection connection, String attributeType,
- byte[] attributeVal, String line,
- LDAPCompareOptions compareOptions)
- throws IOException, LDAPException
- {
- ArrayList<Control> controls = compareOptions.getControls();
- ByteString dnOctetStr = ByteString.valueOfUtf8(line);
- ByteString attrValOctetStr = ByteString.wrap(attributeVal);
-
- ProtocolOp protocolOp = new CompareRequestProtocolOp(dnOctetStr,
- attributeType, attrValOctetStr);
-
-
- if (!isScriptFriendly())
- {
- out.println(INFO_PROCESSING_COMPARE_OPERATION.get(
- attributeType, attrValOctetStr, dnOctetStr));
- }
-
- if(!compareOptions.showOperations())
- {
- LDAPMessage responseMessage = null;
- try
- {
- LDAPMessage message = new LDAPMessage(nextMessageID.getAndIncrement(),
- protocolOp, controls);
- connection.getLDAPWriter().writeMessage(message);
- responseMessage = connection.getLDAPReader().readMessage();
- } catch(DecodeException ae)
- {
- if (!compareOptions.continueOnError())
- {
- String message = LDAPToolUtils.getMessageForConnectionException(ae);
- throw new IOException(message, ae);
- }
- else
- {
- printWrappedText(err, INFO_OPERATION_FAILED.get("COMPARE"));
- printWrappedText(err, ae.getMessage());
- return OPERATIONS_ERROR;
- }
- }
-
- CompareResponseProtocolOp op =
- responseMessage.getCompareResponseProtocolOp();
- int resultCode = op.getResultCode();
- LocalizableMessage errorMessage = op.getErrorMessage();
-
- if(resultCode != COMPARE_TRUE && resultCode != COMPARE_FALSE
- && !compareOptions.continueOnError())
- {
- LocalizableMessage msg = INFO_OPERATION_FAILED.get("COMPARE");
- throw new LDAPException(resultCode, errorMessage, msg,
- op.getMatchedDN(), null);
- } else
- {
- if(resultCode == COMPARE_FALSE)
- {
- if (isScriptFriendly())
- {
- out.println(line+": "+COMPARE_FALSE);
- }
- else
- {
- out.println(INFO_COMPARE_OPERATION_RESULT_FALSE.get(line));
- }
- } else if(resultCode == COMPARE_TRUE)
- {
- if (isScriptFriendly())
- {
- out.println(line+": "+COMPARE_TRUE);
- }
- else
- {
- out.println(INFO_COMPARE_OPERATION_RESULT_TRUE.get(line));
- }
- } else
- {
- LocalizableMessage msg = INFO_OPERATION_FAILED.get("COMPARE");
- LDAPToolUtils.printErrorMessage(err, msg, resultCode, errorMessage,
- op.getMatchedDN());
- }
- }
- return resultCode;
- }
- return SUCCESS;
- }
-
- /**
- * The main method for LDAPCompare tool.
- *
- * @param args The command-line arguments provided to this program.
- */
- public static void main(String[] args)
- {
- int retCode = mainCompare(args, true, System.out, System.err);
- if(retCode != 0)
- {
- System.exit(filterExitCode(retCode));
- }
- }
-
- /**
- * Parses the provided command-line arguments and uses that information to
- * run the ldapcompare tool.
- *
- * @param args The command-line arguments provided to this program.
- *
- * @return The error code.
- */
- public static int mainCompare(String[] args)
- {
- return mainCompare(args, true, System.out, System.err);
- }
-
- /**
- * Parses the provided command-line arguments and uses that information to
- * run the ldapcompare tool.
- *
- * @param args The command-line arguments provided to this
- * program.
- * @param initializeServer Indicates whether to initialize the server.
- * @param outStream The output stream to use for standard output, or
- * <CODE>null</CODE> if standard output is not
- * needed.
- * @param errStream The output stream to use for standard error, or
- * <CODE>null</CODE> if standard error is not
- * needed.
- *
- * @return The error code.
- */
- public static int mainCompare(String[] args, boolean initializeServer,
- OutputStream outStream, OutputStream errStream)
- {
- PrintStream out = NullOutputStream.wrapOrNullStream(outStream);
- PrintStream err = NullOutputStream.wrapOrNullStream(errStream);
-
- LDAPConnectionOptions connectionOptions = new LDAPConnectionOptions();
- LDAPCompareOptions compareOptions = new LDAPCompareOptions();
- LDAPConnection connection = null;
-
- final BooleanArgument continueOnError;
- final BooleanArgument noop;
- final BooleanArgument saslExternal;
- final BooleanArgument showUsage;
- final BooleanArgument useCompareResultCode;
- final BooleanArgument startTLS;
- final BooleanArgument trustAll;
- final BooleanArgument useSSL;
- final BooleanArgument verbose;
- final FileBasedArgument bindPasswordFile;
- final FileBasedArgument keyStorePasswordFile;
- final FileBasedArgument trustStorePasswordFile;
- final IntegerArgument port;
- final IntegerArgument version;
- final StringArgument assertionFilter;
- final StringArgument bindDN;
- final StringArgument bindPassword;
- final StringArgument certNickname;
- final StringArgument controlStr;
- final StringArgument encodingStr;
- final StringArgument filename;
- final StringArgument hostName;
- final StringArgument keyStorePath;
- final StringArgument keyStorePassword;
- final StringArgument saslOptions;
- final StringArgument trustStorePath;
- final StringArgument trustStorePassword;
- final IntegerArgument connectTimeout;
- final StringArgument propertiesFileArgument;
- final BooleanArgument noPropertiesFileArgument;
- BooleanArgument scriptFriendlyArgument = null;
-
- final List<String> dnStrings = new ArrayList<> ();
- final String attributeType;
- final byte[] attributeVal;
- Reader rdr = null;
-
- // Create the command-line argument parser for use with this program.
- LocalizableMessage toolDescription = INFO_LDAPCOMPARE_TOOL_DESCRIPTION.get();
- ArgumentParser argParser = new ArgumentParser(CLASS_NAME, toolDescription,
- false, true, 1, 0,
- " \'attribute:value\' \"DN\" ...");
- argParser.setShortToolDescription(REF_SHORT_DESC_LDAPCOMPARE.get());
- argParser.setVersionHandler(new DirectoryServerVersionHandler());
-
- try
- {
- scriptFriendlyArgument =
- BooleanArgument.builder("script-friendly")
- .shortIdentifier('s')
- .description(INFO_DESCRIPTION_SCRIPT_FRIENDLY.get())
- .buildAndAddToParser(argParser);
- propertiesFileArgument =
- StringArgument.builder(OPTION_LONG_PROP_FILE_PATH)
- .description(INFO_DESCRIPTION_PROP_FILE_PATH.get())
- .valuePlaceholder(INFO_PROP_FILE_PATH_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- argParser.setFilePropertiesArgument(propertiesFileArgument);
-
- noPropertiesFileArgument =
- BooleanArgument.builder(OPTION_LONG_NO_PROP_FILE)
- .description(INFO_DESCRIPTION_NO_PROP_FILE.get())
- .buildAndAddToParser(argParser);
- argParser.setNoPropertiesFileArgument(noPropertiesFileArgument);
-
- hostName =
- StringArgument.builder(OPTION_LONG_HOST)
- .shortIdentifier(OPTION_SHORT_HOST)
- .description(INFO_DESCRIPTION_HOST.get())
- .defaultValue("localhost")
- .valuePlaceholder(INFO_HOST_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- port =
- IntegerArgument.builder(OPTION_LONG_PORT)
- .shortIdentifier(OPTION_SHORT_PORT)
- .description(INFO_DESCRIPTION_PORT.get())
- .range(1, 65535)
- .defaultValue(389)
- .valuePlaceholder(INFO_PORT_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- useSSL =
- BooleanArgument.builder(OPTION_LONG_USE_SSL)
- .shortIdentifier(OPTION_SHORT_USE_SSL)
- .description(INFO_DESCRIPTION_USE_SSL.get())
- .buildAndAddToParser(argParser);
- startTLS =
- BooleanArgument.builder(OPTION_LONG_START_TLS)
- .shortIdentifier(OPTION_SHORT_START_TLS)
- .description(INFO_DESCRIPTION_START_TLS.get())
- .buildAndAddToParser(argParser);
- bindDN =
- StringArgument.builder(OPTION_LONG_BINDDN)
- .shortIdentifier(OPTION_SHORT_BINDDN)
- .description(INFO_DESCRIPTION_BINDDN.get())
- .valuePlaceholder(INFO_BINDDN_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- bindPassword =
- StringArgument.builder(OPTION_LONG_BINDPWD)
- .shortIdentifier(OPTION_SHORT_BINDPWD)
- .description(INFO_DESCRIPTION_BINDPASSWORD.get())
- .valuePlaceholder(INFO_BINDPWD_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- bindPasswordFile =
- FileBasedArgument.builder(OPTION_LONG_BINDPWD_FILE)
- .shortIdentifier(OPTION_SHORT_BINDPWD_FILE)
- .description(INFO_DESCRIPTION_BINDPASSWORDFILE.get())
- .valuePlaceholder(INFO_BINDPWD_FILE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- filename =
- StringArgument.builder(OPTION_LONG_FILENAME)
- .shortIdentifier(OPTION_SHORT_FILENAME)
- .description(INFO_COMPARE_DESCRIPTION_FILENAME.get())
- .valuePlaceholder(INFO_FILE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- saslExternal =
- BooleanArgument.builder("useSASLExternal")
- .shortIdentifier('r')
- .description(INFO_DESCRIPTION_USE_SASL_EXTERNAL.get())
- .buildAndAddToParser(argParser);
- saslOptions =
- StringArgument.builder(OPTION_LONG_SASLOPTION)
- .shortIdentifier(OPTION_SHORT_SASLOPTION)
- .description(INFO_DESCRIPTION_SASL_PROPERTIES.get())
- .multiValued()
- .valuePlaceholder(INFO_SASL_OPTION_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
-
- trustAll = trustAllArgument();
- argParser.addArgument(trustAll);
-
- keyStorePath =
- StringArgument.builder(OPTION_LONG_KEYSTOREPATH)
- .shortIdentifier(OPTION_SHORT_KEYSTOREPATH)
- .description(INFO_DESCRIPTION_KEYSTOREPATH.get())
- .valuePlaceholder(INFO_KEYSTOREPATH_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- keyStorePassword =
- StringArgument.builder(OPTION_LONG_KEYSTORE_PWD)
- .shortIdentifier(OPTION_SHORT_KEYSTORE_PWD)
- .description(INFO_DESCRIPTION_KEYSTOREPASSWORD.get())
- .valuePlaceholder(INFO_KEYSTORE_PWD_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- keyStorePasswordFile =
- FileBasedArgument.builder(OPTION_LONG_KEYSTORE_PWD_FILE)
- .shortIdentifier(OPTION_SHORT_KEYSTORE_PWD_FILE)
- .description(INFO_DESCRIPTION_KEYSTOREPASSWORD_FILE.get())
- .valuePlaceholder(INFO_KEYSTORE_PWD_FILE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- certNickname =
- StringArgument.builder("certNickname")
- .shortIdentifier('N')
- .description(INFO_DESCRIPTION_CERT_NICKNAME.get())
- .valuePlaceholder(INFO_NICKNAME_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- trustStorePath =
- StringArgument.builder(OPTION_LONG_TRUSTSTOREPATH)
- .shortIdentifier(OPTION_SHORT_TRUSTSTOREPATH)
- .description(INFO_DESCRIPTION_TRUSTSTOREPATH.get())
- .valuePlaceholder(INFO_TRUSTSTOREPATH_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- trustStorePassword =
- StringArgument.builder(OPTION_LONG_TRUSTSTORE_PWD)
- .description(INFO_DESCRIPTION_TRUSTSTOREPASSWORD.get())
- .valuePlaceholder(INFO_TRUSTSTORE_PWD_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- trustStorePasswordFile =
- FileBasedArgument.builder(OPTION_LONG_TRUSTSTORE_PWD_FILE)
- .shortIdentifier(OPTION_SHORT_TRUSTSTORE_PWD_FILE)
- .description(INFO_DESCRIPTION_TRUSTSTOREPASSWORD_FILE.get())
- .valuePlaceholder(INFO_TRUSTSTORE_PWD_FILE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- assertionFilter =
- StringArgument.builder(OPTION_LONG_ASSERTION_FILE)
- .description(INFO_DESCRIPTION_ASSERTION_FILTER.get())
- .valuePlaceholder(INFO_ASSERTION_FILTER_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- controlStr =
- StringArgument.builder("control")
- .shortIdentifier('J')
- .description(INFO_DESCRIPTION_CONTROLS.get())
- .multiValued()
- .valuePlaceholder(INFO_LDAP_CONTROL_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- version =
- IntegerArgument.builder(OPTION_LONG_PROTOCOL_VERSION)
- .shortIdentifier(OPTION_SHORT_PROTOCOL_VERSION)
- .description(INFO_DESCRIPTION_VERSION.get())
- .defaultValue(3)
- .valuePlaceholder(INFO_PROTOCOL_VERSION_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- connectTimeout =
- IntegerArgument.builder(OPTION_LONG_CONNECT_TIMEOUT)
- .description(INFO_DESCRIPTION_CONNECTION_TIMEOUT.get())
- .lowerBound(0)
- .defaultValue(CliConstants.DEFAULT_LDAP_CONNECT_TIMEOUT)
- .valuePlaceholder(INFO_TIMEOUT_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- encodingStr =
- StringArgument.builder("encoding")
- .shortIdentifier('i')
- .description(INFO_DESCRIPTION_ENCODING.get())
- .valuePlaceholder(INFO_ENCODING_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- continueOnError =
- BooleanArgument.builder("continueOnError")
- .shortIdentifier('c')
- .description(INFO_DESCRIPTION_CONTINUE_ON_ERROR.get())
- .buildAndAddToParser(argParser);
- noop =
- BooleanArgument.builder(OPTION_LONG_DRYRUN)
- .shortIdentifier(OPTION_SHORT_DRYRUN)
- .description(INFO_DESCRIPTION_NOOP.get())
- .buildAndAddToParser(argParser);
-
- verbose = verboseArgument();
- argParser.addArgument(verbose);
-
- showUsage = showUsageArgument();
- argParser.addArgument(showUsage);
-
- useCompareResultCode =
- BooleanArgument.builder("useCompareResultCode")
- .shortIdentifier('m')
- .description(INFO_LDAPCOMPARE_DESCRIPTION_USE_COMPARE_RESULT.get())
- .buildAndAddToParser(argParser);
-
- argParser.setUsageArgument(showUsage, out);
- } catch (ArgumentException ae)
- {
- printWrappedText(err, ERR_CANNOT_INITIALIZE_ARGS.get(ae.getMessage()));
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
- // Parse the command-line arguments provided to this program.
- try
- {
- argParser.parseArguments(args);
- }
- catch (ArgumentException ae)
- {
- argParser.displayMessageAndUsageReference(err, ERR_ERROR_PARSING_ARGS.get(ae.getMessage()));
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
- // If we should just display usage or version information,
- // then print it and exit.
- if (argParser.usageOrVersionDisplayed())
- {
- return SUCCESS;
- }
-
- if (bindPassword.isPresent() && bindPasswordFile.isPresent())
- {
- printWrappedText(err, conflictingArgsErrorMessage(bindPassword, bindPasswordFile));
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
- ArrayList<String> attrAndDNStrings = argParser.getTrailingArguments();
-
- if(attrAndDNStrings.isEmpty())
- {
- printWrappedText(err, ERR_LDAPCOMPARE_NO_ATTR.get());
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
- // First element should be an attribute string.
- String attributeString = attrAndDNStrings.remove(0);
- // Rest are DN strings
- dnStrings.addAll(attrAndDNStrings);
-
- // If no DNs were provided, then exit with an error.
- if (dnStrings.isEmpty() && !filename.isPresent())
- {
- printWrappedText(err, ERR_LDAPCOMPARE_NO_DNS.get());
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
- // If trailing DNs were provided and the filename argument was also
- // provided, exit with an error.
- if (!dnStrings.isEmpty() && filename.isPresent())
- {
- printWrappedText(err, ERR_LDAPCOMPARE_FILENAME_AND_DNS.get());
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
- // parse the attribute string
- int idx = attributeString.indexOf(":");
- if(idx == -1)
- {
- printWrappedText(err, ERR_LDAPCOMPARE_INVALID_ATTR_STRING.get(attributeString));
- return CLIENT_SIDE_PARAM_ERROR;
- }
- attributeType = attributeString.substring(0, idx);
- String remainder = attributeString.substring(idx+1,
- attributeString.length());
- if (remainder.length() > 0)
- {
- char nextChar = remainder.charAt(0);
- if(nextChar == ':')
- {
- String base64 = remainder.substring(1, remainder.length());
- try
- {
- attributeVal = Base64.decode(base64);
- }
- catch (ParseException e)
- {
- printWrappedText(err, INFO_COMPARE_CANNOT_BASE64_DECODE_ASSERTION_VALUE.get());
- printWrappedText(err, e.getLocalizedMessage());
- return CLIENT_SIDE_PARAM_ERROR;
- }
- } else if(nextChar == '<')
- {
- try
- {
- String filePath = remainder.substring(1, remainder.length());
- attributeVal = LDAPToolUtils.readBytesFromFile(filePath, err);
- }
- catch (Exception e)
- {
- printWrappedText(err, INFO_COMPARE_CANNOT_READ_ASSERTION_VALUE_FROM_FILE.get(e));
- return CLIENT_SIDE_PARAM_ERROR;
- }
- } else
- {
- attributeVal = remainder.getBytes();
- }
- }
- else
- {
- attributeVal = remainder.getBytes();
- }
-
- String hostNameValue = hostName.getValue();
- int portNumber = 389;
- try
- {
- portNumber = port.getIntValue();
- } catch (ArgumentException ae)
- {
- argParser.displayMessageAndUsageReference(err, ae.getMessageObject());
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
- try
- {
- int versionNumber = version.getIntValue();
- if(versionNumber != 2 && versionNumber != 3)
- {
- printWrappedText(err, ERR_DESCRIPTION_INVALID_VERSION.get(versionNumber));
- return CLIENT_SIDE_PARAM_ERROR;
- }
- connectionOptions.setVersionNumber(versionNumber);
- } catch(ArgumentException ae)
- {
- argParser.displayMessageAndUsageReference(err, ae.getMessageObject());
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
-
- String bindDNValue = bindDN.getValue();
- String fileNameValue = filename.getValue();
- String bindPasswordValue;
- try
- {
- bindPasswordValue = getPasswordValue(
- bindPassword, bindPasswordFile, bindDNValue, out, err);
- }
- catch (ClientException ex)
- {
- printWrappedText(err, ex.getMessage());
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
- String keyStorePathValue = keyStorePath.getValue();
- String trustStorePathValue = trustStorePath.getValue();
-
- String keyStorePasswordValue = null;
- if (keyStorePassword.isPresent())
- {
- keyStorePasswordValue = keyStorePassword.getValue();
- }
- else if (keyStorePasswordFile.isPresent())
- {
- keyStorePasswordValue = keyStorePasswordFile.getValue();
- }
-
- String trustStorePasswordValue = null;
- if (trustStorePassword.isPresent())
- {
- trustStorePasswordValue = trustStorePassword.getValue();
- }
- else if (trustStorePasswordFile.isPresent())
- {
- trustStorePasswordValue = trustStorePasswordFile.getValue();
- }
-
- compareOptions.setShowOperations(noop.isPresent());
- compareOptions.setVerbose(verbose.isPresent());
- compareOptions.setContinueOnError(continueOnError.isPresent());
- compareOptions.setEncoding(encodingStr.getValue());
-
- if(controlStr.isPresent())
- {
- for (String ctrlString : controlStr.getValues())
- {
- Control ctrl = LDAPToolUtils.getControl(ctrlString, err);
- if(ctrl == null)
- {
- printWrappedText(err, ERR_TOOL_INVALID_CONTROL_STRING.get(ctrlString));
- return CLIENT_SIDE_PARAM_ERROR;
- }
- compareOptions.getControls().add(ctrl);
- }
- }
-
- if (assertionFilter.isPresent())
- {
- String filterString = assertionFilter.getValue();
- LDAPFilter filter;
- try
- {
- filter = LDAPFilter.decode(filterString);
-
- Control assertionControl =
- new LDAPAssertionRequestControl(true, filter);
- compareOptions.getControls().add(assertionControl);
- }
- catch (LDAPException le)
- {
- printWrappedText(err, ERR_LDAP_ASSERTION_INVALID_FILTER.get(le.getMessage()));
- return CLIENT_SIDE_PARAM_ERROR;
- }
- }
-
- // Set the connection options.
- // Parse the SASL properties.
- connectionOptions.setSASLExternal(saslExternal.isPresent());
- if(saslOptions.isPresent())
- {
- for (String saslOption : saslOptions.getValues())
- {
- boolean val;
- if(saslOption.startsWith("mech="))
- {
- val = connectionOptions.setSASLMechanism(saslOption);
- }
- else
- {
- val = connectionOptions.addSASLProperty(saslOption);
- }
- if(!val)
- {
- return CLIENT_SIDE_PARAM_ERROR;
- }
- }
- }
- connectionOptions.setUseSSL(useSSL.isPresent());
- connectionOptions.setStartTLS(startTLS.isPresent());
-
- if(connectionOptions.useSASLExternal())
- {
- if(!connectionOptions.useSSL() && !connectionOptions.useStartTLS())
- {
- printWrappedText(err, ERR_TOOL_SASLEXTERNAL_NEEDS_SSL_OR_TLS.get());
- return CLIENT_SIDE_PARAM_ERROR;
- }
- if(keyStorePathValue == null)
- {
- printWrappedText(err, ERR_TOOL_SASLEXTERNAL_NEEDS_KEYSTORE.get());
- return CLIENT_SIDE_PARAM_ERROR;
- }
- }
-
- LDAPCompare ldapCompare = null;
- try
- {
- if (initializeServer)
- {
- DirectoryServer.bootstrapClient();
- }
-
- // Connect to the specified host with the supplied userDN and password.
- SSLConnectionFactory sslConnectionFactory = null;
- if(connectionOptions.useSSL() || connectionOptions.useStartTLS())
- {
- String clientAlias;
- if (certNickname.isPresent())
- {
- clientAlias = certNickname.getValue();
- }
- else
- {
- clientAlias = null;
- }
-
- sslConnectionFactory = new SSLConnectionFactory();
- sslConnectionFactory.init(trustAll.isPresent(), keyStorePathValue,
- keyStorePasswordValue, clientAlias,
- trustStorePathValue, trustStorePasswordValue);
- connectionOptions.setSSLConnectionFactory(sslConnectionFactory);
- }
-
- AtomicInteger nextMessageID = new AtomicInteger(1);
- connection = new LDAPConnection(hostNameValue, portNumber,
- connectionOptions, out, err);
-
- int timeout = connectTimeout.getIntValue();
- connection.connectToHost(bindDNValue, bindPasswordValue, nextMessageID,
- timeout);
-
- ldapCompare = new LDAPCompare(nextMessageID, out, err);
- ldapCompare.isScriptFriendly = scriptFriendlyArgument.isPresent();
- if(fileNameValue == null && dnStrings.isEmpty())
- {
- // Read from stdin.
- rdr = new InputStreamReader(System.in);
- } else if(fileNameValue != null)
- {
- try
- {
- rdr = new FileReader(fileNameValue);
- }
- catch (Throwable t)
- {
- String details = t.getMessage();
- if (details == null)
- {
- details = t.toString();
- }
- printWrappedText(err, ERR_LDAPCOMPARE_ERROR_READING_FILE.get(fileNameValue, details));
- return CLIENT_SIDE_PARAM_ERROR;
- }
- }
- int resultCode;
- if(rdr != null)
- {
- resultCode =
- ldapCompare.readAndExecute(connection, attributeType, attributeVal,
- rdr, compareOptions);
- } else
- {
- resultCode =
- ldapCompare.readAndExecute(connection, attributeType, attributeVal,
- dnStrings, compareOptions);
- }
-
- if (useCompareResultCode.isPresent())
- {
- return resultCode;
- }
- return SUCCESS;
- } catch(LDAPException le)
- {
- LDAPToolUtils.printErrorMessage(
- err, le.getMessageObject(),
- le.getResultCode(),
- le.getMessageObject(),
- le.getMatchedDN());
- return le.getResultCode();
- } catch(LDAPConnectionException lce)
- {
- LDAPToolUtils.printErrorMessage(err,
- lce.getMessageObject(),
- lce.getResultCode(),
- lce.getMessageObject(),
- lce.getMatchedDN());
- return lce.getResultCode();
- } catch(Exception e)
- {
- printWrappedText(err, e.getMessage());
- return OPERATIONS_ERROR;
- } finally
- {
- if(connection != null)
- {
- if (ldapCompare != null)
- {
- connection.close(ldapCompare.nextMessageID);
- }
- else
- {
- connection.close(null);
- }
- }
- }
- }
-
- private boolean isScriptFriendly()
- {
- return isScriptFriendly;
- }
-}
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPCompareOptions.java b/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPCompareOptions.java
deleted file mode 100644
index 594dd66..0000000
--- a/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPCompareOptions.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * The contents of this file are subject to the terms of the Common Development and
- * Distribution License (the License). You may not use this file except in compliance with the
- * License.
- *
- * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
- * specific language governing permission and limitations under the License.
- *
- * When distributing Covered Software, include this CDDL Header Notice in each file and include
- * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
- * Header, with the fields enclosed by brackets [] replaced by your own identifying
- * information: "Portions Copyright [year] [name of copyright owner]".
- *
- * Copyright 2006-2008 Sun Microsystems, Inc.
- */
-package org.opends.server.tools;
-
-
-
-
-/**
- * This class defines options for all the compare operations used
- * by the ldapcompare tool.
- */
-public class LDAPCompareOptions extends LDAPToolOptions
-{
-
- /**
- * Creates the options instance.
- *
- */
- public LDAPCompareOptions()
- {
- }
-
-}
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPDelete.java b/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPDelete.java
deleted file mode 100644
index 319dd9c..0000000
--- a/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPDelete.java
+++ /dev/null
@@ -1,745 +0,0 @@
-/*
- * The contents of this file are subject to the terms of the Common Development and
- * Distribution License (the License). You may not use this file except in compliance with the
- * License.
- *
- * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
- * specific language governing permission and limitations under the License.
- *
- * When distributing Covered Software, include this CDDL Header Notice in each file and include
- * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
- * Header, with the fields enclosed by brackets [] replaced by your own identifying
- * information: "Portions Copyright [year] [name of copyright owner]".
- *
- * Copyright 2006-2010 Sun Microsystems, Inc.
- * Portions Copyright 2012-2016 ForgeRock AS.
- */
-package org.opends.server.tools;
-
-import static com.forgerock.opendj.cli.ArgumentConstants.*;
-import static com.forgerock.opendj.cli.CliMessages.INFO_DESCRIPTION_BINDPASSWORDFILE;
-import static com.forgerock.opendj.cli.Utils.*;
-import static com.forgerock.opendj.cli.CommonArguments.*;
-import static org.opends.messages.ToolMessages.*;
-import static org.opends.server.protocols.ldap.LDAPResultCode.*;
-import static org.opends.server.util.cli.LDAPConnectionArgumentParser.*;
-
-import java.io.BufferedReader;
-import java.io.FileReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.io.PrintStream;
-import java.io.Reader;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import org.forgerock.i18n.LocalizableMessage;
-import org.forgerock.i18n.slf4j.LocalizedLogger;
-import org.forgerock.opendj.ldap.ByteString;
-import org.forgerock.opendj.ldap.DecodeException;
-import org.opends.server.controls.SubtreeDeleteControl;
-import org.opends.server.core.DirectoryServer;
-import org.opends.server.core.DirectoryServer.DirectoryServerVersionHandler;
-import org.opends.server.protocols.ldap.DeleteRequestProtocolOp;
-import org.opends.server.protocols.ldap.DeleteResponseProtocolOp;
-import org.opends.server.protocols.ldap.LDAPMessage;
-import org.opends.server.protocols.ldap.ProtocolOp;
-import org.opends.server.types.Control;
-import org.opends.server.types.LDAPException;
-import org.opends.server.types.NullOutputStream;
-import com.forgerock.opendj.cli.ArgumentException;
-import com.forgerock.opendj.cli.ArgumentParser;
-import com.forgerock.opendj.cli.BooleanArgument;
-import com.forgerock.opendj.cli.CliConstants;
-import com.forgerock.opendj.cli.FileBasedArgument;
-import com.forgerock.opendj.cli.IntegerArgument;
-import com.forgerock.opendj.cli.StringArgument;
-
-/**
- * This class provides a tool that can be used to issue delete requests to the
- * Directory Server.
- */
-public class LDAPDelete
-{
- private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
-
- /** The fully-qualified name of this class. */
- private static final String CLASS_NAME = "org.opends.server.tools.LDAPDelete";
-
-
- /** The message ID counter to use for requests. */
- private final AtomicInteger nextMessageID;
-
- /** The print stream to use for standard error. */
- private final PrintStream err;
- /** The print stream to use for standard output. */
- private final PrintStream out;
-
-
-
- /**
- * Constructor for the LDAPDelete object.
- *
- * @param nextMessageID The next message ID to use for requests.
- * @param out The print stream to use for standard output.
- * @param err The print stream to use for standard error.
- */
- public LDAPDelete(AtomicInteger nextMessageID, PrintStream out,
- PrintStream err)
- {
- this.nextMessageID = nextMessageID;
- this.out = out;
- this.err = err;
- }
-
- /**
- * Execute the delete request on the specified list of DNs.
- *
- * @param connection The connection to use to execute the request.
- * @param lines The list of DNs to delete.
- * @param deleteOptions The constraints to use for this request.
- *
- * @throws IOException If a problem occurs while attempting to communicate
- * with the Directory Server.
- *
- * @throws LDAPException If the Directory Server returns an error response.
- */
- public void readAndExecute(LDAPConnection connection,
- List<String> lines,
- LDAPDeleteOptions deleteOptions)
- throws IOException, LDAPException
- {
- for(String line : lines)
- {
- executeDelete(connection, line, deleteOptions);
- }
- }
-
- /**
- * Read the specified DNs from the given reader
- * (file or stdin) and execute the given delete request.
- *
- * @param connection The connection to use to execute the request.
- * @param reader The reader to read the list of DNs from.
- * @param deleteOptions The constraints to use for this request.
- *
- * @throws IOException If a problem occurs while attempting to communicate
- * with the Directory Server.
- *
- * @throws LDAPException If the Directory Server returns an error response.
- */
- public void readAndExecute(LDAPConnection connection, Reader reader,
- LDAPDeleteOptions deleteOptions)
- throws IOException, LDAPException
- {
- BufferedReader in = new BufferedReader(reader);
- String line = null;
-
- while ((line = in.readLine()) != null)
- {
- executeDelete(connection, line, deleteOptions);
- }
- in.close();
- }
-
-
- /**
- * Execute the delete request for the specified DN.
- *
- * @param connection The connection to use to execute the request.
- * @param line The DN to delete.
- * @param deleteOptions The list of constraints for this request.
- *
- * @throws IOException If a problem occurs while attempting to communicate
- * with the Directory Server.
- *
- * @throws LDAPException If the Directory Server returns an error response.
- */
- private void executeDelete(LDAPConnection connection, String line,
- LDAPDeleteOptions deleteOptions)
- throws IOException, LDAPException
- {
- ArrayList<Control> controls = deleteOptions.getControls();
- ProtocolOp protocolOp = null;
- ByteString asn1OctetStr = ByteString.valueOfUtf8(line);
-
- protocolOp = new DeleteRequestProtocolOp(asn1OctetStr);
-
- out.println(INFO_PROCESSING_OPERATION.get("DELETE", asn1OctetStr));
- if(!deleteOptions.showOperations())
- {
- LDAPMessage message = new LDAPMessage(nextMessageID.getAndIncrement(),
- protocolOp, controls);
- LDAPMessage responseMessage = null;
- try
- {
- connection.getLDAPWriter().writeMessage(message);
- responseMessage = connection.getLDAPReader().readMessage();
- } catch(DecodeException ae)
- {
- logger.traceException(ae);
- if (!deleteOptions.continueOnError())
- {
- String msg = LDAPToolUtils.getMessageForConnectionException(ae);
- throw new IOException(msg, ae);
- }
- else
- {
- printWrappedText(err, INFO_OPERATION_FAILED.get("DELETE"));
- printWrappedText(err, ae.getMessage());
- return;
- }
- }
-
- DeleteResponseProtocolOp op =
- responseMessage.getDeleteResponseProtocolOp();
- int resultCode = op.getResultCode();
- LocalizableMessage errorMessage = op.getErrorMessage();
- if(resultCode != SUCCESS && resultCode != REFERRAL &&
- !deleteOptions.continueOnError())
- {
- LocalizableMessage msg = INFO_OPERATION_FAILED.get("DELETE");
- throw new LDAPException(resultCode, errorMessage, msg,
- op.getMatchedDN(), null);
- } else
- {
- if(resultCode != SUCCESS && resultCode != REFERRAL)
- {
- LocalizableMessage msg = INFO_OPERATION_FAILED.get("DELETE");
- LDAPToolUtils.printErrorMessage(err, msg, resultCode, errorMessage,
- op.getMatchedDN());
- } else
- {
- LocalizableMessage msg = INFO_OPERATION_SUCCESSFUL.get("DELETE", line);
- out.println(msg);
- }
- }
- }
- }
-
- /**
- * The main method for LDAPDelete tool.
- *
- * @param args The command-line arguments provided to this program.
- */
-
- public static void main(String[] args)
- {
- int retCode = mainDelete(args, true, System.out, System.err);
-
- if(retCode != 0)
- {
- System.exit(filterExitCode(retCode));
- }
- }
-
- /**
- * Parses the provided command-line arguments and uses that information to
- * run the ldapdelete tool.
- *
- * @param args The command-line arguments provided to this program.
- *
- * @return The error code.
- */
-
- public static int mainDelete(String[] args)
- {
- return mainDelete(args, true, System.out, System.err);
- }
-
- /**
- * Parses the provided command-line arguments and uses that information to
- * run the ldapdelete tool.
- *
- * @param args The command-line arguments provided to this
- * program.
- * @param initializeServer Indicates whether to initialize the server.
- * @param outStream The output stream to use for standard output, or
- * <CODE>null</CODE> if standard output is not
- * needed.
- * @param errStream The output stream to use for standard error, or
- * <CODE>null</CODE> if standard error is not
- * needed.
- *
- * @return The error code.
- */
-
- public static int mainDelete(String[] args, boolean initializeServer,
- OutputStream outStream, OutputStream errStream)
- {
- PrintStream out = NullOutputStream.wrapOrNullStream(outStream);
- PrintStream err = NullOutputStream.wrapOrNullStream(errStream);
-
- LDAPConnectionOptions connectionOptions = new LDAPConnectionOptions();
- LDAPDeleteOptions deleteOptions = new LDAPDeleteOptions();
- LDAPConnection connection = null;
-
- final BooleanArgument continueOnError;
- final BooleanArgument deleteSubtree;
- final BooleanArgument noop;
- final BooleanArgument saslExternal;
- final BooleanArgument showUsage;
- final BooleanArgument startTLS;
- final BooleanArgument trustAll;
- final BooleanArgument useSSL;
- final BooleanArgument verbose;
- final FileBasedArgument bindPasswordFile;
- final FileBasedArgument keyStorePasswordFile;
- final FileBasedArgument trustStorePasswordFile;
- final IntegerArgument port;
- final IntegerArgument version;
- final StringArgument bindDN;
- final StringArgument bindPassword;
- final StringArgument certNickname;
- final StringArgument controlStr;
- final StringArgument encodingStr;
- final StringArgument filename;
- final StringArgument hostName;
- final StringArgument keyStorePath;
- final StringArgument keyStorePassword;
- final StringArgument saslOptions;
- final StringArgument trustStorePath;
- final StringArgument trustStorePassword;
- final IntegerArgument connectTimeout;
- final StringArgument propertiesFileArgument;
- final BooleanArgument noPropertiesFileArgument;
-
- Reader rdr = null;
- List<String> dnStrings = new ArrayList<>();
-
- // Create the command-line argument parser for use with this program.
- LocalizableMessage toolDescription = INFO_LDAPDELETE_TOOL_DESCRIPTION.get();
- ArgumentParser argParser = new ArgumentParser(CLASS_NAME, toolDescription,
- false, true, 0, 1, "\"DN\"");
- argParser.setShortToolDescription(REF_SHORT_DESC_LDAPDELETE.get());
- argParser.setVersionHandler(new DirectoryServerVersionHandler());
- try
- {
- propertiesFileArgument =
- StringArgument.builder(OPTION_LONG_PROP_FILE_PATH)
- .description(INFO_DESCRIPTION_PROP_FILE_PATH.get())
- .valuePlaceholder(INFO_PROP_FILE_PATH_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- argParser.setFilePropertiesArgument(propertiesFileArgument);
-
- noPropertiesFileArgument =
- BooleanArgument.builder(OPTION_LONG_NO_PROP_FILE)
- .description(INFO_DESCRIPTION_NO_PROP_FILE.get())
- .buildAndAddToParser(argParser);
- argParser.setNoPropertiesFileArgument(noPropertiesFileArgument);
-
- hostName =
- StringArgument.builder(OPTION_LONG_HOST)
- .shortIdentifier(OPTION_SHORT_HOST)
- .description(INFO_DESCRIPTION_HOST.get())
- .defaultValue("localhost")
- .valuePlaceholder(INFO_HOST_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- port =
- IntegerArgument.builder(OPTION_LONG_PORT)
- .shortIdentifier(OPTION_SHORT_PORT)
- .description(INFO_DESCRIPTION_PORT.get())
- .range(1, 65535)
- .defaultValue(389)
- .valuePlaceholder(INFO_PORT_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- useSSL =
- BooleanArgument.builder(OPTION_LONG_USE_SSL)
- .shortIdentifier(OPTION_SHORT_USE_SSL)
- .description(INFO_DESCRIPTION_USE_SSL.get())
- .buildAndAddToParser(argParser);
- startTLS =
- BooleanArgument.builder(OPTION_LONG_START_TLS)
- .shortIdentifier(OPTION_SHORT_START_TLS)
- .description(INFO_DESCRIPTION_START_TLS.get())
- .buildAndAddToParser(argParser);
- bindDN =
- StringArgument.builder(OPTION_LONG_BINDDN)
- .shortIdentifier(OPTION_SHORT_BINDDN)
- .description(INFO_DESCRIPTION_BINDDN.get())
- .valuePlaceholder(INFO_BINDDN_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- bindPassword =
- StringArgument.builder(OPTION_LONG_BINDPWD)
- .shortIdentifier(OPTION_SHORT_BINDPWD)
- .description(INFO_DESCRIPTION_BINDPASSWORD.get())
- .valuePlaceholder(INFO_BINDPWD_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- bindPasswordFile =
- FileBasedArgument.builder(OPTION_LONG_BINDPWD_FILE)
- .shortIdentifier(OPTION_SHORT_BINDPWD_FILE)
- .description(INFO_DESCRIPTION_BINDPASSWORDFILE.get())
- .valuePlaceholder(INFO_BINDPWD_FILE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- filename =
- StringArgument.builder(OPTION_LONG_FILENAME)
- .shortIdentifier(OPTION_SHORT_FILENAME)
- .description(INFO_DELETE_DESCRIPTION_FILENAME.get())
- .valuePlaceholder(INFO_FILE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- saslExternal =
- BooleanArgument.builder("useSASLExternal")
- .shortIdentifier('r')
- .description(INFO_DESCRIPTION_USE_SASL_EXTERNAL.get())
- .buildAndAddToParser(argParser);
- saslOptions =
- StringArgument.builder(OPTION_LONG_SASLOPTION)
- .shortIdentifier(OPTION_SHORT_SASLOPTION)
- .description(INFO_DESCRIPTION_SASL_PROPERTIES.get())
- .multiValued()
- .valuePlaceholder(INFO_SASL_OPTION_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
-
- trustAll = trustAllArgument();
- argParser.addArgument(trustAll);
-
- keyStorePath =
- StringArgument.builder(OPTION_LONG_KEYSTOREPATH)
- .shortIdentifier(OPTION_SHORT_KEYSTOREPATH)
- .description(INFO_DESCRIPTION_KEYSTOREPATH.get())
- .valuePlaceholder(INFO_KEYSTOREPATH_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- keyStorePassword =
- StringArgument.builder(OPTION_LONG_KEYSTORE_PWD)
- .shortIdentifier(OPTION_SHORT_KEYSTORE_PWD)
- .description(INFO_DESCRIPTION_KEYSTOREPASSWORD.get())
- .valuePlaceholder(INFO_KEYSTORE_PWD_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- keyStorePasswordFile =
- FileBasedArgument.builder(OPTION_LONG_KEYSTORE_PWD_FILE)
- .shortIdentifier(OPTION_SHORT_KEYSTORE_PWD_FILE)
- .description(INFO_DESCRIPTION_KEYSTOREPASSWORD_FILE.get())
- .valuePlaceholder(INFO_KEYSTORE_PWD_FILE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- certNickname =
- StringArgument.builder("certNickname")
- .shortIdentifier('N')
- .description(INFO_DESCRIPTION_CERT_NICKNAME.get())
- .valuePlaceholder(INFO_NICKNAME_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- trustStorePath =
- StringArgument.builder(OPTION_LONG_TRUSTSTOREPATH)
- .shortIdentifier(OPTION_SHORT_TRUSTSTOREPATH)
- .description(INFO_DESCRIPTION_TRUSTSTOREPATH.get())
- .valuePlaceholder(INFO_TRUSTSTOREPATH_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- trustStorePassword =
- StringArgument.builder(OPTION_LONG_TRUSTSTORE_PWD)
- .description(INFO_DESCRIPTION_TRUSTSTOREPASSWORD.get())
- .valuePlaceholder(INFO_TRUSTSTORE_PWD_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- trustStorePasswordFile =
- FileBasedArgument.builder(OPTION_LONG_TRUSTSTORE_PWD_FILE)
- .shortIdentifier(OPTION_SHORT_TRUSTSTORE_PWD_FILE)
- .description(INFO_DESCRIPTION_TRUSTSTOREPASSWORD_FILE.get())
- .valuePlaceholder(INFO_TRUSTSTORE_PWD_FILE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- deleteSubtree =
- BooleanArgument.builder("deleteSubtree")
- .shortIdentifier('x')
- .description(INFO_DELETE_DESCRIPTION_DELETE_SUBTREE.get())
- .buildAndAddToParser(argParser);
- controlStr =
- StringArgument.builder("control")
- .shortIdentifier('J')
- .description(INFO_DESCRIPTION_CONTROLS.get())
- .multiValued()
- .valuePlaceholder(INFO_LDAP_CONTROL_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- version =
- IntegerArgument.builder(OPTION_LONG_PROTOCOL_VERSION)
- .shortIdentifier(OPTION_SHORT_PROTOCOL_VERSION)
- .description(INFO_DESCRIPTION_VERSION.get())
- .defaultValue(3)
- .valuePlaceholder(INFO_PROTOCOL_VERSION_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- connectTimeout =
- IntegerArgument.builder(OPTION_LONG_CONNECT_TIMEOUT)
- .description(INFO_DESCRIPTION_CONNECTION_TIMEOUT.get())
- .lowerBound(0)
- .defaultValue(CliConstants.DEFAULT_LDAP_CONNECT_TIMEOUT)
- .valuePlaceholder(INFO_TIMEOUT_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- encodingStr =
- StringArgument.builder(OPTION_LONG_ENCODING)
- .shortIdentifier('i')
- .description(INFO_DESCRIPTION_ENCODING.get())
- .valuePlaceholder(INFO_ENCODING_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- continueOnError =
- BooleanArgument.builder("continueOnError")
- .shortIdentifier('c')
- .description(INFO_DESCRIPTION_CONTINUE_ON_ERROR.get())
- .buildAndAddToParser(argParser);
- noop =
- BooleanArgument.builder(OPTION_LONG_DRYRUN)
- .shortIdentifier(OPTION_SHORT_DRYRUN)
- .description(INFO_DESCRIPTION_NOOP.get())
- .buildAndAddToParser(argParser);
-
- verbose = verboseArgument();
- argParser.addArgument(verbose);
-
- showUsage = showUsageArgument();
- argParser.addArgument(showUsage);
- argParser.setUsageArgument(showUsage, out);
- } catch (ArgumentException ae)
- {
- printWrappedText(err, ERR_CANNOT_INITIALIZE_ARGS.get(ae.getMessage()));
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
- // Parse the command-line arguments provided to this program.
- try
- {
- argParser.parseArguments(args);
- }
- catch (ArgumentException ae)
- {
- argParser.displayMessageAndUsageReference(err, ERR_ERROR_PARSING_ARGS.get(ae.getMessage()));
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
- // If we should just display usage or version information,
- // then it has already been done so just exit.
- if (argParser.usageOrVersionDisplayed())
- {
- return 0;
- }
-
- if (bindPassword.isPresent() && bindPasswordFile.isPresent())
- {
- printWrappedText(err, conflictingArgsErrorMessage(bindPassword, bindPasswordFile));
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
-
- String hostNameValue = hostName.getValue();
- int portNumber = 389;
- try
- {
- portNumber = port.getIntValue();
- } catch(ArgumentException ae)
- {
- logger.traceException(ae);
- argParser.displayMessageAndUsageReference(err, ae.getMessageObject());
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
- try
- {
- int versionNumber = version.getIntValue();
- if(versionNumber != 2 && versionNumber != 3)
- {
- printWrappedText(err, ERR_DESCRIPTION_INVALID_VERSION.get(versionNumber));
- return CLIENT_SIDE_PARAM_ERROR;
- }
- connectionOptions.setVersionNumber(versionNumber);
- } catch(ArgumentException ae)
- {
- logger.traceException(ae);
- argParser.displayMessageAndUsageReference(err, ae.getMessageObject());
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
- String bindDNValue = bindDN.getValue();
- String fileNameValue = filename.getValue();
- String bindPasswordValue;
- try
- {
- bindPasswordValue = getPasswordValue(
- bindPassword, bindPasswordFile, bindDNValue, out, err);
- }
- catch (Exception ex)
- {
- logger.traceException(ex);
- printWrappedText(err, ex.getMessage());
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
- String keyStorePathValue = keyStorePath.getValue();
- String trustStorePathValue = trustStorePath.getValue();
-
- String keyStorePasswordValue = null;
- if (keyStorePassword.isPresent())
- {
- keyStorePasswordValue = keyStorePassword.getValue();
- }
- else if (keyStorePasswordFile.isPresent())
- {
- keyStorePasswordValue = keyStorePasswordFile.getValue();
- }
-
- String trustStorePasswordValue = null;
- if (trustStorePassword.isPresent())
- {
- trustStorePasswordValue = trustStorePassword.getValue();
- }
- else if (trustStorePasswordFile.isPresent())
- {
- trustStorePasswordValue = trustStorePasswordFile.getValue();
- }
-
- deleteOptions.setShowOperations(noop.isPresent());
- deleteOptions.setVerbose(verbose.isPresent());
- deleteOptions.setContinueOnError(continueOnError.isPresent());
- deleteOptions.setEncoding(encodingStr.getValue());
- deleteOptions.setDeleteSubtree(deleteSubtree.isPresent());
-
- if(controlStr.isPresent())
- {
- for (String ctrlString : controlStr.getValues())
- {
- Control ctrl = LDAPToolUtils.getControl(ctrlString, err);
- if(ctrl == null)
- {
- printWrappedText(err, ERR_TOOL_INVALID_CONTROL_STRING.get(ctrlString));
- return CLIENT_SIDE_PARAM_ERROR;
- }
- deleteOptions.getControls().add(ctrl);
- }
- }
-
- if(deleteOptions.getDeleteSubtree())
- {
- Control control = new SubtreeDeleteControl(false);
- deleteOptions.getControls().add(control);
- }
-
- ArrayList<String> trailingArgs = argParser.getTrailingArguments();
- dnStrings.addAll(trailingArgs);
-
- // Set the connection options.
- // Parse the SASL properties.
- connectionOptions.setSASLExternal(saslExternal.isPresent());
- if(saslOptions.isPresent())
- {
- for (String saslOption : saslOptions.getValues())
- {
- boolean val = saslOption.startsWith("mech=")
- ? connectionOptions.setSASLMechanism(saslOption)
- : connectionOptions.addSASLProperty(saslOption);
- if (!val)
- {
- return CLIENT_SIDE_PARAM_ERROR;
- }
- }
- }
- connectionOptions.setUseSSL(useSSL.isPresent());
- connectionOptions.setStartTLS(startTLS.isPresent());
-
- if(connectionOptions.useSASLExternal())
- {
- if(!connectionOptions.useSSL() && !connectionOptions.useStartTLS())
- {
- printWrappedText(err, ERR_TOOL_SASLEXTERNAL_NEEDS_SSL_OR_TLS.get());
- return CLIENT_SIDE_PARAM_ERROR;
- }
- if(keyStorePathValue == null)
- {
- printWrappedText(err, ERR_TOOL_SASLEXTERNAL_NEEDS_KEYSTORE.get());
- return CLIENT_SIDE_PARAM_ERROR;
- }
- }
-
- LDAPDelete ldapDelete = null;
- try
- {
- if (initializeServer)
- {
- DirectoryServer.bootstrapClient();
- }
-
- // Connect to the specified host with the supplied userDN and password.
- SSLConnectionFactory sslConnectionFactory = null;
- if(connectionOptions.useSSL() || connectionOptions.useStartTLS())
- {
- String clientAlias;
- if (certNickname.isPresent())
- {
- clientAlias = certNickname.getValue();
- }
- else
- {
- clientAlias = null;
- }
-
- sslConnectionFactory = new SSLConnectionFactory();
- sslConnectionFactory.init(trustAll.isPresent(), keyStorePathValue,
- keyStorePasswordValue, clientAlias,
- trustStorePathValue, trustStorePasswordValue);
- connectionOptions.setSSLConnectionFactory(sslConnectionFactory);
- }
-
- AtomicInteger nextMessageID = new AtomicInteger(1);
- connection = new LDAPConnection(hostNameValue, portNumber,
- connectionOptions, out, err);
- int timeout = connectTimeout.getIntValue();
- connection.connectToHost(bindDNValue, bindPasswordValue, nextMessageID,
- timeout);
-
- ldapDelete = new LDAPDelete(nextMessageID, out, err);
- if(fileNameValue == null && dnStrings.isEmpty())
- {
- // Read from stdin.
- rdr = new InputStreamReader(System.in);
- } else if(fileNameValue != null)
- {
- rdr = new FileReader(fileNameValue);
- }
-
- if(rdr != null)
- {
- ldapDelete.readAndExecute(connection, rdr, deleteOptions);
- } else
- {
- ldapDelete.readAndExecute(connection, dnStrings, deleteOptions);
- }
- } catch(LDAPException le)
- {
- logger.traceException(le);
- LDAPToolUtils.printErrorMessage(err, le.getMessageObject(),
- le.getResultCode(),
- le.getErrorMessage(),
- le.getMatchedDN());
- return le.getResultCode();
- } catch(LDAPConnectionException lce)
- {
- logger.traceException(lce);
- LDAPToolUtils.printErrorMessage(err, lce.getMessageObject(),
- lce.getResultCode(),
- lce.getErrorMessage(),
- lce.getMatchedDN());
- return lce.getResultCode();
- }
- catch(ArgumentException e)
- {
- argParser.displayMessageAndUsageReference(err, e.getMessageObject());
- return 1;
- }
- catch (Exception e)
- {
- logger.traceException(e);
- printWrappedText(err, e.getMessage());
- return 1;
- } finally
- {
- if(connection != null)
- {
- if (ldapDelete == null)
- {
- connection.close(null);
- }
- else
- {
- connection.close(ldapDelete.nextMessageID);
- }
- }
- }
- return 0;
- }
-
-}
-
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPDeleteOptions.java b/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPDeleteOptions.java
deleted file mode 100644
index 2d6cd59..0000000
--- a/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPDeleteOptions.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * The contents of this file are subject to the terms of the Common Development and
- * Distribution License (the License). You may not use this file except in compliance with the
- * License.
- *
- * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
- * specific language governing permission and limitations under the License.
- *
- * When distributing Covered Software, include this CDDL Header Notice in each file and include
- * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
- * Header, with the fields enclosed by brackets [] replaced by your own identifying
- * information: "Portions Copyright [year] [name of copyright owner]".
- *
- * Copyright 2006-2008 Sun Microsystems, Inc.
- * Portions Copyright 2015 ForgeRock AS.
- */
-package org.opends.server.tools;
-
-
-
-
-/**
- * This class defines options for all the delete operations used
- * by the ldapdelete tool.
- */
-public class LDAPDeleteOptions extends LDAPToolOptions
-{
-
- private boolean deleteSubtree;
-
- /**
- * Creates the options instance.
- *
- */
- public LDAPDeleteOptions()
- {
- }
-
- /**
- * Set whether to delete the entire subtree or not.
- *
- * @param deleteSubtree Indicates whether to delete the entire subtree.
- */
- public void setDeleteSubtree(boolean deleteSubtree)
- {
- this.deleteSubtree = deleteSubtree;
- }
-
- /**
- * Get the value of the deleteSubtree flag.
- *
- * @return <CODE>true</CODE> if the subtree delete control should be
- * included in the request, or <CODE>false</CODE> if not.
- */
- public boolean getDeleteSubtree()
- {
- return deleteSubtree;
- }
-}
-
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPModify.java b/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPModify.java
deleted file mode 100644
index 1251d6c..0000000
--- a/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPModify.java
+++ /dev/null
@@ -1,1085 +0,0 @@
-/*
- * The contents of this file are subject to the terms of the Common Development and
- * Distribution License (the License). You may not use this file except in compliance with the
- * License.
- *
- * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
- * specific language governing permission and limitations under the License.
- *
- * When distributing Covered Software, include this CDDL Header Notice in each file and include
- * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
- * Header, with the fields enclosed by brackets [] replaced by your own identifying
- * information: "Portions Copyright [year] [name of copyright owner]".
- *
- * Copyright 2006-2010 Sun Microsystems, Inc.
- * Portions Copyright 2012 profiq, s.r.o.
- * Portions Copyright 2012-2016 ForgeRock AS.
- */
-package org.opends.server.tools;
-
-import static com.forgerock.opendj.cli.ArgumentConstants.*;
-import static com.forgerock.opendj.cli.CliMessages.INFO_DESCRIPTION_BINDPASSWORDFILE;
-import static com.forgerock.opendj.cli.Utils.*;
-import static com.forgerock.opendj.cli.CommonArguments.*;
-import static org.opends.messages.ToolMessages.*;
-import static org.opends.server.protocols.ldap.LDAPResultCode.*;
-import static org.opends.server.util.ServerConstants.*;
-import static org.opends.server.util.cli.LDAPConnectionArgumentParser.*;
-
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.PrintStream;
-import java.util.*;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import org.forgerock.i18n.LocalizableMessage;
-import org.forgerock.i18n.slf4j.LocalizedLogger;
-import org.forgerock.opendj.ldap.ByteString;
-import org.forgerock.opendj.ldap.DN;
-import org.forgerock.opendj.ldap.DecodeException;
-import org.forgerock.opendj.ldap.ResultCode;
-import org.opends.server.controls.*;
-import org.opends.server.core.DirectoryServer;
-import org.opends.server.core.DirectoryServer.DirectoryServerVersionHandler;
-import org.opends.server.plugins.ChangeNumberControlPlugin;
-import org.opends.server.protocols.ldap.AddRequestProtocolOp;
-import org.opends.server.protocols.ldap.AddResponseProtocolOp;
-import org.opends.server.protocols.ldap.DeleteRequestProtocolOp;
-import org.opends.server.protocols.ldap.DeleteResponseProtocolOp;
-import org.opends.server.protocols.ldap.ExtendedResponseProtocolOp;
-import org.opends.server.protocols.ldap.LDAPAttribute;
-import org.opends.server.protocols.ldap.LDAPConstants;
-import org.opends.server.protocols.ldap.LDAPControl;
-import org.opends.server.protocols.ldap.LDAPFilter;
-import org.opends.server.protocols.ldap.LDAPMessage;
-import org.opends.server.protocols.ldap.ModifyDNRequestProtocolOp;
-import org.opends.server.protocols.ldap.ModifyDNResponseProtocolOp;
-import org.opends.server.protocols.ldap.ModifyRequestProtocolOp;
-import org.opends.server.protocols.ldap.ModifyResponseProtocolOp;
-import org.opends.server.protocols.ldap.ProtocolOp;
-import org.opends.server.types.*;
-import org.opends.server.util.AddChangeRecordEntry;
-import org.opends.server.util.ChangeRecordEntry;
-import org.opends.server.util.LDIFException;
-import org.opends.server.util.LDIFReader;
-import org.opends.server.util.ModifyChangeRecordEntry;
-import org.opends.server.util.ModifyDNChangeRecordEntry;
-
-import com.forgerock.opendj.cli.ArgumentException;
-import com.forgerock.opendj.cli.ArgumentParser;
-import com.forgerock.opendj.cli.BooleanArgument;
-import com.forgerock.opendj.cli.CliConstants;
-import com.forgerock.opendj.cli.FileBasedArgument;
-import com.forgerock.opendj.cli.IntegerArgument;
-import com.forgerock.opendj.cli.StringArgument;
-
-/**
- * This class provides a tool that can be used to issue modify requests to the
- * Directory Server.
- */
-public class LDAPModify
-{
- private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
-
- /**
- * The fully-qualified name of this class.
- */
- private static final String CLASS_NAME = "org.opends.server.tools.LDAPModify";
-
- /** The message ID counter to use for requests. */
- private final AtomicInteger nextMessageID;
-
- /** The print stream to use for standard error. */
- private final PrintStream err;
-
- /** The print stream to use for standard output. */
- private final PrintStream out;
-
- /**
- * Constructor for the LDAPModify object.
- *
- * @param nextMessageID The message ID counter to use for requests.
- * @param out The print stream to use for standard output.
- * @param err The print stream to use for standard error.
- */
- public LDAPModify(AtomicInteger nextMessageID, PrintStream out,
- PrintStream err)
- {
- this.nextMessageID = nextMessageID;
- this.out = out;
- this.err = err;
- }
-
-
- /**
- * Read the specified change records from the given input stream
- * (file or stdin) and execute the given modify request.
- *
- * @param connection The connection to use for this modify request.
- * @param fileNameValue Name of the file from which to read. If null,
- * input will be read from <code>System.in</code>.
- * @param modifyOptions The constraints for the modify request.
- *
- * @throws IOException If a problem occurs while attempting to communicate
- * with the Directory Server.
- *
- * @throws LDAPException If the Directory Server returns an error response.
- */
- public void readAndExecute(LDAPConnection connection, String fileNameValue,
- LDAPModifyOptions modifyOptions)
- throws IOException, LDAPException
- {
- ArrayList<Control> controls = modifyOptions.getControls();
- LDIFReader reader;
-
- // Create an LDIF import configuration to do this and then get the reader.
-
- try
- {
- InputStream is = System.in;
- if(fileNameValue != null)
- {
- is = new FileInputStream(fileNameValue);
- }
-
- LDIFImportConfig importConfig = new LDIFImportConfig(is);
- importConfig.setValidateSchema(false);
- reader = new LDIFReader(importConfig);
- } catch (Exception e)
- {
- logger.traceException(e);
- LocalizableMessage message =
- ERR_LDIF_FILE_CANNOT_OPEN_FOR_READ.get(fileNameValue,
- e.getLocalizedMessage());
- throw new FileNotFoundException(message.toString());
- }
-
- // Set this for error messages
- if (fileNameValue == null)
- {
- fileNameValue = "Console";
- }
-
- while (true)
- {
- ChangeRecordEntry entry = null;
-
- try
- {
- entry = reader.readChangeRecord(modifyOptions.getDefaultAdd());
- } catch (LDIFException le)
- {
- logger.traceException(le);
- if (!modifyOptions.continueOnError())
- {
- try
- {
- reader.close();
- }
- catch (Exception e)
- {
- logger.traceException(e);
- }
-
- LocalizableMessage message = ERR_LDIF_FILE_INVALID_LDIF_ENTRY.get(
- le.getLineNumber(), fileNameValue, le);
- throw new IOException(message.toString());
- }
- else
- {
- printWrappedText(err, ERR_LDIF_FILE_INVALID_LDIF_ENTRY.get(le.getLineNumber(), fileNameValue, le));
- continue;
- }
- } catch (Exception e)
- {
- logger.traceException(e);
-
- if (!modifyOptions.continueOnError())
- {
- try
- {
- reader.close();
- }
- catch (Exception e2)
- {
- logger.traceException(e2);
- }
-
- LocalizableMessage message = ERR_LDIF_FILE_READ_ERROR.get(fileNameValue, e);
- throw new IOException(message.toString());
- }
- else
- {
- printWrappedText(err, ERR_LDIF_FILE_READ_ERROR.get(fileNameValue, e));
- continue;
- }
- }
-
- // If the entry is null, then we have reached the end of the config file.
- if(entry == null)
- {
- try
- {
- reader.close();
- }
- catch (Exception e)
- {
- logger.traceException(e);
- }
-
- break;
- }
-
- ProtocolOp protocolOp = null;
- ByteString asn1OctetStr =
- ByteString.valueOfUtf8(entry.getDN().toString());
-
- String operationType = "";
- switch(entry.getChangeOperationType())
- {
- case ADD:
- operationType = "ADD";
- AddChangeRecordEntry addEntry = (AddChangeRecordEntry) entry;
- List<Attribute> attrs = addEntry.getAttributes();
- ArrayList<RawAttribute> attributes = new ArrayList<>(attrs.size());
- for(Attribute a : attrs)
- {
- attributes.add(new LDAPAttribute(a));
- }
- protocolOp = new AddRequestProtocolOp(asn1OctetStr, attributes);
- out.println(INFO_PROCESSING_OPERATION.get(operationType, asn1OctetStr));
- break;
- case DELETE:
- operationType = "DELETE";
- protocolOp = new DeleteRequestProtocolOp(asn1OctetStr);
- out.println(INFO_PROCESSING_OPERATION.get(operationType, asn1OctetStr));
- break;
- case MODIFY:
- operationType = "MODIFY";
- ModifyChangeRecordEntry modEntry = (ModifyChangeRecordEntry) entry;
- ArrayList<RawModification> mods = new ArrayList<>(modEntry.getModifications());
- protocolOp = new ModifyRequestProtocolOp(asn1OctetStr, mods);
- out.println(INFO_PROCESSING_OPERATION.get(operationType, asn1OctetStr));
- break;
- case MODIFY_DN:
- operationType = "MODIFY DN";
- ModifyDNChangeRecordEntry modDNEntry =
- (ModifyDNChangeRecordEntry) entry;
- if(modDNEntry.getNewSuperiorDN() != null)
- {
- protocolOp = new ModifyDNRequestProtocolOp(asn1OctetStr,
- ByteString.valueOfUtf8(modDNEntry.getNewRDN().toString()),
- modDNEntry.deleteOldRDN(),
- ByteString.valueOfUtf8(
- modDNEntry.getNewSuperiorDN().toString()));
- } else
- {
- protocolOp = new ModifyDNRequestProtocolOp(asn1OctetStr,
- ByteString.valueOfUtf8(modDNEntry.getNewRDN().toString()),
- modDNEntry.deleteOldRDN());
- }
-
- out.println(INFO_PROCESSING_OPERATION.get(operationType, asn1OctetStr));
- break;
- default:
- break;
- }
-
- if(!modifyOptions.showOperations())
- {
- LDAPMessage responseMessage = null;
- try
- {
- LDAPMessage message =
- new LDAPMessage(nextMessageID.getAndIncrement(), protocolOp,
- controls);
- connection.getLDAPWriter().writeMessage(message);
- responseMessage = connection.getLDAPReader().readMessage();
- } catch(DecodeException ae)
- {
- logger.traceException(ae);
- printWrappedText(err, INFO_OPERATION_FAILED.get(operationType));
- printWrappedText(err, ae.getMessage());
- if (!modifyOptions.continueOnError())
- {
- String msg = LDAPToolUtils.getMessageForConnectionException(ae);
- throw new IOException(msg, ae);
- }
- return;
- }
-
- int resultCode = 0;
- LocalizableMessage errorMessage = null;
- DN matchedDN = null;
- List<String> referralURLs = null;
- try
- {
- switch(entry.getChangeOperationType())
- {
- case ADD:
- AddResponseProtocolOp addOp =
- responseMessage.getAddResponseProtocolOp();
- resultCode = addOp.getResultCode();
- errorMessage = addOp.getErrorMessage();
- matchedDN = addOp.getMatchedDN();
- referralURLs = addOp.getReferralURLs();
- break;
- case DELETE:
- DeleteResponseProtocolOp delOp =
- responseMessage.getDeleteResponseProtocolOp();
- resultCode = delOp.getResultCode();
- errorMessage = delOp.getErrorMessage();
- matchedDN = delOp.getMatchedDN();
- referralURLs = delOp.getReferralURLs();
- break;
- case MODIFY:
- ModifyResponseProtocolOp modOp =
- responseMessage.getModifyResponseProtocolOp();
- resultCode = modOp.getResultCode();
- errorMessage = modOp.getErrorMessage();
- matchedDN = modOp.getMatchedDN();
- referralURLs = modOp.getReferralURLs();
- break;
- case MODIFY_DN:
- ModifyDNResponseProtocolOp modDNOp =
- responseMessage.getModifyDNResponseProtocolOp();
- resultCode = modDNOp.getResultCode();
- errorMessage = modDNOp.getErrorMessage();
- matchedDN = modDNOp.getMatchedDN();
- referralURLs = modDNOp.getReferralURLs();
- break;
- default:
- break;
- }
- }
- catch (ClassCastException ce)
- {
- // It is possible that this is extended response.
- if (responseMessage.getProtocolOpType() ==
- LDAPConstants.OP_TYPE_EXTENDED_RESPONSE)
- {
- ExtendedResponseProtocolOp extRes =
- responseMessage.getExtendedResponseProtocolOp();
- resultCode = extRes.getResultCode();
- errorMessage = extRes.getErrorMessage();
- matchedDN = extRes.getMatchedDN();
- referralURLs = extRes.getReferralURLs();
- }
- else
- {
- // This should not happen but if it does, then debug log it,
- // set the error code to OTHER and fall through.
- logger.traceException(ce);
- resultCode = ResultCode.OTHER.intValue();
- errorMessage = null;
- matchedDN = null;
- referralURLs = null;
- }
- }
-
- if(resultCode != SUCCESS && resultCode != REFERRAL)
- {
- LocalizableMessage msg = INFO_OPERATION_FAILED.get(operationType);
-
- if(!modifyOptions.continueOnError())
- {
- throw new LDAPException(resultCode, errorMessage, msg,
- matchedDN, null);
- } else
- {
- LDAPToolUtils.printErrorMessage(err, msg, resultCode, errorMessage,
- matchedDN);
- }
- } else
- {
- out.println(INFO_OPERATION_SUCCESSFUL.get(operationType, asn1OctetStr));
-
- if (errorMessage != null)
- {
- printWrappedText(out, errorMessage);
- }
-
- if (referralURLs != null)
- {
- out.println(referralURLs);
- }
- }
-
-
- for (Control c : responseMessage.getControls())
- {
- String oid = c.getOID();
- if (oid.equals(OID_LDAP_READENTRY_PREREAD))
- {
- SearchResultEntry searchEntry;
- try
- {
- LDAPPreReadResponseControl prrc;
- if(c instanceof LDAPControl)
- {
- // Control needs to be decoded
- prrc = LDAPPreReadResponseControl.DECODER.decode(
- c.isCritical(), ((LDAPControl) c).getValue());
- }
- else
- {
- prrc = (LDAPPreReadResponseControl)c;
- }
- searchEntry = prrc.getSearchEntry();
- }
- catch (DirectoryException de)
- {
- printWrappedText(err, ERR_LDAPMODIFY_PREREAD_CANNOT_DECODE_VALUE.get(de.getMessage()));
- continue;
- }
-
- StringBuilder buffer = new StringBuilder();
- searchEntry.toString(buffer, 0);
- out.println(INFO_LDAPMODIFY_PREREAD_ENTRY.get());
- out.println(buffer);
- }
- else if (oid.equals(OID_LDAP_READENTRY_POSTREAD))
- {
- SearchResultEntry searchEntry;
- try
- {
- LDAPPostReadResponseControl pprc;
- if (c instanceof LDAPControl)
- {
- // Control needs to be decoded
- pprc = LDAPPostReadResponseControl.DECODER.decode(c
- .isCritical(), ((LDAPControl) c).getValue());
- }
- else
- {
- pprc = (LDAPPostReadResponseControl)c;
- }
- searchEntry = pprc.getSearchEntry();
- }
- catch (DirectoryException de)
- {
- printWrappedText(err, ERR_LDAPMODIFY_POSTREAD_CANNOT_DECODE_VALUE.get(de.getMessage()));
- continue;
- }
-
- StringBuilder buffer = new StringBuilder();
- searchEntry.toString(buffer, 0);
- out.println(INFO_LDAPMODIFY_POSTREAD_ENTRY.get());
- out.println(buffer);
- }
- else if (oid.equals(OID_CSN_CONTROL))
- {
- if(c instanceof LDAPControl)
- {
- // Don't really need to decode since its just an octet string.
- out.println(INFO_CHANGE_NUMBER_CONTROL_RESULT.get(
- operationType, ((LDAPControl)c).getValue()));
- }
- else
- {
- out.println(INFO_CHANGE_NUMBER_CONTROL_RESULT.get(operationType,
- ((ChangeNumberControlPlugin.ChangeNumberControl)c).getCSN()));
- }
- }
- }
- }
- }
-
- }
-
- /**
- * The main method for LDAPModify tool.
- *
- * @param args The command-line arguments provided to this program.
- */
-
- public static void main(String[] args)
- {
- int retCode = mainModify(args, true, System.out, System.err);
-
- if(retCode != 0)
- {
- System.exit(filterExitCode(retCode));
- }
- }
-
-
- /**
- * Parses the provided command-line arguments and uses that information to
- * run the ldapmodify tool.
- *
- * @param args The command-line arguments provided to this program.
- *
- * @return The error code.
- */
-
- public static int mainModify(String[] args)
- {
- return mainModify(args, true, System.out, System.err);
- }
-
-
- /**
- * Parses the provided command-line arguments and uses that information to
- * run the ldapmodify tool.
- *
- * @param args The command-line arguments provided to this
- * program.
- * @param initializeServer Indicates whether to initialize the server.
- * @param outStream The output stream to use for standard output, or
- * <CODE>null</CODE> if standard output is not
- * needed.
- * @param errStream The output stream to use for standard error, or
- * <CODE>null</CODE> if standard error is not
- * needed.
- *
- * @return The error code.
- */
-
- public static int mainModify(String[] args, boolean initializeServer,
- OutputStream outStream, OutputStream errStream)
- {
- PrintStream out = NullOutputStream.wrapOrNullStream(outStream);
- PrintStream err = NullOutputStream.wrapOrNullStream(errStream);
-
- LDAPConnectionOptions connectionOptions = new LDAPConnectionOptions();
- LDAPModifyOptions modifyOptions = new LDAPModifyOptions();
- LDAPConnection connection = null;
-
- final BooleanArgument continueOnError;
- final BooleanArgument defaultAdd;
- final BooleanArgument noop;
- final BooleanArgument reportAuthzID;
- final BooleanArgument saslExternal;
- final BooleanArgument showUsage;
- final BooleanArgument startTLS;
- final BooleanArgument trustAll;
- final BooleanArgument useSSL;
- final BooleanArgument verbose;
- final FileBasedArgument bindPasswordFile;
- final FileBasedArgument keyStorePasswordFile;
- final FileBasedArgument trustStorePasswordFile;
- final IntegerArgument connectTimeout;
- final IntegerArgument port;
- final IntegerArgument version;
- final StringArgument assertionFilter;
- final StringArgument bindDN;
- final StringArgument bindPassword;
- final StringArgument certNickname;
- final StringArgument controlStr;
- final StringArgument encodingStr;
- final StringArgument filename;
- final StringArgument hostName;
- final StringArgument keyStorePath;
- final StringArgument keyStorePassword;
- final StringArgument postReadAttributes;
- final StringArgument preReadAttributes;
- final StringArgument proxyAuthzID;
- final StringArgument saslOptions;
- final StringArgument trustStorePath;
- final StringArgument trustStorePassword;
- final StringArgument propertiesFileArgument;
- final BooleanArgument noPropertiesFileArgument;
-
- // Create the command-line argument parser for use with this program.
- LocalizableMessage toolDescription = INFO_LDAPMODIFY_TOOL_DESCRIPTION.get();
- ArgumentParser argParser = new ArgumentParser(CLASS_NAME, toolDescription,
- false);
- argParser.setShortToolDescription(REF_SHORT_DESC_LDAPMODIFY.get());
- argParser.setVersionHandler(new DirectoryServerVersionHandler());
- try
- {
- propertiesFileArgument =
- StringArgument.builder(OPTION_LONG_PROP_FILE_PATH)
- .description(INFO_DESCRIPTION_PROP_FILE_PATH.get())
- .valuePlaceholder(INFO_PROP_FILE_PATH_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- argParser.setFilePropertiesArgument(propertiesFileArgument);
-
- noPropertiesFileArgument =
- BooleanArgument.builder(OPTION_LONG_NO_PROP_FILE)
- .description(INFO_DESCRIPTION_NO_PROP_FILE.get())
- .buildAndAddToParser(argParser);
- argParser.setNoPropertiesFileArgument(noPropertiesFileArgument);
-
- hostName =
- StringArgument.builder(OPTION_LONG_HOST)
- .shortIdentifier(OPTION_SHORT_HOST)
- .description(INFO_DESCRIPTION_HOST.get())
- .defaultValue("localhost")
- .valuePlaceholder(INFO_HOST_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- port =
- IntegerArgument.builder(OPTION_LONG_PORT)
- .shortIdentifier(OPTION_SHORT_PORT)
- .description(INFO_DESCRIPTION_PORT.get())
- .range(1, 65535)
- .defaultValue(389)
- .valuePlaceholder(INFO_PORT_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- useSSL =
- BooleanArgument.builder(OPTION_LONG_USE_SSL)
- .shortIdentifier(OPTION_SHORT_USE_SSL)
- .description(INFO_DESCRIPTION_USE_SSL.get())
- .buildAndAddToParser(argParser);
- startTLS =
- BooleanArgument.builder(OPTION_LONG_START_TLS)
- .shortIdentifier(OPTION_SHORT_START_TLS)
- .description(INFO_DESCRIPTION_START_TLS.get())
- .buildAndAddToParser(argParser);
- bindDN =
- StringArgument.builder(OPTION_LONG_BINDDN)
- .shortIdentifier(OPTION_SHORT_BINDDN)
- .description(INFO_DESCRIPTION_BINDDN.get())
- .valuePlaceholder(INFO_BINDDN_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- bindPassword =
- StringArgument.builder(OPTION_LONG_BINDPWD)
- .shortIdentifier(OPTION_SHORT_BINDPWD)
- .description(INFO_DESCRIPTION_BINDPASSWORD.get())
- .valuePlaceholder(INFO_BINDPWD_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- bindPasswordFile =
- FileBasedArgument.builder(OPTION_LONG_BINDPWD_FILE)
- .shortIdentifier(OPTION_SHORT_BINDPWD_FILE)
- .description(INFO_DESCRIPTION_BINDPASSWORDFILE.get())
- .valuePlaceholder(INFO_BINDPWD_FILE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- defaultAdd =
- BooleanArgument.builder("defaultAdd")
- .shortIdentifier('a')
- .description(INFO_MODIFY_DESCRIPTION_DEFAULT_ADD.get())
- .buildAndAddToParser(argParser);
- filename =
- StringArgument.builder(OPTION_LONG_FILENAME)
- .shortIdentifier(OPTION_SHORT_FILENAME)
- .description(INFO_LDAPMODIFY_DESCRIPTION_FILENAME.get())
- .valuePlaceholder(INFO_FILE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- saslExternal =
- BooleanArgument.builder("useSASLExternal")
- .shortIdentifier('r')
- .description(INFO_DESCRIPTION_USE_SASL_EXTERNAL.get())
- .buildAndAddToParser(argParser);
- saslOptions =
- StringArgument.builder(OPTION_LONG_SASLOPTION)
- .shortIdentifier(OPTION_SHORT_SASLOPTION)
- .description(INFO_DESCRIPTION_SASL_PROPERTIES.get())
- .multiValued()
- .valuePlaceholder(INFO_SASL_OPTION_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
-
- trustAll = trustAllArgument();
- argParser.addArgument(trustAll);
-
- keyStorePath =
- StringArgument.builder(OPTION_LONG_KEYSTOREPATH)
- .shortIdentifier(OPTION_SHORT_KEYSTOREPATH)
- .description(INFO_DESCRIPTION_KEYSTOREPATH.get())
- .valuePlaceholder(INFO_KEYSTOREPATH_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- keyStorePassword =
- StringArgument.builder(OPTION_LONG_KEYSTORE_PWD)
- .shortIdentifier(OPTION_SHORT_KEYSTORE_PWD)
- .description(INFO_DESCRIPTION_KEYSTOREPASSWORD.get())
- .valuePlaceholder(INFO_KEYSTORE_PWD_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- keyStorePasswordFile =
- FileBasedArgument.builder(OPTION_LONG_KEYSTORE_PWD_FILE)
- .shortIdentifier(OPTION_SHORT_KEYSTORE_PWD_FILE)
- .description(INFO_DESCRIPTION_KEYSTOREPASSWORD_FILE.get())
- .valuePlaceholder(INFO_KEYSTORE_PWD_FILE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- certNickname =
- StringArgument.builder("certNickname")
- .shortIdentifier('N')
- .description(INFO_DESCRIPTION_CERT_NICKNAME.get())
- .valuePlaceholder(INFO_NICKNAME_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- trustStorePath =
- StringArgument.builder(OPTION_LONG_TRUSTSTOREPATH)
- .shortIdentifier(OPTION_SHORT_TRUSTSTOREPATH)
- .description(INFO_DESCRIPTION_TRUSTSTOREPATH.get())
- .valuePlaceholder(INFO_TRUSTSTOREPATH_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- trustStorePassword =
- StringArgument.builder(OPTION_LONG_TRUSTSTORE_PWD)
- .description(INFO_DESCRIPTION_TRUSTSTOREPASSWORD.get())
- .valuePlaceholder(INFO_TRUSTSTORE_PWD_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- trustStorePasswordFile =
- FileBasedArgument.builder(OPTION_LONG_TRUSTSTORE_PWD_FILE)
- .shortIdentifier(OPTION_SHORT_TRUSTSTORE_PWD_FILE)
- .description(INFO_DESCRIPTION_TRUSTSTOREPASSWORD_FILE.get())
- .valuePlaceholder(INFO_TRUSTSTORE_PWD_FILE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- proxyAuthzID =
- StringArgument.builder(OPTION_LONG_PROXYAUTHID)
- .shortIdentifier(OPTION_SHORT_PROXYAUTHID)
- .description(INFO_DESCRIPTION_PROXY_AUTHZID.get())
- .valuePlaceholder(INFO_PROXYAUTHID_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- reportAuthzID =
- BooleanArgument.builder("reportAuthzID")
- .shortIdentifier('E')
- .description(INFO_DESCRIPTION_REPORT_AUTHZID.get())
- .buildAndAddToParser(argParser);
- assertionFilter =
- StringArgument.builder(OPTION_LONG_ASSERTION_FILE)
- .description(INFO_DESCRIPTION_ASSERTION_FILTER.get())
- .valuePlaceholder(INFO_ASSERTION_FILTER_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- preReadAttributes =
- StringArgument.builder("preReadAttributes")
- .description(INFO_DESCRIPTION_PREREAD_ATTRS.get())
- .valuePlaceholder(INFO_ATTRIBUTE_LIST_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- postReadAttributes =
- StringArgument.builder("postReadAttributes")
- .description(INFO_DESCRIPTION_POSTREAD_ATTRS.get())
- .valuePlaceholder(INFO_ATTRIBUTE_LIST_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- controlStr =
- StringArgument.builder("control")
- .shortIdentifier('J')
- .description(INFO_DESCRIPTION_CONTROLS.get())
- .multiValued()
- .valuePlaceholder(INFO_LDAP_CONTROL_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- version =
- IntegerArgument.builder(OPTION_LONG_PROTOCOL_VERSION)
- .shortIdentifier(OPTION_SHORT_PROTOCOL_VERSION)
- .description(INFO_DESCRIPTION_VERSION.get())
- .defaultValue(3)
- .valuePlaceholder(INFO_PROTOCOL_VERSION_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- connectTimeout =
- IntegerArgument.builder(OPTION_LONG_CONNECT_TIMEOUT)
- .description(INFO_DESCRIPTION_CONNECTION_TIMEOUT.get())
- .lowerBound(0)
- .defaultValue(CliConstants.DEFAULT_LDAP_CONNECT_TIMEOUT)
- .valuePlaceholder(INFO_TIMEOUT_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- encodingStr =
- StringArgument.builder("encoding")
- .shortIdentifier('i')
- .description(INFO_DESCRIPTION_ENCODING.get())
- .valuePlaceholder(INFO_ENCODING_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- continueOnError =
- BooleanArgument.builder("continueOnError")
- .shortIdentifier('c')
- .description(INFO_DESCRIPTION_CONTINUE_ON_ERROR.get())
- .buildAndAddToParser(argParser);
- noop =
- BooleanArgument.builder(OPTION_LONG_DRYRUN)
- .shortIdentifier(OPTION_SHORT_DRYRUN)
- .description(INFO_DESCRIPTION_NOOP.get())
- .buildAndAddToParser(argParser);
-
- verbose = verboseArgument();
- argParser.addArgument(verbose);
-
- showUsage = showUsageArgument();
- argParser.addArgument(showUsage);
- argParser.setUsageArgument(showUsage, out);
- } catch (ArgumentException ae)
- {
- printWrappedText(err, ERR_CANNOT_INITIALIZE_ARGS.get(ae.getMessage()));
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
- // Parse the command-line arguments provided to this program.
- try
- {
- argParser.parseArguments(args);
- }
- catch (ArgumentException ae)
- {
- argParser.displayMessageAndUsageReference(err, ERR_ERROR_PARSING_ARGS.get(ae.getMessage()));
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
- // If we should just display usage or version information,
- // then print it and exit.
- if (argParser.usageOrVersionDisplayed())
- {
- return SUCCESS;
- }
-
- if (bindPassword.isPresent() && bindPasswordFile.isPresent())
- {
- printWrappedText(err, conflictingArgsErrorMessage(bindPassword, bindPasswordFile));
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
- String hostNameValue = hostName.getValue();
- int portNumber = 389;
- try
- {
- portNumber = port.getIntValue();
- } catch(ArgumentException ae)
- {
- logger.traceException(ae);
- argParser.displayMessageAndUsageReference(err, ae.getMessageObject());
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
- try
- {
- int versionNumber = version.getIntValue();
- if(versionNumber != 2 && versionNumber != 3)
- {
- printWrappedText(err, ERR_DESCRIPTION_INVALID_VERSION.get(versionNumber));
- return CLIENT_SIDE_PARAM_ERROR;
- }
- connectionOptions.setVersionNumber(versionNumber);
- } catch(ArgumentException ae)
- {
- logger.traceException(ae);
- argParser.displayMessageAndUsageReference(err, ae.getMessageObject());
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
- String bindDNValue = bindDN.getValue();
- String fileNameValue = filename.getValue();
- String bindPasswordValue;
- try
- {
- bindPasswordValue = getPasswordValue(
- bindPassword, bindPasswordFile, bindDNValue, out, err);
- }
- catch (Exception ex)
- {
- logger.traceException(ex);
- printWrappedText(err, ex.getMessage());
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
- String keyStorePathValue = keyStorePath.getValue();
- String trustStorePathValue = trustStorePath.getValue();
-
- String keyStorePasswordValue = null;
- if (keyStorePassword.isPresent())
- {
- keyStorePasswordValue = keyStorePassword.getValue();
- }
- else if (keyStorePasswordFile.isPresent())
- {
- keyStorePasswordValue = keyStorePasswordFile.getValue();
- }
-
- String trustStorePasswordValue = null;
- if (trustStorePassword.isPresent())
- {
- trustStorePasswordValue = trustStorePassword.getValue();
- }
- else if (trustStorePasswordFile.isPresent())
- {
- trustStorePasswordValue = trustStorePasswordFile.getValue();
- }
-
- modifyOptions.setShowOperations(noop.isPresent());
- modifyOptions.setVerbose(verbose.isPresent());
- modifyOptions.setContinueOnError(continueOnError.isPresent());
- modifyOptions.setEncoding(encodingStr.getValue());
- modifyOptions.setDefaultAdd(defaultAdd.isPresent());
-
- if (controlStr.isPresent())
- {
- for (String ctrlString : controlStr.getValues())
- {
- Control ctrl = LDAPToolUtils.getControl(ctrlString, err);
- if(ctrl == null)
- {
- printWrappedText(err, ERR_TOOL_INVALID_CONTROL_STRING.get(ctrlString));
- return CLIENT_SIDE_PARAM_ERROR;
- }
- modifyOptions.getControls().add(ctrl);
- }
- }
-
- if (proxyAuthzID.isPresent())
- {
- Control proxyControl =
- new ProxiedAuthV2Control(true,
- ByteString.valueOfUtf8(proxyAuthzID.getValue()));
- modifyOptions.getControls().add(proxyControl);
- }
-
- if (assertionFilter.isPresent())
- {
- String filterString = assertionFilter.getValue();
- LDAPFilter filter;
- try
- {
- filter = LDAPFilter.decode(filterString);
-
- Control assertionControl =
- new LDAPAssertionRequestControl(true, filter);
- modifyOptions.getControls().add(assertionControl);
- }
- catch (LDAPException le)
- {
- printWrappedText(err, ERR_LDAP_ASSERTION_INVALID_FILTER.get(le.getMessage()));
- return CLIENT_SIDE_PARAM_ERROR;
- }
- }
-
- if (preReadAttributes.isPresent())
- {
- String valueStr = preReadAttributes.getValue();
- Set<String> attrElements = new LinkedHashSet<>();
-
- StringTokenizer tokenizer = new StringTokenizer(valueStr, ", ");
- while (tokenizer.hasMoreTokens())
- {
- attrElements.add(tokenizer.nextToken());
- }
-
- Control c = new LDAPPreReadRequestControl(true, attrElements);
- modifyOptions.getControls().add(c);
- }
-
- if (postReadAttributes.isPresent())
- {
- String valueStr = postReadAttributes.getValue();
- Set<String> attrElements = new LinkedHashSet<>();
-
- StringTokenizer tokenizer = new StringTokenizer(valueStr, ", ");
- while (tokenizer.hasMoreTokens())
- {
- attrElements.add(tokenizer.nextToken());
- }
-
- Control c = new LDAPPostReadRequestControl(true, attrElements);
- modifyOptions.getControls().add(c);
- }
-
- // Set the connection options.
- connectionOptions.setSASLExternal(saslExternal.isPresent());
- if(saslOptions.isPresent())
- {
- for (String saslOption : saslOptions.getValues())
- {
- boolean val = saslOption.startsWith("mech=")
- ? connectionOptions.setSASLMechanism(saslOption)
- : connectionOptions.addSASLProperty(saslOption);
- if (!val)
- {
- return CLIENT_SIDE_PARAM_ERROR;
- }
- }
- }
-
- connectionOptions.setUseSSL(useSSL.isPresent());
- connectionOptions.setStartTLS(startTLS.isPresent());
- connectionOptions.setReportAuthzID(reportAuthzID.isPresent());
-
- if(connectionOptions.useSASLExternal())
- {
- if(!connectionOptions.useSSL() && !connectionOptions.useStartTLS())
- {
- printWrappedText(err, ERR_TOOL_SASLEXTERNAL_NEEDS_SSL_OR_TLS.get());
- return CLIENT_SIDE_PARAM_ERROR;
- }
- if(keyStorePathValue == null)
- {
- printWrappedText(err, ERR_TOOL_SASLEXTERNAL_NEEDS_KEYSTORE.get());
- return CLIENT_SIDE_PARAM_ERROR;
- }
- }
-
- connectionOptions.setVerbose(verbose.isPresent());
-
- LDAPModify ldapModify = null;
- try
- {
- if (initializeServer)
- {
- DirectoryServer.bootstrapClient();
- }
-
- // Connect to the specified host with the supplied userDN and password.
- SSLConnectionFactory sslConnectionFactory = null;
- if(connectionOptions.useSSL() || connectionOptions.useStartTLS())
- {
- String clientAlias;
- if (certNickname.isPresent())
- {
- clientAlias = certNickname.getValue();
- }
- else
- {
- clientAlias = null;
- }
-
- sslConnectionFactory = new SSLConnectionFactory();
- sslConnectionFactory.init(trustAll.isPresent(), keyStorePathValue,
- keyStorePasswordValue, clientAlias,
- trustStorePathValue, trustStorePasswordValue);
- connectionOptions.setSSLConnectionFactory(sslConnectionFactory);
- }
-
- AtomicInteger nextMessageID = new AtomicInteger(1);
- connection = new LDAPConnection(hostNameValue, portNumber,
- connectionOptions, out, err);
- int timeout = connectTimeout.getIntValue();
- connection.connectToHost(bindDNValue, bindPasswordValue, nextMessageID,
- timeout);
-
- ldapModify = new LDAPModify(nextMessageID, out, err);
- ldapModify.readAndExecute(connection, fileNameValue, modifyOptions);
- } catch(LDAPException le)
- {
- logger.traceException(le);
- LDAPToolUtils.printErrorMessage(err, le.getMessageObject(),
- le.getResultCode(),
- le.getErrorMessage(), le.getMatchedDN());
- return le.getResultCode();
- } catch(LDAPConnectionException lce)
- {
- logger.traceException(lce);
- LDAPToolUtils.printErrorMessage(err, lce.getMessageObject(),
- lce.getResultCode(),
- lce.getErrorMessage(),
- lce.getMatchedDN());
- return lce.getResultCode();
- } catch (FileNotFoundException fe)
- {
- logger.traceException(fe);
- printWrappedText(err, fe.getMessage());
- return CLIENT_SIDE_PARAM_ERROR;
- }
- catch(ArgumentException e)
- {
- argParser.displayMessageAndUsageReference(err, e.getMessageObject());
- return 1;
- }
- catch(Exception e)
- {
- logger.traceException(e);
- printWrappedText(err, e.getMessage());
- return OPERATIONS_ERROR;
- } finally
- {
- if(connection != null)
- {
- if (ldapModify == null)
- {
- connection.close(null);
- }
- else
- {
- connection.close(ldapModify.nextMessageID);
- }
- }
- }
- return SUCCESS;
- }
-
-}
-
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPModifyOptions.java b/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPModifyOptions.java
deleted file mode 100644
index 3772a1f..0000000
--- a/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPModifyOptions.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * The contents of this file are subject to the terms of the Common Development and
- * Distribution License (the License). You may not use this file except in compliance with the
- * License.
- *
- * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
- * specific language governing permission and limitations under the License.
- *
- * When distributing Covered Software, include this CDDL Header Notice in each file and include
- * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
- * Header, with the fields enclosed by brackets [] replaced by your own identifying
- * information: "Portions Copyright [year] [name of copyright owner]".
- *
- * Copyright 2006-2008 Sun Microsystems, Inc.
- * Portions Copyright 2015 ForgeRock AS.
- */
-package org.opends.server.tools;
-
-
-
-
-/**
- * This class defines options for all the modify operations used
- * by the ldapmodify tool.
- */
-public class LDAPModifyOptions extends LDAPToolOptions
-{
-
- private boolean defaultAdd;
-
- /**
- * Creates the options instance.
- *
- */
- public LDAPModifyOptions()
- {
- }
-
- /**
- * Set whether to default to adding entries if no changetype is provided.
- *
- * @param defaultAdd If entries with no changetype should be considered add
- * requests.
- */
- public void setDefaultAdd(boolean defaultAdd)
- {
- this.defaultAdd = defaultAdd;
- }
-
- /**
- * Get the value of the defaultAdd flag.
- *
- * @return <CODE>true</CODE> if a default changetype of "add" should be used,
- * or <CODE>false</CODE> if not.
- */
- public boolean getDefaultAdd()
- {
- return defaultAdd;
- }
-}
-
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPPasswordModify.java b/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPPasswordModify.java
deleted file mode 100644
index 354b08c..0000000
--- a/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPPasswordModify.java
+++ /dev/null
@@ -1,729 +0,0 @@
-/*
- * The contents of this file are subject to the terms of the Common Development and
- * Distribution License (the License). You may not use this file except in compliance with the
- * License.
- *
- * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
- * specific language governing permission and limitations under the License.
- *
- * When distributing Covered Software, include this CDDL Header Notice in each file and include
- * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
- * Header, with the fields enclosed by brackets [] replaced by your own identifying
- * information: "Portions Copyright [year] [name of copyright owner]".
- *
- * Copyright 2006-2010 Sun Microsystems, Inc.
- * Portions Copyright 2013-2016 ForgeRock AS.
- */
-package org.opends.server.tools;
-
-import static org.opends.messages.ToolMessages.*;
-import static org.opends.server.extensions.ExtensionsConstants.*;
-import static org.opends.server.protocols.ldap.LDAPResultCode.*;
-import static org.opends.server.util.ServerConstants.*;
-import static org.opends.server.util.StaticUtils.*;
-import static com.forgerock.opendj.cli.ArgumentConstants.*;
-import static com.forgerock.opendj.cli.Utils.*;
-import static com.forgerock.opendj.cli.CommonArguments.*;
-
-import java.io.OutputStream;
-import java.io.PrintStream;
-import java.util.ArrayList;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import org.forgerock.i18n.LocalizableMessage;
-import org.forgerock.opendj.io.ASN1;
-import org.forgerock.opendj.io.ASN1Reader;
-import org.forgerock.opendj.io.ASN1Writer;
-import org.forgerock.opendj.ldap.ByteString;
-import org.forgerock.opendj.ldap.ByteStringBuilder;
-import org.opends.server.controls.PasswordPolicyErrorType;
-import org.opends.server.controls.PasswordPolicyResponseControl;
-import org.opends.server.controls.PasswordPolicyWarningType;
-import org.opends.server.core.DirectoryServer;
-import org.opends.server.core.DirectoryServer.DirectoryServerVersionHandler;
-import org.opends.server.protocols.ldap.ExtendedRequestProtocolOp;
-import org.opends.server.protocols.ldap.ExtendedResponseProtocolOp;
-import org.opends.server.protocols.ldap.LDAPControl;
-import org.opends.server.protocols.ldap.LDAPMessage;
-import org.opends.server.protocols.ldap.LDAPResultCode;
-import org.opends.server.protocols.ldap.UnbindRequestProtocolOp;
-import org.opends.server.types.Control;
-import org.forgerock.opendj.ldap.DN;
-import org.opends.server.types.NullOutputStream;
-import com.forgerock.opendj.cli.ArgumentException;
-import com.forgerock.opendj.cli.ArgumentParser;
-import com.forgerock.opendj.cli.BooleanArgument;
-import com.forgerock.opendj.cli.CliConstants;
-import com.forgerock.opendj.cli.ConsoleApplication;
-import com.forgerock.opendj.cli.FileBasedArgument;
-import com.forgerock.opendj.cli.IntegerArgument;
-import com.forgerock.opendj.cli.StringArgument;
-
-/**
- * This program provides a utility that uses the LDAP password modify extended
- * operation to change the password for a user. It exposes the three primary
- * options available for this operation, which are:
- *
- * <UL>
- * <LI>The user identity whose password should be changed.</LI>
- * <LI>The current password for the user.</LI>
- * <LI>The new password for the user.</LI>
- * </UL>
- *
- * All of these are optional components that may be included or omitted from the
- * request.
- */
-public class LDAPPasswordModify
-{
- /** The fully-qualified name of this class. */
- private static final String CLASS_NAME =
- "org.opends.server.tools.LDAPPasswordModify";
-
- /**
- * Parses the command-line arguments, establishes a connection to the
- * Directory Server, sends the password modify request, and reads the
- * response.
- *
- * @param args The command-line arguments provided to this program.
- */
- public static void main(String[] args)
- {
- int returnCode = mainPasswordModify(args, true, System.out, System.err);
- if (returnCode != 0)
- {
- System.exit(filterExitCode(returnCode));
- }
- }
-
- /**
- * Parses the command-line arguments, establishes a connection to the
- * Directory Server, sends the password modify request, and reads the
- * response.
- *
- * @param args The command-line arguments provided to this
- * program.
- * @param initializeServer Indicates whether to initialize the server.
- * @param outStream The output stream to use for standard output.
- * @param errStream The output stream to use for standard error.
- *
- * @return An integer value of zero if everything completed successfully, or
- * a nonzero value if an error occurred.
- */
- public static int mainPasswordModify(String[] args, boolean initializeServer,
- OutputStream outStream,
- OutputStream errStream)
- {
- PrintStream out = NullOutputStream.wrapOrNullStream(outStream);
- PrintStream err = NullOutputStream.wrapOrNullStream(errStream);
-
- // Create the arguments that will be used by this program.
- BooleanArgument provideDNForAuthzID;
- BooleanArgument showUsage;
- BooleanArgument trustAll;
- BooleanArgument useSSL;
- BooleanArgument useStartTLS;
- FileBasedArgument bindPWFile;
- StringArgument certNickname;
- FileBasedArgument currentPWFile;
- FileBasedArgument newPWFile;
- FileBasedArgument sslKeyStorePINFile;
- FileBasedArgument sslTrustStorePINFile;
- IntegerArgument ldapPort;
- StringArgument authzID;
- StringArgument bindDN;
- StringArgument bindPW;
- StringArgument controlStr;
- StringArgument currentPW;
- StringArgument ldapHost;
- StringArgument newPW;
- StringArgument sslKeyStore;
- StringArgument sslKeyStorePIN;
- StringArgument sslTrustStore;
- StringArgument sslTrustStorePIN;
- IntegerArgument connectTimeout;
- StringArgument propertiesFileArgument;
- BooleanArgument noPropertiesFileArgument;
-
- // Initialize the argument parser.
- LocalizableMessage toolDescription = INFO_LDAPPWMOD_TOOL_DESCRIPTION.get();
- ArgumentParser argParser = new ArgumentParser(CLASS_NAME, toolDescription,
- false);
- argParser.setShortToolDescription(REF_SHORT_DESC_LDAPPASSWORDMODIFY.get());
- argParser.setVersionHandler(new DirectoryServerVersionHandler());
-
- try
- {
- propertiesFileArgument =
- StringArgument.builder(OPTION_LONG_PROP_FILE_PATH)
- .description(INFO_DESCRIPTION_PROP_FILE_PATH.get())
- .valuePlaceholder(INFO_PROP_FILE_PATH_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- argParser.setFilePropertiesArgument(propertiesFileArgument);
-
- noPropertiesFileArgument =
- BooleanArgument.builder(OPTION_LONG_NO_PROP_FILE)
- .description(INFO_DESCRIPTION_NO_PROP_FILE.get())
- .buildAndAddToParser(argParser);
- argParser.setNoPropertiesFileArgument(noPropertiesFileArgument);
-
- ldapHost =
- StringArgument.builder(OPTION_LONG_HOST)
- .shortIdentifier(OPTION_SHORT_HOST)
- .description(INFO_LDAPPWMOD_DESCRIPTION_HOST.get())
- .defaultValue("127.0.0.1")
- .valuePlaceholder(INFO_HOST_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- ldapPort =
- IntegerArgument.builder(OPTION_LONG_PORT)
- .shortIdentifier(OPTION_SHORT_PORT)
- .description(INFO_LDAPPWMOD_DESCRIPTION_PORT.get())
- .range(1, 65535)
- .defaultValue(389)
- .valuePlaceholder(INFO_PORT_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- useSSL =
- BooleanArgument.builder(OPTION_LONG_USE_SSL)
- .shortIdentifier(OPTION_SHORT_USE_SSL)
- .description(INFO_LDAPPWMOD_DESCRIPTION_USE_SSL.get())
- .buildAndAddToParser(argParser);
- useStartTLS =
- BooleanArgument.builder(OPTION_LONG_START_TLS)
- .shortIdentifier(OPTION_SHORT_START_TLS)
- .description(INFO_LDAPPWMOD_DESCRIPTION_USE_STARTTLS.get())
- .buildAndAddToParser(argParser);
- bindDN =
- StringArgument.builder(OPTION_LONG_BINDDN)
- .shortIdentifier(OPTION_SHORT_BINDDN)
- .description(INFO_LDAPPWMOD_DESCRIPTION_BIND_DN.get())
- .valuePlaceholder(INFO_BINDDN_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- bindPW =
- StringArgument.builder(OPTION_LONG_BINDPWD)
- .shortIdentifier(OPTION_SHORT_BINDPWD)
- .description(INFO_LDAPPWMOD_DESCRIPTION_BIND_PW.get())
- .valuePlaceholder(INFO_BINDPWD_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- bindPWFile =
- FileBasedArgument.builder(OPTION_LONG_BINDPWD_FILE)
- .shortIdentifier(OPTION_SHORT_BINDPWD_FILE)
- .description(INFO_LDAPPWMOD_DESCRIPTION_BIND_PW_FILE.get())
- .valuePlaceholder(INFO_BINDPWD_FILE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- authzID =
- StringArgument.builder("authzID")
- .shortIdentifier('a')
- .description(INFO_LDAPPWMOD_DESCRIPTION_AUTHZID.get())
- .valuePlaceholder(INFO_PROXYAUTHID_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- provideDNForAuthzID =
- BooleanArgument.builder("provideDNForAuthzID")
- .shortIdentifier('A')
- .description(INFO_LDAPPWMOD_DESCRIPTION_PROVIDE_DN_FOR_AUTHZID.get())
- .buildAndAddToParser(argParser);
- newPW =
- StringArgument.builder("newPassword")
- .shortIdentifier('n')
- .description(INFO_LDAPPWMOD_DESCRIPTION_NEWPW.get())
- .valuePlaceholder(INFO_NEW_PASSWORD_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- newPWFile =
- FileBasedArgument.builder("newPasswordFile")
- .shortIdentifier('N')
- .description(INFO_LDAPPWMOD_DESCRIPTION_NEWPWFILE.get())
- .valuePlaceholder(INFO_FILE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- currentPW =
- StringArgument.builder("currentPassword")
- .shortIdentifier('c')
- .description(INFO_LDAPPWMOD_DESCRIPTION_CURRENTPW.get())
- .valuePlaceholder(INFO_CURRENT_PASSWORD_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- currentPWFile =
- FileBasedArgument.builder("currentPasswordFile")
- .shortIdentifier('C')
- .description(INFO_LDAPPWMOD_DESCRIPTION_CURRENTPWFILE.get())
- .valuePlaceholder(INFO_FILE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
-
- trustAll = trustAllArgument();
- argParser.addArgument(trustAll);
-
- sslKeyStore =
- StringArgument.builder(OPTION_LONG_KEYSTOREPATH)
- .shortIdentifier(OPTION_SHORT_KEYSTOREPATH)
- .description(INFO_LDAPPWMOD_DESCRIPTION_KEYSTORE.get())
- .valuePlaceholder(INFO_KEYSTOREPATH_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- sslKeyStorePIN =
- StringArgument.builder(OPTION_LONG_KEYSTORE_PWD)
- .shortIdentifier(OPTION_SHORT_KEYSTORE_PWD)
- .description(INFO_LDAPPWMOD_DESCRIPTION_KEYSTORE_PIN.get())
- .valuePlaceholder(INFO_KEYSTORE_PWD_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- sslKeyStorePINFile =
- FileBasedArgument.builder(OPTION_LONG_KEYSTORE_PWD_FILE)
- .shortIdentifier(OPTION_SHORT_KEYSTORE_PWD_FILE)
- .description(INFO_LDAPPWMOD_DESCRIPTION_KEYSTORE_PINFILE.get())
- .valuePlaceholder(INFO_KEYSTORE_PWD_FILE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- certNickname =
- StringArgument.builder("certNickname")
- .description(INFO_DESCRIPTION_CERT_NICKNAME.get())
- .valuePlaceholder(INFO_NICKNAME_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- sslTrustStore =
- StringArgument.builder(OPTION_LONG_TRUSTSTOREPATH)
- .shortIdentifier(OPTION_SHORT_TRUSTSTOREPATH)
- .description(INFO_LDAPPWMOD_DESCRIPTION_TRUSTSTORE.get())
- .valuePlaceholder(INFO_TRUSTSTOREPATH_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- sslTrustStorePIN =
- StringArgument.builder(OPTION_LONG_TRUSTSTORE_PWD)
- .description(INFO_LDAPPWMOD_DESCRIPTION_TRUSTSTORE_PIN.get())
- .valuePlaceholder(INFO_TRUSTSTORE_PWD_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- sslTrustStorePINFile =
- FileBasedArgument.builder(OPTION_LONG_TRUSTSTORE_PWD_FILE)
- .shortIdentifier(OPTION_SHORT_TRUSTSTORE_PWD_FILE)
- .description(INFO_LDAPPWMOD_DESCRIPTION_TRUSTSTORE_PINFILE.get())
- .valuePlaceholder(INFO_TRUSTSTORE_PWD_FILE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- controlStr =
- StringArgument.builder("control")
- .shortIdentifier('J')
- .description(INFO_DESCRIPTION_CONTROLS.get())
- .multiValued()
- .valuePlaceholder(INFO_LDAP_CONTROL_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- connectTimeout =
- IntegerArgument.builder(OPTION_LONG_CONNECT_TIMEOUT)
- .description(INFO_DESCRIPTION_CONNECTION_TIMEOUT.get())
- .lowerBound(0)
- .defaultValue(CliConstants.DEFAULT_LDAP_CONNECT_TIMEOUT)
- .valuePlaceholder(INFO_TIMEOUT_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
-
- showUsage = showUsageArgument();
- argParser.addArgument(showUsage);
- argParser.setUsageArgument(showUsage, out);
- }
- catch (ArgumentException ae)
- {
- printWrappedText(err, ERR_CANNOT_INITIALIZE_ARGS.get(ae.getMessage()));
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
- // Parse the command-line arguments provided to this program.
- try
- {
- argParser.parseArguments(args);
- }
- catch (ArgumentException ae)
- {
- argParser.displayMessageAndUsageReference(err, ERR_ERROR_PARSING_ARGS.get(ae.getMessage()));
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
- // If the usage or version argument was provided,
- // then we don't need to do anything else.
- if (argParser.usageOrVersionDisplayed())
- {
- return 0;
- }
-
- // Make sure that the user didn't specify any conflicting arguments.
- try
- {
- throwIfArgumentsConflict(bindPW, bindPWFile);
- throwIfArgumentsConflict(newPW, newPWFile);
- throwIfArgumentsConflict(currentPW, currentPWFile);
- throwIfArgumentsConflict(useSSL, useStartTLS);
- throwIfArgumentsConflict(sslKeyStorePIN, sslKeyStorePINFile);
- throwIfArgumentsConflict(sslTrustStorePIN, sslTrustStorePINFile);
- }
- catch(final ArgumentException conflict)
- {
- printWrappedText(err, conflict.getMessageObject());
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
- // If a bind DN was provided, make sure that a password was given. If a
- // password was given, make sure a bind DN was provided. If neither were
- // given, then make sure that an authorization ID and the current password
- // were provided.
- if (bindDN.isPresent())
- {
- if (!bindPW.isPresent() && !bindPWFile.isPresent())
- {
- argParser.displayMessageAndUsageReference(err, ERR_LDAPPWMOD_BIND_DN_AND_PW_MUST_BE_TOGETHER.get());
- return CLIENT_SIDE_PARAM_ERROR;
- }
- }
- else if (bindPW.isPresent() || bindPWFile.isPresent())
- {
- argParser.displayMessageAndUsageReference(err, ERR_LDAPPWMOD_BIND_DN_AND_PW_MUST_BE_TOGETHER.get());
- return CLIENT_SIDE_PARAM_ERROR;
- }
- else
- {
- if (provideDNForAuthzID.isPresent())
- {
- argParser.displayMessageAndUsageReference(err,
- ERR_LDAPPWMOD_DEPENDENT_ARGS.get(provideDNForAuthzID.getLongIdentifier(), bindDN.getLongIdentifier()));
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
- if (!authzID.isPresent() || (!currentPW.isPresent() && !currentPWFile.isPresent()))
- {
- argParser.displayMessageAndUsageReference(err, ERR_LDAPPWMOD_ANON_REQUIRES_AUTHZID_AND_CURRENTPW.get());
- return CLIENT_SIDE_PARAM_ERROR;
- }
- }
-
- // Get the host and port.
- String host = ldapHost.getValue();
- int port;
- try
- {
- port = ldapPort.getIntValue();
- }
- catch (Exception e)
- {
- // This should never happen.
- printWrappedText(err, e.toString());
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
- // If a control string was provided, then decode the requested controls.
- ArrayList<Control> controls = new ArrayList<>();
- if(controlStr.isPresent())
- {
- for (String ctrlString : controlStr.getValues())
- {
- LDAPControl ctrl = LDAPToolUtils.getControl(ctrlString, err);
- if(ctrl == null)
- {
- printWrappedText(err, ERR_TOOL_INVALID_CONTROL_STRING.get(ctrlString));
- return CLIENT_SIDE_PARAM_ERROR;
- }
- controls.add(ctrl);
- }
- }
-
- if (initializeServer)
- {
- DirectoryServer.bootstrapClient();
- }
-
- // Establish a connection to the Directory Server.
- AtomicInteger nextMessageID = new AtomicInteger(1);
- LDAPConnectionOptions connectionOptions = new LDAPConnectionOptions();
- connectionOptions.setUseSSL(useSSL.isPresent());
- connectionOptions.setStartTLS(useStartTLS.isPresent());
- connectionOptions.setVersionNumber(3);
- if(connectionOptions.useSSL() || connectionOptions.useStartTLS())
- {
- String keyPIN = null;
- if (sslKeyStorePIN.isPresent())
- {
- keyPIN = sslKeyStorePIN.getValue();
- }
- else if (sslKeyStorePINFile.isPresent())
- {
- keyPIN = sslKeyStorePINFile.getValue();
- }
-
- String trustPIN = null;
- if (sslTrustStorePIN.isPresent())
- {
- trustPIN = sslTrustStorePIN.getValue();
- }
- else if (sslTrustStorePINFile.isPresent())
- {
- trustPIN = sslTrustStorePINFile.getValue();
- }
-
- try
- {
- String clientAlias;
- if (certNickname.isPresent())
- {
- clientAlias = certNickname.getValue();
- }
- else
- {
- clientAlias = null;
- }
- SSLConnectionFactory sslConnectionFactory = new SSLConnectionFactory();
- sslConnectionFactory.init(trustAll.isPresent(),
- sslKeyStore.getValue(), keyPIN, clientAlias,
- sslTrustStore.getValue(), trustPIN);
- connectionOptions.setSSLConnectionFactory(sslConnectionFactory);
- }
- catch (Exception e)
- {
- printWrappedText(err, ERR_LDAPPWMOD_ERROR_INITIALIZING_SSL.get(e));
- return CLIENT_SIDE_PARAM_ERROR;
- }
- }
-
- LDAPConnection connection = new LDAPConnection(host, port,
- connectionOptions, out, err);
- String dn;
- String pw;
- if (bindPW.isPresent())
- {
- dn = bindDN.getValue();
- pw = bindPW.getValue();
- if ("-".equals(pw))
- {
- // read the password from the stdin.
- try
- {
- out.print(INFO_LDAPAUTH_PASSWORD_PROMPT.get(dn));
- char[] pwChars = ConsoleApplication.readPassword();
- //As per rfc 4513(section-5.1.2) a client should avoid sending
- //an empty password to the server.
- while(pwChars.length==0)
- {
- printWrappedText(err, INFO_LDAPAUTH_NON_EMPTY_PASSWORD.get());
- out.print(INFO_LDAPAUTH_PASSWORD_PROMPT.get(dn));
- pwChars = ConsoleApplication.readPassword();
- }
- pw = new String(pwChars);
- } catch(Exception ex)
- {
- printWrappedText(err, ex.getMessage());
- return CLIENT_SIDE_PARAM_ERROR;
- }
- }
- }
- else if (bindPWFile.isPresent())
- {
- dn = bindDN.getValue();
- pw = bindPWFile.getValue();
- }
- else
- {
- dn = null;
- pw = null;
- }
-
- try
- {
- int timeout = connectTimeout.getIntValue();
- connection.connectToHost(dn, pw, nextMessageID, timeout);
- }
- catch (LDAPConnectionException lce)
- {
- printWrappedText(err, ERR_LDAPPWMOD_CANNOT_CONNECT.get(lce.getMessage()));
- return lce.getResultCode();
- }
- catch (ArgumentException e)
- {
- // This should not occur because the arguments are already parsed.
- // It is a bug
- e.printStackTrace();
- throw new IllegalStateException("Unexpected error: "+e, e);
- }
-
- LDAPReader reader = connection.getLDAPReader();
- LDAPWriter writer = connection.getLDAPWriter();
-
- // Construct the password modify request.
- ByteStringBuilder builder = new ByteStringBuilder();
- ASN1Writer asn1Writer = ASN1.getWriter(builder);
-
- try
- {
- asn1Writer.writeStartSequence();
- if (authzID.isPresent())
- {
- asn1Writer.writeOctetString(TYPE_PASSWORD_MODIFY_USER_ID,
- authzID.getValue());
- }
- else if (provideDNForAuthzID.isPresent())
- {
- asn1Writer.writeOctetString(TYPE_PASSWORD_MODIFY_USER_ID, "dn:" + dn);
- }
-
- if (currentPW.isPresent())
- {
- asn1Writer.writeOctetString(TYPE_PASSWORD_MODIFY_OLD_PASSWORD,
- currentPW.getValue());
- }
- else if (currentPWFile.isPresent())
- {
- asn1Writer.writeOctetString(TYPE_PASSWORD_MODIFY_OLD_PASSWORD,
- currentPWFile.getValue());
- }
- else if (provideDNForAuthzID.isPresent())
- {
- asn1Writer.writeOctetString(TYPE_PASSWORD_MODIFY_OLD_PASSWORD,
- pw);
- }
-
- if (newPW.isPresent())
- {
- asn1Writer.writeOctetString(TYPE_PASSWORD_MODIFY_NEW_PASSWORD,
- newPW.getValue());
- }
- else if (newPWFile.isPresent())
- {
- asn1Writer.writeOctetString(TYPE_PASSWORD_MODIFY_NEW_PASSWORD,
- newPWFile.getValue());
- }
- asn1Writer.writeEndSequence();
- }
- catch(Exception e)
- {
- err.println(e);
- }
-
- ExtendedRequestProtocolOp extendedRequest =
- new ExtendedRequestProtocolOp(OID_PASSWORD_MODIFY_REQUEST,
- builder.toByteString());
- LDAPMessage requestMessage =
- new LDAPMessage(nextMessageID.getAndIncrement(), extendedRequest,
- controls);
-
- // Send the request to the server and read the response.
- try
- {
- writer.writeMessage(requestMessage);
- }
- catch (Exception e)
- {
- printWrappedText(err, ERR_LDAPPWMOD_CANNOT_SEND_PWMOD_REQUEST.get(e));
- unbind(nextMessageID, writer);
- close(reader, writer);
- return 1;
- }
-
- // Read the response from the server.
- LDAPMessage responseMessage = null;
- try
- {
- responseMessage = reader.readMessage();
- }
- catch (Exception e)
- {
- printWrappedText(err, ERR_LDAPPWMOD_CANNOT_READ_PWMOD_RESPONSE.get(e));
- unbind(nextMessageID, writer);
- close(reader, writer);
- return 1;
- }
-
- // Make sure that the response was acceptable.
- ExtendedResponseProtocolOp extendedResponse =
- responseMessage.getExtendedResponseProtocolOp();
- int resultCode = extendedResponse.getResultCode();
- if (resultCode != LDAPResultCode.SUCCESS)
- {
- printWrappedText(err, ERR_LDAPPWMOD_FAILED.get(resultCode));
-
- LocalizableMessage errorMessage = extendedResponse.getErrorMessage();
- if (errorMessage != null && errorMessage.length() > 0)
- {
- printWrappedText(err, ERR_LDAPPWMOD_FAILURE_ERROR_MESSAGE.get(errorMessage));
- }
-
- DN matchedDN = extendedResponse.getMatchedDN();
- if (matchedDN != null)
- {
- printWrappedText(err, ERR_LDAPPWMOD_FAILURE_MATCHED_DN.get(matchedDN));
- }
-
- unbind(nextMessageID, writer);
- close(reader, writer);
- return resultCode;
- }
- else
- {
- printWrappedText(out, INFO_LDAPPWMOD_SUCCESSFUL.get());
- LocalizableMessage additionalInfo = extendedResponse.getErrorMessage();
- if (additionalInfo != null && additionalInfo.length() > 0)
- {
- printWrappedText(out, INFO_LDAPPWMOD_ADDITIONAL_INFO.get(additionalInfo));
- }
- }
-
- // See if the response included any controls that we recognize, and if so
- // then handle them.
- for (Control c : responseMessage.getControls())
- {
- if (c.getOID().equals(OID_PASSWORD_POLICY_CONTROL))
- {
- try
- {
- PasswordPolicyResponseControl pwPolicyControl =
- PasswordPolicyResponseControl.DECODER
- .decode(c.isCritical(), ((LDAPControl) c).getValue());
-
- PasswordPolicyWarningType pwPolicyWarningType = pwPolicyControl.getWarningType();
- if (pwPolicyWarningType != null)
- {
- printWrappedText(
- out, INFO_LDAPPWMOD_PWPOLICY_WARNING.get(pwPolicyWarningType, pwPolicyControl.getWarningValue()));
- }
-
- PasswordPolicyErrorType pwPolicyErrorType = pwPolicyControl.getErrorType();
- if (pwPolicyErrorType != null)
- {
- printWrappedText(out, INFO_LDAPPWMOD_PWPOLICY_ERROR.get(pwPolicyErrorType));
- }
- }
- catch (Exception e)
- {
- printWrappedText(err, ERR_LDAPPWMOD_CANNOT_DECODE_PWPOLICY_CONTROL.get(e));
- }
- }
- }
-
- // See if the response included a generated password.
- ByteString responseValue = extendedResponse.getValue();
- if (responseValue != null)
- {
- try
- {
- ASN1Reader asn1Reader = ASN1.getReader(responseValue);
- asn1Reader.readStartSequence();
- while(asn1Reader.hasNextElement())
- {
- if (asn1Reader.peekType() == TYPE_PASSWORD_MODIFY_GENERATED_PASSWORD)
- {
- printWrappedText(out, INFO_LDAPPWMOD_GENERATED_PASSWORD.get(asn1Reader.readOctetStringAsString()));
- }
- else
- {
- printWrappedText(err, ERR_LDAPPWMOD_UNRECOGNIZED_VALUE_TYPE.get(asn1Reader.readOctetStringAsString()));
- }
- }
- asn1Reader.readEndSequence();
- }
- catch (Exception e)
- {
- printWrappedText(err, ERR_LDAPPWMOD_COULD_NOT_DECODE_RESPONSE_VALUE.get(e));
- unbind(nextMessageID, writer);
- close(reader, writer);
- return 1;
- }
- }
-
- // Unbind from the server and close the connection.
- unbind(nextMessageID, writer);
- close(reader, writer);
- return 0;
- }
-
- private static void unbind(AtomicInteger nextMessageID, LDAPWriter writer)
- {
- try
- {
- LDAPMessage requestMessage = new LDAPMessage(
- nextMessageID.getAndIncrement(), new UnbindRequestProtocolOp());
- writer.writeMessage(requestMessage);
- }
- catch (Exception e) {}
- }
-}
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPSearch.java b/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPSearch.java
deleted file mode 100644
index 403bae1..0000000
--- a/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPSearch.java
+++ /dev/null
@@ -1,1647 +0,0 @@
-/*
- * The contents of this file are subject to the terms of the Common Development and
- * Distribution License (the License). You may not use this file except in compliance with the
- * License.
- *
- * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
- * specific language governing permission and limitations under the License.
- *
- * When distributing Covered Software, include this CDDL Header Notice in each file and include
- * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
- * Header, with the fields enclosed by brackets [] replaced by your own identifying
- * information: "Portions Copyright [year] [name of copyright owner]".
- *
- * Copyright 2006-2010 Sun Microsystems, Inc.
- * Portions Copyright 2012-2016 ForgeRock AS.
- */
-package org.opends.server.tools;
-
-import static com.forgerock.opendj.cli.ArgumentConstants.*;
-import static com.forgerock.opendj.cli.Utils.*;
-import static com.forgerock.opendj.cli.CommonArguments.*;
-import static org.opends.messages.ToolMessages.*;
-import static org.opends.server.protocols.ldap.LDAPConstants.*;
-import static org.opends.server.protocols.ldap.LDAPResultCode.*;
-import static org.opends.server.util.ServerConstants.*;
-import static org.opends.server.util.StaticUtils.*;
-import static org.opends.server.util.cli.LDAPConnectionArgumentParser.*;
-
-import java.io.BufferedReader;
-import java.io.FileReader;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.PrintStream;
-import java.util.*;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import org.forgerock.i18n.LocalizableMessage;
-import org.forgerock.i18n.slf4j.LocalizedLogger;
-import org.forgerock.opendj.ldap.ByteString;
-import org.forgerock.opendj.ldap.DN;
-import org.forgerock.opendj.ldap.DecodeException;
-import org.opends.server.controls.*;
-import org.opends.server.core.DirectoryServer;
-import org.opends.server.core.DirectoryServer.DirectoryServerVersionHandler;
-import org.opends.server.protocols.ldap.*;
-import org.opends.server.types.*;
-import org.opends.server.util.Base64;
-import com.forgerock.opendj.cli.ArgumentException;
-import com.forgerock.opendj.cli.ArgumentParser;
-import com.forgerock.opendj.cli.BooleanArgument;
-import com.forgerock.opendj.cli.CliConstants;
-import com.forgerock.opendj.cli.FileBasedArgument;
-import com.forgerock.opendj.cli.IntegerArgument;
-import com.forgerock.opendj.cli.MultiChoiceArgument;
-import com.forgerock.opendj.cli.StringArgument;
-
-/**
- * This class provides a tool that can be used to issue search requests to the
- * Directory Server.
- */
-public class LDAPSearch
-{
- private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
-
- /** The fully-qualified name of this class. */
- private static final String CLASS_NAME = "org.opends.server.tools.LDAPSearch";
-
-
-
- /** The set of response controls for the search. */
- private List<Control> responseControls;
-
- /** The message ID counter to use for requests. */
- private final AtomicInteger nextMessageID;
-
- /** The print stream to use for standard error. */
- private final PrintStream err;
- /** The print stream to use for standard output. */
- private final PrintStream out;
-
-
-
- /**
- * Constructor for the LDAPSearch object.
- *
- * @param nextMessageID The message ID counter to use for requests.
- * @param out The print stream to use for standard output.
- * @param err The print stream to use for standard error.
- */
- public LDAPSearch(AtomicInteger nextMessageID, PrintStream out,
- PrintStream err)
- {
- this.nextMessageID = nextMessageID;
- this.out = out;
- this.err = err;
- responseControls = new ArrayList<>();
- }
-
-
- /**
- * Execute the search based on the specified input parameters.
- *
- * @param connection The connection to use for the search.
- * @param baseDN The base DN for the search request.
- * @param filters The filters to use for the results.
- * @param attributes The attributes to return in the results.
- * @param searchOptions The constraints for the search.
- * @param wrapColumn The column at which to wrap long lines.
- *
- * @return The number of matching entries returned by the server. If there
- * were multiple search filters provided, then this will be the
- * total number of matching entries for all searches.
- *
- * @throws IOException If a problem occurs while attempting to communicate
- * with the Directory Server.
- *
- * @throws LDAPException If the Directory Server returns an error response.
- */
- public int executeSearch(LDAPConnection connection, String baseDN,
- List<LDAPFilter> filters,
- Set<String> attributes,
- LDAPSearchOptions searchOptions,
- int wrapColumn )
- throws IOException, LDAPException
- {
- int matchingEntries = 0;
-
- for (LDAPFilter filter: filters)
- {
- ByteString asn1OctetStr = ByteString.valueOfUtf8(baseDN);
-
- SearchRequestProtocolOp protocolOp =
- new SearchRequestProtocolOp(asn1OctetStr,
- searchOptions.getSearchScope(),
- searchOptions.getDereferencePolicy(),
- searchOptions.getSizeLimit(),
- searchOptions.getTimeLimit(),
- searchOptions.getTypesOnly(),
- filter, attributes);
- if(!searchOptions.showOperations())
- {
- try
- {
- boolean typesOnly = searchOptions.getTypesOnly();
- LDAPMessage message = new LDAPMessage(nextMessageID.getAndIncrement(),
- protocolOp,
- searchOptions.getControls());
- connection.getLDAPWriter().writeMessage(message);
-
- byte opType;
- do
- {
- int resultCode = 0;
- LocalizableMessage errorMessage = null;
- DN matchedDN = null;
- LDAPMessage responseMessage =
- connection.getLDAPReader().readMessage();
- responseControls = responseMessage.getControls();
-
-
- opType = responseMessage.getProtocolOpType();
- switch(opType)
- {
- case OP_TYPE_SEARCH_RESULT_ENTRY:
- for (Control c : responseControls)
- {
- if (c.getOID().equals(OID_ENTRY_CHANGE_NOTIFICATION))
- {
- try
- {
- EntryChangeNotificationControl ecn =
- EntryChangeNotificationControl.DECODER
- .decode(c.isCritical(), ((LDAPControl) c).getValue());
-
- out.println(INFO_LDAPSEARCH_PSEARCH_CHANGE_TYPE.get(ecn.getChangeType()));
- DN previousDN = ecn.getPreviousDN();
- if (previousDN != null)
- {
- out.println(INFO_LDAPSEARCH_PSEARCH_PREVIOUS_DN.get(previousDN));
- }
- } catch (Exception e) {}
- }
- else if (c.getOID().equals(OID_ACCOUNT_USABLE_CONTROL))
- {
- try
- {
- AccountUsableResponseControl acrc =
- AccountUsableResponseControl.DECODER
- .decode(c.isCritical(), ((LDAPControl) c).getValue());
-
- out.println(INFO_LDAPSEARCH_ACCTUSABLE_HEADER.get());
- if (acrc.isUsable())
- {
- out.println(INFO_LDAPSEARCH_ACCTUSABLE_IS_USABLE.get());
- if (acrc.getSecondsBeforeExpiration() > 0)
- {
- int timeToExp = acrc.getSecondsBeforeExpiration();
- LocalizableMessage timeToExpStr = secondsToTimeString(timeToExp);
-
- out.println(
- INFO_LDAPSEARCH_ACCTUSABLE_TIME_UNTIL_EXPIRATION.
- get(timeToExpStr));
- }
- }
- else
- {
- out.println(
- INFO_LDAPSEARCH_ACCTUSABLE_NOT_USABLE.get());
- if (acrc.isInactive())
- {
- out.println(
- INFO_LDAPSEARCH_ACCTUSABLE_ACCT_INACTIVE.get());
- }
- if (acrc.isReset())
- {
- out.println(
- INFO_LDAPSEARCH_ACCTUSABLE_PW_RESET.get());
- }
- if (acrc.isExpired())
- {
- out.println(
- INFO_LDAPSEARCH_ACCTUSABLE_PW_EXPIRED.get());
-
- if (acrc.getRemainingGraceLogins() > 0)
- {
- out.println(
- INFO_LDAPSEARCH_ACCTUSABLE_REMAINING_GRACE
- .get(acrc.getRemainingGraceLogins()));
- }
- }
- if (acrc.isLocked())
- {
- out.println(INFO_LDAPSEARCH_ACCTUSABLE_LOCKED.get());
- if (acrc.getSecondsBeforeUnlock() > 0)
- {
- int timeToUnlock = acrc.getSecondsBeforeUnlock();
- LocalizableMessage timeToUnlockStr =
- secondsToTimeString(timeToUnlock);
-
- out.println(
- INFO_LDAPSEARCH_ACCTUSABLE_TIME_UNTIL_UNLOCK
- .get(timeToUnlockStr));
- }
- }
- }
- } catch (Exception e) {}
- }
- else if (c.getOID().equals(OID_ECL_COOKIE_EXCHANGE_CONTROL))
- {
- try
- {
- EntryChangelogNotificationControl ctrl =
- EntryChangelogNotificationControl.DECODER.decode(
- c.isCritical(), ((LDAPControl) c).getValue());
- out.println(
- INFO_LDAPSEARCH_PUBLIC_CHANGELOG_COOKIE_EXC.get(
- c.getOID(), ctrl.getCookie()));
- }
- catch (Exception e)
- {
- logger.traceException(e);
- }
- }
- }
-
- SearchResultEntryProtocolOp searchEntryOp =
- responseMessage.getSearchResultEntryProtocolOp();
- StringBuilder sb = new StringBuilder();
- toLDIF(searchEntryOp, sb, wrapColumn, typesOnly);
- out.print(sb.toString());
- matchingEntries++;
- break;
-
- case OP_TYPE_SEARCH_RESULT_REFERENCE:
- SearchResultReferenceProtocolOp searchRefOp =
- responseMessage.getSearchResultReferenceProtocolOp();
- out.println(searchRefOp.toString());
- break;
-
- case OP_TYPE_SEARCH_RESULT_DONE:
- SearchResultDoneProtocolOp searchOp =
- responseMessage.getSearchResultDoneProtocolOp();
- resultCode = searchOp.getResultCode();
- errorMessage = searchOp.getErrorMessage();
- matchedDN = searchOp.getMatchedDN();
-
- for (Control c : responseMessage.getControls())
- {
- if (c.getOID().equals(OID_SERVER_SIDE_SORT_RESPONSE_CONTROL))
- {
- try
- {
- ServerSideSortResponseControl sortResponse =
- ServerSideSortResponseControl.DECODER
- .decode(c.isCritical(), ((LDAPControl) c).getValue());
- int rc = sortResponse.getResultCode();
- if (rc != LDAPResultCode.SUCCESS)
- {
- LocalizableMessage msg = WARN_LDAPSEARCH_SORT_ERROR.get(
- LDAPResultCode.toString(rc));
- err.println(msg);
- }
- }
- catch (Exception e)
- {
- LocalizableMessage msg =
- WARN_LDAPSEARCH_CANNOT_DECODE_SORT_RESPONSE.get(
- getExceptionMessage(e));
- err.println(msg);
- }
- }
- else if (c.getOID().equals(OID_VLV_RESPONSE_CONTROL))
- {
- try
- {
- VLVResponseControl vlvResponse =
- VLVResponseControl.DECODER.decode(c.isCritical(),
- ((LDAPControl) c).getValue());
- int rc = vlvResponse.getVLVResultCode();
- if (rc == LDAPResultCode.SUCCESS)
- {
- LocalizableMessage msg = INFO_LDAPSEARCH_VLV_TARGET_OFFSET.get(
- vlvResponse.getTargetPosition());
- out.println(msg);
-
-
- msg = INFO_LDAPSEARCH_VLV_CONTENT_COUNT.get(
- vlvResponse.getContentCount());
- out.println(msg);
- }
- else
- {
- LocalizableMessage msg = WARN_LDAPSEARCH_VLV_ERROR.get(
- LDAPResultCode.toString(rc));
- err.println(msg);
- }
- }
- catch (Exception e)
- {
- LocalizableMessage msg =
- WARN_LDAPSEARCH_CANNOT_DECODE_VLV_RESPONSE.get(
- getExceptionMessage(e));
- err.println(msg);
- }
- }
- }
-
- break;
- default:
- if(opType == OP_TYPE_EXTENDED_RESPONSE)
- {
- ExtendedResponseProtocolOp op =
- responseMessage.getExtendedResponseProtocolOp();
- if(op.getOID().equals(OID_NOTICE_OF_DISCONNECTION))
- {
- resultCode = op.getResultCode();
- errorMessage = op.getErrorMessage();
- matchedDN = op.getMatchedDN();
- break;
- }
- }
- // FIXME - throw exception?
- printWrappedText(err, INFO_SEARCH_OPERATION_INVALID_PROTOCOL.get(opType));
- }
-
- if(resultCode != SUCCESS)
- {
- LocalizableMessage msg = INFO_OPERATION_FAILED.get("SEARCH");
- throw new LDAPException(resultCode, errorMessage, msg,
- matchedDN, null);
- }
- else if (errorMessage != null)
- {
- out.println();
- printWrappedText(out, errorMessage);
- }
-
- } while(opType != OP_TYPE_SEARCH_RESULT_DONE);
-
- } catch(DecodeException ae)
- {
- logger.traceException(ae);
- throw new IOException(ae.getMessage());
- }
- }
- }
-
- if (searchOptions.countMatchingEntries())
- {
- LocalizableMessage message =
- INFO_LDAPSEARCH_MATCHING_ENTRY_COUNT.get(matchingEntries);
- out.println(message);
- out.println();
- }
- return matchingEntries;
- }
-
- /**
- * Appends an LDIF representation of the entry to the provided buffer.
- *
- * @param entry The entry to be written as LDIF.
- * @param buffer The buffer to which the entry should be appended.
- * @param wrapColumn The column at which long lines should be wrapped.
- * @param typesOnly Indicates whether to include only attribute types
- * without values.
- */
- public void toLDIF(SearchResultEntryProtocolOp entry, StringBuilder buffer,
- int wrapColumn, boolean typesOnly)
- {
- // Add the DN to the buffer.
- String dnString = entry.getDN().toString();
- int colsRemaining;
- if (needsBase64Encoding(dnString))
- {
- dnString = Base64.encode(getBytes(dnString));
- buffer.append("dn:: ");
-
- colsRemaining = wrapColumn - 5;
- }
- else
- {
- buffer.append("dn: ");
-
- colsRemaining = wrapColumn - 4;
- }
-
- int dnLength = dnString.length();
- if (dnLength <= colsRemaining || colsRemaining <= 0)
- {
- buffer.append(dnString);
- buffer.append(EOL);
- }
- else
- {
- buffer.append(dnString, 0, colsRemaining);
- buffer.append(EOL);
-
- int startPos = colsRemaining;
- while (dnLength - startPos > wrapColumn - 1)
- {
- buffer.append(" ");
- buffer.append(dnString, startPos, startPos+wrapColumn-1);
- buffer.append(EOL);
-
- startPos += wrapColumn-1;
- }
-
- if (startPos < dnLength)
- {
- buffer.append(" ");
- buffer.append(dnString.substring(startPos));
- buffer.append(EOL);
- }
- }
-
-
- LinkedList<LDAPAttribute> attributes = entry.getAttributes();
- // Add the attributes to the buffer.
- for (LDAPAttribute a : attributes)
- {
- String name = a.getAttributeType();
- int nameLength = name.length();
-
-
- if(typesOnly)
- {
- buffer.append(name);
- buffer.append(EOL);
- } else
- {
- for (ByteString v : a.getValues())
- {
- String valueString;
- if (needsBase64Encoding(v))
- {
- valueString = Base64.encode(v);
- buffer.append(name);
- buffer.append(":: ");
-
- colsRemaining = wrapColumn - nameLength - 3;
- } else
- {
- valueString = v.toString();
- buffer.append(name);
- buffer.append(": ");
-
- colsRemaining = wrapColumn - nameLength - 2;
- }
-
- int valueLength = valueString.length();
- if (valueLength <= colsRemaining || colsRemaining <= 0)
- {
- buffer.append(valueString);
- buffer.append(EOL);
- } else
- {
- buffer.append(valueString, 0, colsRemaining);
- buffer.append(EOL);
-
- int startPos = colsRemaining;
- while (valueLength - startPos > wrapColumn - 1)
- {
- buffer.append(" ");
- buffer.append(valueString, startPos, startPos+wrapColumn-1);
- buffer.append(EOL);
-
- startPos += wrapColumn-1;
- }
-
- if (startPos < valueLength)
- {
- buffer.append(" ");
- buffer.append(valueString.substring(startPos));
- buffer.append(EOL);
- }
- }
- }
- }
- }
-
-
- // Make sure to add an extra blank line to ensure that there will be one
- // between this entry and the next.
- buffer.append(EOL);
- }
-
- /**
- * Retrieves the set of response controls included in the last search result
- * done message.
- *
- * @return The set of response controls included in the last search result
- * done message.
- */
- public List<Control> getResponseControls()
- {
- return responseControls;
- }
-
- /**
- * The main method for LDAPSearch tool.
- *
- * @param args The command-line arguments provided to this program.
- */
-
- public static void main(String[] args)
- {
- int retCode = mainSearch(args, true, false, System.out, System.err);
-
- if(retCode != 0)
- {
- System.exit(filterExitCode(retCode));
- }
- }
-
- /**
- * Parses the provided command-line arguments and uses that information to
- * run the ldapsearch tool.
- *
- * @param args The command-line arguments provided to this program.
- *
- * @return The error code.
- */
-
- public static int mainSearch(String[] args)
- {
- return mainSearch(args, true, true, System.out, System.err);
- }
-
- /**
- * Parses the provided command-line arguments and uses that information to
- * run the ldapsearch tool.
- *
- * @param args The command-line arguments provided to this
- * program.
- * @param initializeServer Indicates whether to initialize the server.
- * @param outStream The output stream to use for standard output, or
- * <CODE>null</CODE> if standard output is not
- * needed.
- * @param errStream The output stream to use for standard error, or
- * <CODE>null</CODE> if standard error is not
- * needed.
- *
- * @return The error code.
- */
- public static int mainSearch(String[] args, boolean initializeServer,
- OutputStream outStream, OutputStream errStream)
- {
- return mainSearch(args, initializeServer, true, outStream, errStream);
- }
-
- /**
- * Parses the provided command-line arguments and uses that information to
- * run the ldapsearch tool.
- *
- * @param args The command-line arguments provided to this
- * program.
- * @param initializeServer Indicates whether to initialize the server.
- * @param returnMatchingEntries whether when the option --countEntries is
- * specified, the number of matching entries should
- * be returned or not.
- * @param outStream The output stream to use for standard output, or
- * <CODE>null</CODE> if standard output is not
- * needed.
- * @param errStream The output stream to use for standard error, or
- * <CODE>null</CODE> if standard error is not
- * needed.
- *
- * @return The error code.
- */
-
- public static int mainSearch(String[] args, boolean initializeServer,
- boolean returnMatchingEntries, OutputStream outStream,
- OutputStream errStream)
- {
- PrintStream out = NullOutputStream.wrapOrNullStream(outStream);
- PrintStream err = NullOutputStream.wrapOrNullStream(errStream);
-
- LDAPConnectionOptions connectionOptions = new LDAPConnectionOptions();
- LDAPSearchOptions searchOptions = new LDAPSearchOptions();
- LDAPConnection connection = null;
- final List<LDAPFilter> filters = new ArrayList<>();
- final Set<String> attributes = new LinkedHashSet<>();
-
- final BooleanArgument continueOnError;
- final BooleanArgument countEntries;
- final BooleanArgument dontWrap;
- final BooleanArgument noop;
- final BooleanArgument reportAuthzID;
- final BooleanArgument saslExternal;
- final BooleanArgument showUsage;
- final BooleanArgument trustAll;
- final BooleanArgument usePasswordPolicyControl;
- final BooleanArgument useSSL;
- final BooleanArgument startTLS;
- final BooleanArgument typesOnly;
- final BooleanArgument verbose;
- final FileBasedArgument bindPasswordFile;
- final FileBasedArgument keyStorePasswordFile;
- final FileBasedArgument trustStorePasswordFile;
- final IntegerArgument port;
- final IntegerArgument simplePageSize;
- final IntegerArgument sizeLimit;
- final IntegerArgument timeLimit;
- final IntegerArgument version;
- final StringArgument assertionFilter;
- final StringArgument baseDN;
- final StringArgument bindDN;
- final StringArgument bindPassword;
- final StringArgument certNickname;
- final StringArgument controlStr;
- final StringArgument dereferencePolicy;
- final StringArgument encodingStr;
- final StringArgument filename;
- final StringArgument hostName;
- final StringArgument keyStorePath;
- final StringArgument keyStorePassword;
- final StringArgument matchedValuesFilter;
- final StringArgument proxyAuthzID;
- final StringArgument pSearchInfo;
- final StringArgument saslOptions;
- final MultiChoiceArgument searchScope;
- final StringArgument sortOrder;
- final StringArgument trustStorePath;
- final StringArgument trustStorePassword;
- final IntegerArgument connectTimeout;
- final StringArgument vlvDescriptor;
- final StringArgument effectiveRightsUser;
- final StringArgument effectiveRightsAttrs;
- final StringArgument propertiesFileArgument;
- final BooleanArgument noPropertiesFileArgument;
- final BooleanArgument subEntriesArgument ;
-
- // Create the command-line argument parser for use with this program.
- LocalizableMessage toolDescription = INFO_LDAPSEARCH_TOOL_DESCRIPTION.get();
- ArgumentParser argParser = new ArgumentParser(CLASS_NAME, toolDescription,
- false, true, 0, 0,
- "[filter] [attributes ...]");
- argParser.setShortToolDescription(REF_SHORT_DESC_LDAPSEARCH.get());
- argParser.setVersionHandler(new DirectoryServerVersionHandler());
-
- try
- {
- propertiesFileArgument =
- StringArgument.builder(OPTION_LONG_PROP_FILE_PATH)
- .description(INFO_DESCRIPTION_PROP_FILE_PATH.get())
- .valuePlaceholder(INFO_PROP_FILE_PATH_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- argParser.setFilePropertiesArgument(propertiesFileArgument);
-
- noPropertiesFileArgument =
- BooleanArgument.builder(OPTION_LONG_NO_PROP_FILE)
- .description(INFO_DESCRIPTION_NO_PROP_FILE.get())
- .buildAndAddToParser(argParser);
- argParser.setNoPropertiesFileArgument(noPropertiesFileArgument);
-
- hostName =
- StringArgument.builder(OPTION_LONG_HOST)
- .shortIdentifier(OPTION_SHORT_HOST)
- .description(INFO_DESCRIPTION_HOST.get())
- .defaultValue("localhost")
- .valuePlaceholder(INFO_HOST_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- port =
- IntegerArgument.builder(OPTION_LONG_PORT)
- .shortIdentifier(OPTION_SHORT_PORT)
- .description(INFO_DESCRIPTION_PORT.get())
- .range(1, 65535)
- .defaultValue(389)
- .valuePlaceholder(INFO_PORT_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- useSSL =
- BooleanArgument.builder(OPTION_LONG_USE_SSL)
- .shortIdentifier(OPTION_SHORT_USE_SSL)
- .description(INFO_DESCRIPTION_USE_SSL.get())
- .buildAndAddToParser(argParser);
- startTLS =
- BooleanArgument.builder(OPTION_LONG_START_TLS)
- .shortIdentifier(OPTION_SHORT_START_TLS)
- .description(INFO_DESCRIPTION_START_TLS.get())
- .buildAndAddToParser(argParser);
- bindDN =
- StringArgument.builder(OPTION_LONG_BINDDN)
- .shortIdentifier(OPTION_SHORT_BINDDN)
- .description(INFO_DESCRIPTION_BINDDN.get())
- .valuePlaceholder(INFO_BINDDN_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- bindPassword =
- StringArgument.builder(OPTION_LONG_BINDPWD)
- .shortIdentifier(OPTION_SHORT_BINDPWD)
- .description(INFO_DESCRIPTION_BINDPASSWORD.get())
- .valuePlaceholder(INFO_BINDPWD_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- bindPasswordFile =
- FileBasedArgument.builder(OPTION_LONG_BINDPWD_FILE)
- .shortIdentifier(OPTION_SHORT_BINDPWD_FILE)
- .description(INFO_DESCRIPTION_BINDPASSWORDFILE.get())
- .valuePlaceholder(INFO_BINDPWD_FILE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- baseDN =
- StringArgument.builder(OPTION_LONG_BASEDN)
- .shortIdentifier(OPTION_SHORT_BASEDN)
- .description(INFO_SEARCH_DESCRIPTION_BASEDN.get())
- .required()
- .valuePlaceholder(INFO_BASEDN_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- searchScope =
- MultiChoiceArgument.<String>builder("searchScope")
- .shortIdentifier('s')
- .description(INFO_SEARCH_DESCRIPTION_SEARCH_SCOPE.get())
- .allowedValues("base", "one", "sub", "subordinate")
- .defaultValue("sub")
- .valuePlaceholder(INFO_SEARCH_SCOPE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- filename =
- StringArgument.builder(OPTION_LONG_FILENAME)
- .shortIdentifier(OPTION_SHORT_FILENAME)
- .description(INFO_SEARCH_DESCRIPTION_FILENAME.get())
- .valuePlaceholder(INFO_FILE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- saslExternal =
- BooleanArgument.builder("useSASLExternal")
- .shortIdentifier('r')
- .description(INFO_DESCRIPTION_USE_SASL_EXTERNAL.get())
- .buildAndAddToParser(argParser);
- saslOptions =
- StringArgument.builder(OPTION_LONG_SASLOPTION)
- .shortIdentifier(OPTION_SHORT_SASLOPTION)
- .description(INFO_DESCRIPTION_SASL_PROPERTIES.get())
- .multiValued()
- .valuePlaceholder(INFO_SASL_OPTION_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
-
- trustAll = trustAllArgument();
- argParser.addArgument(trustAll);
-
- keyStorePath =
- StringArgument.builder(OPTION_LONG_KEYSTOREPATH)
- .shortIdentifier(OPTION_SHORT_KEYSTOREPATH)
- .description(INFO_DESCRIPTION_KEYSTOREPATH.get())
- .valuePlaceholder(INFO_KEYSTOREPATH_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- keyStorePassword =
- StringArgument.builder(OPTION_LONG_KEYSTORE_PWD)
- .shortIdentifier(OPTION_SHORT_KEYSTORE_PWD)
- .description(INFO_DESCRIPTION_KEYSTOREPASSWORD.get())
- .valuePlaceholder(INFO_KEYSTORE_PWD_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- keyStorePasswordFile =
- FileBasedArgument.builder(OPTION_LONG_KEYSTORE_PWD_FILE)
- .shortIdentifier(OPTION_SHORT_KEYSTORE_PWD_FILE)
- .description(INFO_DESCRIPTION_KEYSTOREPASSWORD_FILE.get())
- .valuePlaceholder(INFO_KEYSTORE_PWD_FILE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- certNickname =
- StringArgument.builder(OPTION_LONG_CERT_NICKNAME)
- .shortIdentifier(OPTION_SHORT_CERT_NICKNAME)
- .description(INFO_DESCRIPTION_CERT_NICKNAME.get())
- .valuePlaceholder(INFO_NICKNAME_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- trustStorePath =
- StringArgument.builder(OPTION_LONG_TRUSTSTOREPATH)
- .shortIdentifier(OPTION_SHORT_TRUSTSTOREPATH)
- .description(INFO_DESCRIPTION_TRUSTSTOREPATH.get())
- .valuePlaceholder(INFO_TRUSTSTOREPATH_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- trustStorePassword =
- StringArgument.builder(OPTION_LONG_TRUSTSTORE_PWD)
- .description(INFO_DESCRIPTION_TRUSTSTOREPASSWORD.get())
- .valuePlaceholder(INFO_TRUSTSTORE_PWD_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- trustStorePasswordFile =
- FileBasedArgument.builder(OPTION_LONG_TRUSTSTORE_PWD_FILE)
- .shortIdentifier(OPTION_SHORT_TRUSTSTORE_PWD_FILE)
- .description(INFO_DESCRIPTION_TRUSTSTOREPASSWORD_FILE.get())
- .valuePlaceholder(INFO_TRUSTSTORE_PWD_FILE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- proxyAuthzID =
- StringArgument.builder(OPTION_LONG_PROXYAUTHID)
- .shortIdentifier(OPTION_SHORT_PROXYAUTHID)
- .description(INFO_DESCRIPTION_PROXY_AUTHZID.get())
- .valuePlaceholder(INFO_PROXYAUTHID_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- reportAuthzID =
- BooleanArgument.builder(OPTION_LONG_REPORT_AUTHZ_ID)
- .shortIdentifier('E')
- .description(INFO_DESCRIPTION_REPORT_AUTHZID.get())
- .buildAndAddToParser(argParser);
- usePasswordPolicyControl =
- BooleanArgument.builder(OPTION_LONG_USE_PW_POLICY_CTL)
- .description(INFO_DESCRIPTION_USE_PWP_CONTROL.get())
- .buildAndAddToParser(argParser);
- pSearchInfo =
- StringArgument.builder("persistentSearch")
- .shortIdentifier('C')
- .description(INFO_DESCRIPTION_PSEARCH_INFO.get())
- .docDescriptionSupplement(SUPPLEMENT_DESCRIPTION_PSEARCH_INFO.get())
- .valuePlaceholder(INFO_PSEARCH_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- simplePageSize =
- IntegerArgument.builder("simplePageSize")
- .description(INFO_DESCRIPTION_SIMPLE_PAGE_SIZE.get())
- .lowerBound(1)
- .defaultValue(1000)
- .valuePlaceholder(INFO_NUM_ENTRIES_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- assertionFilter =
- StringArgument.builder(OPTION_LONG_ASSERTION_FILE)
- .description(INFO_DESCRIPTION_ASSERTION_FILTER.get())
- .valuePlaceholder(INFO_ASSERTION_FILTER_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- matchedValuesFilter =
- StringArgument.builder("matchedValuesFilter")
- .description(INFO_DESCRIPTION_MATCHED_VALUES_FILTER.get())
- .multiValued()
- .valuePlaceholder(INFO_FILTER_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- sortOrder =
- StringArgument.builder("sortOrder")
- .shortIdentifier('S')
- .description(INFO_DESCRIPTION_SORT_ORDER.get())
- .valuePlaceholder(INFO_SORT_ORDER_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- vlvDescriptor =
- StringArgument.builder("virtualListView")
- .shortIdentifier('G')
- .description(INFO_DESCRIPTION_VLV.get())
- .valuePlaceholder(INFO_VLV_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- controlStr =
- StringArgument.builder("control")
- .shortIdentifier('J')
- .description(INFO_DESCRIPTION_CONTROLS.get())
- .docDescriptionSupplement(SUPPLEMENT_DESCRIPTION_CONTROLS.get())
- .multiValued()
- .valuePlaceholder(INFO_LDAP_CONTROL_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- subEntriesArgument =
- BooleanArgument.builder(OPTION_LONG_SUBENTRIES)
- .shortIdentifier(OPTION_SHORT_SUBENTRIES)
- .description(INFO_DESCRIPTION_SUBENTRIES.get())
- .buildAndAddToParser(argParser);
- effectiveRightsUser =
- StringArgument.builder(OPTION_LONG_EFFECTIVERIGHTSUSER)
- .shortIdentifier(OPTION_SHORT_EFFECTIVERIGHTSUSER)
- .description(INFO_DESCRIPTION_EFFECTIVERIGHTS_USER.get())
- .valuePlaceholder(INFO_PROXYAUTHID_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- effectiveRightsAttrs =
- StringArgument.builder(OPTION_LONG_EFFECTIVERIGHTSATTR)
- .shortIdentifier(OPTION_SHORT_EFFECTIVERIGHTSATTR)
- .description(INFO_DESCRIPTION_EFFECTIVERIGHTS_ATTR.get())
- .multiValued()
- .valuePlaceholder(INFO_ATTRIBUTE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- version =
- IntegerArgument.builder(OPTION_LONG_PROTOCOL_VERSION)
- .shortIdentifier(OPTION_SHORT_PROTOCOL_VERSION)
- .description(INFO_DESCRIPTION_VERSION.get())
- .defaultValue(3)
- .valuePlaceholder(INFO_PROTOCOL_VERSION_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- connectTimeout =
- IntegerArgument.builder(OPTION_LONG_CONNECT_TIMEOUT)
- .description(INFO_DESCRIPTION_CONNECTION_TIMEOUT.get())
- .lowerBound(0)
- .defaultValue(CliConstants.DEFAULT_LDAP_CONNECT_TIMEOUT)
- .valuePlaceholder(INFO_TIMEOUT_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- encodingStr =
- StringArgument.builder("encoding")
- .shortIdentifier('i')
- .description(INFO_DESCRIPTION_ENCODING.get())
- .valuePlaceholder(INFO_ENCODING_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- dereferencePolicy =
- StringArgument.builder("dereferencePolicy")
- .shortIdentifier('a')
- .description(INFO_SEARCH_DESCRIPTION_DEREFERENCE_POLICY.get())
- .defaultValue("never")
- .valuePlaceholder(INFO_DEREFERENCE_POLICE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- typesOnly =
- BooleanArgument.builder("typesOnly")
- .shortIdentifier('A')
- .description(INFO_DESCRIPTION_TYPES_ONLY.get())
- .buildAndAddToParser(argParser);
- sizeLimit =
- IntegerArgument.builder("sizeLimit")
- .shortIdentifier('z')
- .description(INFO_SEARCH_DESCRIPTION_SIZE_LIMIT.get())
- .defaultValue(0)
- .valuePlaceholder(INFO_SIZE_LIMIT_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- timeLimit =
- IntegerArgument.builder("timeLimit")
- .shortIdentifier('l')
- .description(INFO_SEARCH_DESCRIPTION_TIME_LIMIT.get())
- .defaultValue(0)
- .valuePlaceholder(INFO_TIME_LIMIT_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- dontWrap =
- BooleanArgument.builder("dontWrap")
- .shortIdentifier('T')
- .description(INFO_DESCRIPTION_DONT_WRAP.get())
- .buildAndAddToParser(argParser);
- countEntries =
- BooleanArgument.builder("countEntries")
- .description(INFO_DESCRIPTION_COUNT_ENTRIES.get())
- .buildAndAddToParser(argParser);
- continueOnError =
- BooleanArgument.builder("continueOnError")
- .shortIdentifier('c')
- .description(INFO_DESCRIPTION_CONTINUE_ON_ERROR.get())
- .buildAndAddToParser(argParser);
- noop =
- BooleanArgument.builder(OPTION_LONG_DRYRUN)
- .shortIdentifier(OPTION_SHORT_DRYRUN)
- .description(INFO_DESCRIPTION_NOOP.get())
- .buildAndAddToParser(argParser);
-
- verbose = verboseArgument();
- argParser.addArgument(verbose);
-
- showUsage = showUsageArgument();
- argParser.addArgument(showUsage);
- argParser.setUsageArgument(showUsage, out);
- } catch (ArgumentException ae)
- {
- printWrappedText(err, ERR_CANNOT_INITIALIZE_ARGS.get(ae.getMessage()));
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
- // Parse the command-line arguments provided to this program.
- try
- {
- argParser.parseArguments(args);
- }
- catch (ArgumentException ae)
- {
- argParser.displayMessageAndUsageReference(err, ERR_ERROR_PARSING_ARGS.get(ae.getMessage()));
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
- // If we should just display usage or version information,
- // then print it and exit.
- if (argParser.usageOrVersionDisplayed())
- {
- return 0;
- }
-
- final List<String> filterAndAttributeStrings = argParser.getTrailingArguments();
- if(!filterAndAttributeStrings.isEmpty())
- {
- // the list of trailing arguments should be structured as follow:
- // - If a filter file is present, trailing arguments are considered
- // as attributes
- // - If filter file is not present, the first trailing argument is
- // considered the filter, the other as attributes.
- if (! filename.isPresent())
- {
- String filterString = filterAndAttributeStrings.remove(0);
-
- try
- {
- filters.add(LDAPFilter.decode(filterString));
- } catch (LDAPException le)
- {
- logger.traceException(le);
- printWrappedText(err, le.getMessage());
- return CLIENT_SIDE_PARAM_ERROR;
- }
- }
- attributes.addAll(filterAndAttributeStrings);
- }
-
- try
- {
- throwIfArgumentsConflict(bindPassword, bindPasswordFile);
- throwIfArgumentsConflict(useSSL, startTLS);
- throwIfArgumentsConflict(keyStorePassword, keyStorePasswordFile);
- throwIfArgumentsConflict(trustStorePassword, trustStorePasswordFile);
- }
- catch (final ArgumentException conflict)
- {
- printWrappedText(err, conflict.getMessageObject());
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
- String hostNameValue = hostName.getValue();
- int portNumber = 389;
- try
- {
- portNumber = port.getIntValue();
- } catch(ArgumentException ae)
- {
- logger.traceException(ae);
- argParser.displayMessageAndUsageReference(err, ae.getMessageObject());
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
- // Read the LDAP version number.
- try
- {
- int versionNumber = version.getIntValue();
- if(versionNumber != 2 && versionNumber != 3)
- {
- printWrappedText(err, ERR_DESCRIPTION_INVALID_VERSION.get(versionNumber));
- return CLIENT_SIDE_PARAM_ERROR;
- }
- connectionOptions.setVersionNumber(versionNumber);
- } catch(ArgumentException ae)
- {
- logger.traceException(ae);
- argParser.displayMessageAndUsageReference(err, ae.getMessageObject());
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
-
- // Indicate whether we should report the authorization ID and/or use the
- // password policy control.
- connectionOptions.setReportAuthzID(reportAuthzID.isPresent());
- connectionOptions.setUsePasswordPolicyControl(
- usePasswordPolicyControl.isPresent());
-
-
- String baseDNValue = baseDN.getValue();
- String bindDNValue = bindDN.getValue();
- String fileNameValue = filename.getValue();
- String bindPasswordValue;
- try
- {
- bindPasswordValue = getPasswordValue(
- bindPassword, bindPasswordFile, bindDNValue, out, err);
- }
- catch (Exception ex)
- {
- logger.traceException(ex);
- printWrappedText(err, ex.getMessage());
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
- String keyStorePathValue = keyStorePath.getValue();
- String trustStorePathValue = trustStorePath.getValue();
-
- String keyStorePasswordValue = null;
- if (keyStorePassword.isPresent())
- {
- keyStorePasswordValue = keyStorePassword.getValue();
- }
- else if (keyStorePasswordFile.isPresent())
- {
- keyStorePasswordValue = keyStorePasswordFile.getValue();
- }
-
- String trustStorePasswordValue = null;
- if (trustStorePassword.isPresent())
- {
- trustStorePasswordValue = trustStorePassword.getValue();
- }
- else if (trustStorePasswordFile.isPresent())
- {
- trustStorePasswordValue = trustStorePasswordFile.getValue();
- }
-
- searchOptions.setTypesOnly(typesOnly.isPresent());
- searchOptions.setShowOperations(noop.isPresent());
- searchOptions.setVerbose(verbose.isPresent());
- searchOptions.setContinueOnError(continueOnError.isPresent());
- searchOptions.setEncoding(encodingStr.getValue());
- searchOptions.setCountMatchingEntries(countEntries.isPresent());
- try
- {
- searchOptions.setTimeLimit(timeLimit.getIntValue());
- searchOptions.setSizeLimit(sizeLimit.getIntValue());
- } catch(ArgumentException ex1)
- {
- argParser.displayMessageAndUsageReference(err, ex1.getMessageObject());
- return CLIENT_SIDE_PARAM_ERROR;
- }
- if (!searchOptions.setSearchScope(searchScope.getValue(), err)
- || !searchOptions.setDereferencePolicy(dereferencePolicy.getValue(), err))
- {
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
- if(controlStr.isPresent())
- {
- for (String ctrlString : controlStr.getValues())
- {
- Control ctrl = LDAPToolUtils.getControl(ctrlString, err);
- if(ctrl == null)
- {
- printWrappedText(err, ERR_TOOL_INVALID_CONTROL_STRING.get(ctrlString));
- return CLIENT_SIDE_PARAM_ERROR;
- }
- searchOptions.getControls().add(ctrl);
- }
- }
-
- if(effectiveRightsUser.isPresent()) {
- String authzID=effectiveRightsUser.getValue();
- if (!authzID.startsWith("dn:")) {
- printWrappedText(err, ERR_EFFECTIVERIGHTS_INVALID_AUTHZID.get(authzID));
- return CLIENT_SIDE_PARAM_ERROR;
- }
- Control effectiveRightsControl =
- new GetEffectiveRightsRequestControl(false, authzID.substring(3),
- effectiveRightsAttrs.getValues());
- searchOptions.getControls().add(effectiveRightsControl);
- }
-
- if (proxyAuthzID.isPresent())
- {
- Control proxyControl =
- new ProxiedAuthV2Control(true,
- ByteString.valueOfUtf8(proxyAuthzID.getValue()));
- searchOptions.getControls().add(proxyControl);
- }
-
- if (pSearchInfo.isPresent())
- {
- String infoString = toLowerCase(pSearchInfo.getValue().trim());
- HashSet<PersistentSearchChangeType> changeTypes = new HashSet<>();
- boolean changesOnly = true;
- boolean returnECs = true;
-
- StringTokenizer tokenizer = new StringTokenizer(infoString, ":");
-
- if (! tokenizer.hasMoreTokens())
- {
- printWrappedText(err, ERR_PSEARCH_MISSING_DESCRIPTOR.get());
- return CLIENT_SIDE_PARAM_ERROR;
- }
- else
- {
- String token = tokenizer.nextToken();
- if (! token.equals("ps"))
- {
- printWrappedText(err, ERR_PSEARCH_DOESNT_START_WITH_PS.get(infoString));
- return CLIENT_SIDE_PARAM_ERROR;
- }
- }
-
- if (tokenizer.hasMoreTokens())
- {
- StringTokenizer st = new StringTokenizer(tokenizer.nextToken(), ", ");
- while (st.hasMoreTokens())
- {
- String token = st.nextToken();
- if (token.equals("add"))
- {
- changeTypes.add(PersistentSearchChangeType.ADD);
- }
- else if (token.equals("delete") || token.equals("del"))
- {
- changeTypes.add(PersistentSearchChangeType.DELETE);
- }
- else if (token.equals("modify") || token.equals("mod"))
- {
- changeTypes.add(PersistentSearchChangeType.MODIFY);
- }
- else if (token.equals("modifydn") || token.equals("moddn") ||
- token.equals("modrdn"))
- {
- changeTypes.add(PersistentSearchChangeType.MODIFY_DN);
- }
- else if (token.equals("any") || token.equals("all"))
- {
- changeTypes.add(PersistentSearchChangeType.ADD);
- changeTypes.add(PersistentSearchChangeType.DELETE);
- changeTypes.add(PersistentSearchChangeType.MODIFY);
- changeTypes.add(PersistentSearchChangeType.MODIFY_DN);
- }
- else
- {
- printWrappedText(err, ERR_PSEARCH_INVALID_CHANGE_TYPE.get(token));
- return CLIENT_SIDE_PARAM_ERROR;
- }
- }
- }
-
- if (changeTypes.isEmpty())
- {
- changeTypes.add(PersistentSearchChangeType.ADD);
- changeTypes.add(PersistentSearchChangeType.DELETE);
- changeTypes.add(PersistentSearchChangeType.MODIFY);
- changeTypes.add(PersistentSearchChangeType.MODIFY_DN);
- }
-
- if (tokenizer.hasMoreTokens())
- {
- String token = tokenizer.nextToken();
- if (token.equals("1") || token.equals("true") || token.equals("yes"))
- {
- changesOnly = true;
- }
- else if (token.equals("0") || token.equals("false") ||
- token.equals("no"))
- {
- changesOnly = false;
- }
- else
- {
- printWrappedText(err, ERR_PSEARCH_INVALID_CHANGESONLY.get(token));
- return CLIENT_SIDE_PARAM_ERROR;
- }
- }
-
- if (tokenizer.hasMoreTokens())
- {
- String token = tokenizer.nextToken();
- if (token.equals("1") || token.equals("true") || token.equals("yes"))
- {
- returnECs = true;
- }
- else if (token.equals("0") || token.equals("false") ||
- token.equals("no"))
- {
- returnECs = false;
- }
- else
- {
- printWrappedText(err, ERR_PSEARCH_INVALID_RETURN_ECS.get(token));
- return CLIENT_SIDE_PARAM_ERROR;
- }
- }
-
- PersistentSearchControl psearchControl =
- new PersistentSearchControl(changeTypes, changesOnly, returnECs);
- searchOptions.getControls().add(psearchControl);
- }
-
- if (assertionFilter.isPresent())
- {
- String filterString = assertionFilter.getValue();
- LDAPFilter filter;
- try
- {
- filter = LDAPFilter.decode(filterString);
-
- // FIXME -- Change this to the correct OID when the official one is
- // assigned.
- Control assertionControl =
- new LDAPAssertionRequestControl(true, filter);
- searchOptions.getControls().add(assertionControl);
- }
- catch (LDAPException le)
- {
- printWrappedText(err, ERR_LDAP_ASSERTION_INVALID_FILTER.get(le.getMessage()));
- return CLIENT_SIDE_PARAM_ERROR;
- }
- }
-
- if (matchedValuesFilter.isPresent())
- {
- List<String> mvFilterStrings = matchedValuesFilter.getValues();
- List<MatchedValuesFilter> mvFilters = new ArrayList<>();
- for (String s : mvFilterStrings)
- {
- try
- {
- LDAPFilter f = LDAPFilter.decode(s);
- mvFilters.add(MatchedValuesFilter.createFromLDAPFilter(f));
- }
- catch (LDAPException le)
- {
- printWrappedText(err, ERR_LDAP_MATCHEDVALUES_INVALID_FILTER.get(le.getMessage()));
- return CLIENT_SIDE_PARAM_ERROR;
- }
- }
-
- MatchedValuesControl mvc = new MatchedValuesControl(true, mvFilters);
- searchOptions.getControls().add(mvc);
- }
-
- if (sortOrder.isPresent())
- {
- try
- {
- searchOptions.getControls().add(
- new ServerSideSortRequestControl(sortOrder.getValue()));
- }
- catch (LDAPException le)
- {
- printWrappedText(err, ERR_LDAP_SORTCONTROL_INVALID_ORDER.get(le.getErrorMessage()));
- return CLIENT_SIDE_PARAM_ERROR;
- }
- }
-
- if (vlvDescriptor.isPresent())
- {
- if (! sortOrder.isPresent())
- {
- printWrappedText(err,
- ERR_LDAPSEARCH_VLV_REQUIRES_SORT.get(vlvDescriptor.getLongIdentifier(), sortOrder.getLongIdentifier()));
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
- StringTokenizer tokenizer =
- new StringTokenizer(vlvDescriptor.getValue(), ":");
- int numTokens = tokenizer.countTokens();
- if (numTokens == 3)
- {
- try
- {
- int beforeCount = Integer.parseInt(tokenizer.nextToken());
- int afterCount = Integer.parseInt(tokenizer.nextToken());
- ByteString assertionValue = ByteString.valueOfUtf8(tokenizer.nextToken());
- searchOptions.getControls().add(
- new VLVRequestControl(beforeCount, afterCount, assertionValue));
- }
- catch (Exception e)
- {
- printWrappedText(err, ERR_LDAPSEARCH_VLV_INVALID_DESCRIPTOR.get());
- return CLIENT_SIDE_PARAM_ERROR;
- }
- }
- else if (numTokens == 4)
- {
- try
- {
- int beforeCount = Integer.parseInt(tokenizer.nextToken());
- int afterCount = Integer.parseInt(tokenizer.nextToken());
- int offset = Integer.parseInt(tokenizer.nextToken());
- int contentCount = Integer.parseInt(tokenizer.nextToken());
- searchOptions.getControls().add(
- new VLVRequestControl(beforeCount, afterCount, offset,
- contentCount));
- }
- catch (Exception e)
- {
- printWrappedText(err, ERR_LDAPSEARCH_VLV_INVALID_DESCRIPTOR.get());
- return CLIENT_SIDE_PARAM_ERROR;
- }
- }
- else
- {
- printWrappedText(err, ERR_LDAPSEARCH_VLV_INVALID_DESCRIPTOR.get());
- return CLIENT_SIDE_PARAM_ERROR;
- }
- }
-
- if (subEntriesArgument.isPresent())
- {
- Control subentriesControl =
- new SubentriesControl(true, true);
- searchOptions.getControls().add(subentriesControl);
- }
-
- // Set the connection options.
- connectionOptions.setSASLExternal(saslExternal.isPresent());
- if(saslOptions.isPresent())
- {
- List<String> values = saslOptions.getValues();
- for(String saslOption : values)
- {
- if(saslOption.startsWith("mech="))
- {
- if (!connectionOptions.setSASLMechanism(saslOption))
- {
- return CLIENT_SIDE_PARAM_ERROR;
- }
- } else
- {
- if (!connectionOptions.addSASLProperty(saslOption))
- {
- return CLIENT_SIDE_PARAM_ERROR;
- }
- }
- }
- }
- connectionOptions.setUseSSL(useSSL.isPresent());
- connectionOptions.setStartTLS(startTLS.isPresent());
-
- if(connectionOptions.useSASLExternal())
- {
- if(!connectionOptions.useSSL() && !connectionOptions.useStartTLS())
- {
- printWrappedText(err, ERR_TOOL_SASLEXTERNAL_NEEDS_SSL_OR_TLS.get());
- return CLIENT_SIDE_PARAM_ERROR;
- }
- if(keyStorePathValue == null)
- {
- printWrappedText(err, ERR_TOOL_SASLEXTERNAL_NEEDS_KEYSTORE.get());
- return CLIENT_SIDE_PARAM_ERROR;
- }
- }
-
- connectionOptions.setVerbose(verbose.isPresent());
-
- // Read the filter strings.
- if(fileNameValue != null)
- {
- BufferedReader in = null;
- try
- {
- in = new BufferedReader(new FileReader(fileNameValue));
- String line = null;
-
- while ((line = in.readLine()) != null)
- {
- if(line.trim().equals(""))
- {
- // ignore empty lines.
- continue;
- }
- LDAPFilter ldapFilter = LDAPFilter.decode(line);
- filters.add(ldapFilter);
- }
- } catch(Exception e)
- {
- logger.traceException(e);
- printWrappedText(err, e.getMessage());
- return CLIENT_SIDE_PARAM_ERROR;
- }
- finally
- {
- close(in);
- }
- }
-
- if(filters.isEmpty())
- {
- argParser.displayMessageAndUsageReference(err, ERR_SEARCH_NO_FILTERS.get());
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
- int wrapColumn = 80;
- if (dontWrap.isPresent())
- {
- wrapColumn = 0;
- }
-
- LDAPSearch ldapSearch = null;
- try
- {
- if (initializeServer)
- {
- DirectoryServer.bootstrapClient();
- }
-
- // Connect to the specified host with the supplied userDN and password.
- SSLConnectionFactory sslConnectionFactory = null;
- if(connectionOptions.useSSL() || connectionOptions.useStartTLS())
- {
- String clientAlias;
- if (certNickname.isPresent())
- {
- clientAlias = certNickname.getValue();
- }
- else
- {
- clientAlias = null;
- }
-
- sslConnectionFactory = new SSLConnectionFactory();
- sslConnectionFactory.init(trustAll.isPresent(), keyStorePathValue,
- keyStorePasswordValue, clientAlias,
- trustStorePathValue, trustStorePasswordValue);
- connectionOptions.setSSLConnectionFactory(sslConnectionFactory);
- }
-
- if (noop.isPresent())
- {
- // We don't actually need to open a connection or perform the search,
- // so we're done. We should return 0 to either mean that the processing
- // was successful or that there were no matching entries, based on
- // countEntries.isPresent() (but in either case the return value should
- // be zero).
- return 0;
- }
-
- AtomicInteger nextMessageID = new AtomicInteger(1);
- connection = new LDAPConnection(hostNameValue, portNumber,
- connectionOptions, out, err);
- int timeout = pSearchInfo.isPresent()?0:connectTimeout.getIntValue();
- connection.connectToHost(bindDNValue, bindPasswordValue, nextMessageID,
- timeout);
-
-
- int matchingEntries = 0;
- if (simplePageSize.isPresent())
- {
- if (filters.size() > 1)
- {
- LocalizableMessage message = ERR_PAGED_RESULTS_REQUIRES_SINGLE_FILTER.get();
- throw new LDAPException(CLIENT_SIDE_PARAM_ERROR, message);
- }
-
- int pageSize = simplePageSize.getIntValue();
- ByteString cookieValue = null;
- ArrayList<Control> origControls = searchOptions.getControls();
-
- while (true)
- {
- ArrayList<Control> newControls = new ArrayList<>(origControls.size() + 1);
- newControls.addAll(origControls);
- newControls.add(new PagedResultsControl(true, pageSize, cookieValue));
- searchOptions.setControls(newControls);
-
- ldapSearch = new LDAPSearch(nextMessageID, out, err);
- matchingEntries += ldapSearch.executeSearch(connection, baseDNValue,
- filters, attributes,
- searchOptions,
- wrapColumn);
-
- List<Control> responseControls =
- ldapSearch.getResponseControls();
- boolean responseFound = false;
- for (Control c : responseControls)
- {
- if (c.getOID().equals(OID_PAGED_RESULTS_CONTROL))
- {
- try
- {
- PagedResultsControl control = PagedResultsControl.DECODER
- .decode(c.isCritical(), ((LDAPControl) c).getValue());
- responseFound = true;
- cookieValue = control.getCookie();
- break;
- }
- catch (DirectoryException de)
- {
- LocalizableMessage message =
- ERR_PAGED_RESULTS_CANNOT_DECODE.get(de.getMessage());
- throw new LDAPException(
- CLIENT_SIDE_DECODING_ERROR, message, de);
- }
- }
- }
-
- if (! responseFound)
- {
- LocalizableMessage message = ERR_PAGED_RESULTS_RESPONSE_NOT_FOUND.get();
- throw new LDAPException(CLIENT_SIDE_CONTROL_NOT_FOUND, message);
- }
- else if (cookieValue.length() == 0)
- {
- break;
- }
- }
- }
- else
- {
- ldapSearch = new LDAPSearch(nextMessageID, out, err);
- matchingEntries = ldapSearch.executeSearch(connection, baseDNValue,
- filters, attributes,
- searchOptions, wrapColumn);
- }
-
- if (countEntries.isPresent() && returnMatchingEntries)
- {
- return matchingEntries;
- }
- else
- {
- return 0;
- }
-
- } catch(LDAPException le)
- {
- int code = le.getResultCode();
- if (code == REFERRAL)
- {
- out.println();
- printWrappedText(out, le.getErrorMessage());
- }
- else
- {
- logger.traceException(le);
-
- LDAPToolUtils.printErrorMessage(err, le.getMessageObject(), code,
- le.getErrorMessage(), le.getMatchedDN());
- }
- return code;
- } catch(LDAPConnectionException lce)
- {
- logger.traceException(lce);
- LDAPToolUtils.printErrorMessage(err,
- lce.getMessageObject(),
- lce.getResultCode(),
- lce.getErrorMessage(),
- lce.getMatchedDN());
- return lce.getResultCode();
- } catch(Exception e)
- {
- logger.traceException(e);
- printWrappedText(err, e.getMessage());
- return 1;
- } finally
- {
- if(connection != null)
- {
- if (ldapSearch == null)
- {
- connection.close(null);
- }
- else
- {
- connection.close(ldapSearch.nextMessageID);
- }
- }
- }
- }
-
-}
-
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPSearchOptions.java b/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPSearchOptions.java
deleted file mode 100644
index abc3715..0000000
--- a/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPSearchOptions.java
+++ /dev/null
@@ -1,238 +0,0 @@
-/*
- * The contents of this file are subject to the terms of the Common Development and
- * Distribution License (the License). You may not use this file except in compliance with the
- * License.
- *
- * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
- * specific language governing permission and limitations under the License.
- *
- * When distributing Covered Software, include this CDDL Header Notice in each file and include
- * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
- * Header, with the fields enclosed by brackets [] replaced by your own identifying
- * information: "Portions Copyright [year] [name of copyright owner]".
- *
- * Copyright 2006-2008 Sun Microsystems, Inc.
- * Portions Copyright 2014-2015 ForgeRock AS.
- */
-package org.opends.server.tools;
-
-import static org.forgerock.opendj.ldap.DereferenceAliasesPolicy.*;
-import static org.forgerock.opendj.ldap.SearchScope.*;
-import static org.opends.messages.ToolMessages.*;
-
-import static com.forgerock.opendj.cli.Utils.*;
-
-import java.io.PrintStream;
-
-import org.forgerock.opendj.ldap.DereferenceAliasesPolicy;
-import org.forgerock.opendj.ldap.SearchScope;
-
-
-
-/**
- * This class defines options for the search operations used
- * by the ldapsearch tool.
- */
-public class LDAPSearchOptions extends LDAPToolOptions
-{
-
- private DereferenceAliasesPolicy dereferencePolicy = NEVER;
- private SearchScope searchScope = WHOLE_SUBTREE;
- private int sizeLimit;
- private int timeLimit;
- private boolean typesOnly;
- private boolean countMatchingEntries;
-
- /**
- * Creates the options instance.
- */
- public LDAPSearchOptions()
- {
- }
-
- /**
- * Set the timeLimit for the operation.
- *
- * @param timeLimit The time limit for the search.
- */
- public void setTimeLimit(int timeLimit)
- {
- this.timeLimit = timeLimit;
- }
-
- /**
- * Return the timeLimit value.
- *
- * @return The timeLimit value.
- */
- public int getTimeLimit()
- {
- return timeLimit;
- }
-
- /**
- * Set the sizeLimit for the operation.
- *
- * @param sizeLimit The size limit for the search.
- *
- */
-
- public void setSizeLimit(int sizeLimit)
- {
- this.sizeLimit = sizeLimit;
- }
-
- /**
- * Return the sizeLimit value.
- *
- * @return The sizeLimit value.
- */
- public int getSizeLimit()
- {
- return sizeLimit;
- }
-
- /**
- * Set the search scope .
- *
- * @param scope The search scope string.
- * @param err A print stream to which error messages should be written if
- * a problem occurs.
- *
- * @return <CODE>true</CODE> if the scope was set properly, or
- * <CODE>false</CODE> if not.
- */
-
- public boolean setSearchScope(String scope, PrintStream err)
- {
- if(scope == null)
- {
- searchScope = WHOLE_SUBTREE;
- }
- else if(scope.equalsIgnoreCase("base"))
- {
- searchScope = BASE_OBJECT;
- } else if(scope.equalsIgnoreCase("one"))
- {
- searchScope = SINGLE_LEVEL;
- } else if (scope.equalsIgnoreCase("sub"))
- {
- searchScope = WHOLE_SUBTREE;
- } else if (scope.equalsIgnoreCase("subordinate"))
- {
- searchScope = SUBORDINATES;
- } else
- {
- printWrappedText(err, ERR_SEARCH_INVALID_SEARCH_SCOPE.get(scope));
- return false;
- }
- return true;
- }
-
- /**
- * Get the search scope value.
- *
- * @return The search scope value.
- */
- public SearchScope getSearchScope()
- {
- return searchScope;
- }
-
- /**
- * Set the dereference policy.
- *
- * @param policy The dereference policy.
- * @param err A print stream to which error messages should be written if
- * a problem occurs.
- *
- * @return <CODE>true</CODE> if the dereference policy was set properly, or
- * <CODE>false</CODE> if not.
- */
-
- public boolean setDereferencePolicy(String policy, PrintStream err)
- {
- if(policy == null)
- {
- dereferencePolicy = NEVER;
- } else if(policy.equals("never"))
- {
- dereferencePolicy = NEVER;
- } else if(policy.equals("always"))
- {
- dereferencePolicy = ALWAYS;
- } else if (policy.equals("search"))
- {
- dereferencePolicy = IN_SEARCHING;
- } else if (policy.equals("find"))
- {
- dereferencePolicy = FINDING_BASE;
- } else
- {
- printWrappedText(err, ERR_SEARCH_INVALID_DEREFERENCE_POLICY.get(policy));
- return false;
- }
- return true;
- }
-
- /**
- * Return the dereference policy.
- *
- * @return The alias dereference policy.
- */
- public DereferenceAliasesPolicy getDereferencePolicy()
- {
- return dereferencePolicy;
- }
-
- /**
- * Return only the attribute types in the search result.
- *
- * @return <CODE>true</CODE> if only attribute types should be returned in
- * matching entries, or <CODE>false</CODE> if both types and values
- * should be included.
- */
- public boolean getTypesOnly()
- {
- return this.typesOnly;
- }
-
-
- /**
- * Return only the attribute types in the search result.
- *
- * @param typesOnly Specifies whether only attribute types should be
- * returned in matching entries, or both types and values.
- */
- public void setTypesOnly(boolean typesOnly)
- {
- this.typesOnly = typesOnly;
- }
-
-
- /**
- * Indicates whether to report the number of matching entries returned by the
- * server.
- *
- * @return {@code true} if the number of matching entries should be reported,
- * or {@code false} if not.
- */
- public boolean countMatchingEntries()
- {
- return countMatchingEntries;
- }
-
-
- /**
- * Specifies whether to report the number of matching entries returned by the
- * server.
- *
- * @param countMatchingEntries Specifies whether to report the number of
- * matching entries returned by the server.
- */
- public void setCountMatchingEntries(boolean countMatchingEntries)
- {
- this.countMatchingEntries = countMatchingEntries;
- }
-}
-
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPToolOptions.java b/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPToolOptions.java
deleted file mode 100644
index 1b3ac77..0000000
--- a/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPToolOptions.java
+++ /dev/null
@@ -1,155 +0,0 @@
-/*
- * The contents of this file are subject to the terms of the Common Development and
- * Distribution License (the License). You may not use this file except in compliance with the
- * License.
- *
- * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
- * specific language governing permission and limitations under the License.
- *
- * When distributing Covered Software, include this CDDL Header Notice in each file and include
- * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
- * Header, with the fields enclosed by brackets [] replaced by your own identifying
- * information: "Portions Copyright [year] [name of copyright owner]".
- *
- * Copyright 2006-2008 Sun Microsystems, Inc.
- * Portions Copyright 2015 ForgeRock AS.
- */
-package org.opends.server.tools;
-
-import java.util.ArrayList;
-import org.opends.server.types.Control;
-
-
-/**
- * This class defines common options for all the operations used
- * by the tools.
- */
-public class LDAPToolOptions
-{
-
- private boolean showOperations;
- private boolean verbose;
- private boolean continueOnError;
- private String encoding = System.getProperty("file.encoding");
- private ArrayList<Control> controls = new ArrayList<>();
-
- /**
- * Creates a the tool options instance.
- *
- */
- public LDAPToolOptions()
- {
- }
-
- /**
- * Set whether to show what would be run but not actually do it.
- *
- * @param showOperations True if we need to show what needs to be done.
- *
- */
-
- public void setShowOperations(boolean showOperations)
- {
- this.showOperations = showOperations;
- }
-
- /**
- * Return the showOperations flag value.
- *
- * @return <CODE>true</CODE> if the operations should only be displayed, or
- * <CODE>false</CODE> if they should actually be performed.
- */
- public boolean showOperations()
- {
- return showOperations;
- }
-
- /**
- * Set verbose flag.
- *
- * @param verbose Indicates whether the tool should operate in verbose mode.
- */
-
- public void setVerbose(boolean verbose)
- {
- this.verbose = verbose;
- }
-
- /**
- * Return the verbose flag value.
- *
- * @return <CODE>true</CODE> if the tool should operate in verbose mode, or
- * <CODE>false</CODE> if not.
- */
- public boolean getVerbose()
- {
- return verbose;
- }
-
- /**
- * Set whether to use continue on error or not.
- *
- * @param continueOnError True if processing should continue on
- * error, false otherwise.
- *
- */
-
- public void setContinueOnError(boolean continueOnError)
- {
- this.continueOnError = continueOnError;
- }
-
- /**
- * Return the continueOnError flag value.
- *
- * @return <CODE>true</CODE> if the tool should continue processing
- * operations if an error occurs with a previous operation, or
- * <CODE>false</CODE> if not.
- */
- public boolean continueOnError()
- {
- return continueOnError;
- }
-
- /**
- * Return the controls to apply to the operation.
- *
- * @return The controls to apply to the operation.
- */
- public ArrayList<Control> getControls()
- {
- return controls;
- }
-
- /**
- * Specifies the set of controls to apply to the operation.
- *
- * @param controls The set of controls to apply to the operation.
- */
- public void setControls(ArrayList<Control> controls)
- {
- this.controls = controls;
- }
-
- /**
- * Set the encoding.
- *
- * @param encodingStr The encoding to use for string values.
- */
- public void setEncoding(String encodingStr)
- {
- this.encoding = encodingStr;
- }
-
- /**
- * Return the encoding value.
- *
- * @return The encoding to use for string values.
- */
- public String getEncoding()
- {
- return encoding;
- }
-
-}
-
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPToolUtils.java b/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPToolUtils.java
deleted file mode 100644
index 01f2f52..0000000
--- a/opendj-server-legacy/src/main/java/org/opends/server/tools/LDAPToolUtils.java
+++ /dev/null
@@ -1,302 +0,0 @@
-/*
- * The contents of this file are subject to the terms of the Common Development and
- * Distribution License (the License). You may not use this file except in compliance with the
- * License.
- *
- * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
- * specific language governing permission and limitations under the License.
- *
- * When distributing Covered Software, include this CDDL Header Notice in each file and include
- * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
- * Header, with the fields enclosed by brackets [] replaced by your own identifying
- * information: "Portions Copyright [year] [name of copyright owner]".
- *
- * Copyright 2006-2010 Sun Microsystems, Inc.
- * Portions Copyright 2011-2016 ForgeRock AS.
- */
-package org.opends.server.tools;
-import static org.opends.messages.ToolMessages.*;
-import static org.opends.server.util.ServerConstants.*;
-import static org.opends.server.util.StaticUtils.*;
-
-import static com.forgerock.opendj.cli.Utils.*;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.PrintStream;
-import java.net.SocketTimeoutException;
-
-import org.forgerock.i18n.LocalizableMessage;
-import org.forgerock.opendj.ldap.ByteString;
-import org.forgerock.opendj.ldap.DecodeException;
-import org.opends.server.protocols.ldap.LDAPControl;
-import org.opends.server.protocols.ldap.LDAPResultCode;
-import org.forgerock.opendj.ldap.DN;
-
-
-
-/**
- * This class provides utility functions for all the client side tools.
- */
-public class LDAPToolUtils
-{
-
-
- /**
- * Parse the specified command line argument to create the
- * appropriate LDAPControl. The argument string should be in the format
- * controloid[:criticality[:value|::b64value|:<fileurl]]
- *
- * @param argString The argument string containing the encoded control
- * information.
- * @param err A print stream to which error messages should be
- * written if a problem occurs.
- *
- * @return The control decoded from the provided string, or <CODE>null</CODE>
- * if an error occurs while parsing the argument value.
- */
- public static LDAPControl getControl(String argString, PrintStream err)
- {
- LDAPControl control = null;
- String controlOID = null;
- boolean controlCriticality = false;
- ByteString controlValue = null;
-
- int idx = argString.indexOf(":");
-
- if(idx < 0)
- {
- controlOID = argString;
- }
- else
- {
- controlOID = argString.substring(0, idx);
- }
-
- String lowerOID = toLowerCase(controlOID);
- if (lowerOID.equals("accountusable") || lowerOID.equals("accountusability"))
- {
- controlOID = OID_ACCOUNT_USABLE_CONTROL;
- }
- else if (lowerOID.equals("authzid") ||
- lowerOID.equals("authorizationidentity"))
- {
- controlOID = OID_AUTHZID_REQUEST;
- }
- else if (lowerOID.equals("noop") || lowerOID.equals("no-op"))
- {
- controlOID = OID_LDAP_NOOP_OPENLDAP_ASSIGNED;
- }
- else if (lowerOID.equals("managedsait"))
- {
- controlOID = OID_MANAGE_DSAIT_CONTROL;
- }
- else if (lowerOID.equals("pwpolicy") || lowerOID.equals("passwordpolicy"))
- {
- controlOID = OID_PASSWORD_POLICY_CONTROL;
- }
- else if (lowerOID.equals("subtreedelete") || lowerOID.equals("treedelete"))
- {
- controlOID = OID_SUBTREE_DELETE_CONTROL;
- }
- else if (lowerOID.equals("realattrsonly") ||
- lowerOID.equals("realattributesonly"))
- {
- controlOID = OID_REAL_ATTRS_ONLY;
- }
- else if (lowerOID.equals("virtualattrsonly") ||
- lowerOID.equals("virtualattributesonly"))
- {
- controlOID = OID_VIRTUAL_ATTRS_ONLY;
- }
- else if(lowerOID.equals("effectiverights") ||
- lowerOID.equals("geteffectiverights"))
- {
- controlOID = OID_GET_EFFECTIVE_RIGHTS;
- }
-
- if (idx < 0)
- {
- return new LDAPControl(controlOID);
- }
-
- String remainder = argString.substring(idx+1, argString.length());
-
- idx = remainder.indexOf(":");
- if(idx == -1)
- {
- if(remainder.equalsIgnoreCase("true"))
- {
- controlCriticality = true;
- } else if(remainder.equalsIgnoreCase("false"))
- {
- controlCriticality = false;
- } else
- {
- printWrappedText(err, "Invalid format for criticality value:" + remainder);
- return null;
- }
- return new LDAPControl(controlOID, controlCriticality);
- }
-
- String critical = remainder.substring(0, idx);
- if(critical.equalsIgnoreCase("true"))
- {
- controlCriticality = true;
- } else if(critical.equalsIgnoreCase("false"))
- {
- controlCriticality = false;
- } else
- {
- printWrappedText(err, "Invalid format for criticality value:" + critical);
- return null;
- }
-
- String valString = remainder.substring(idx+1, remainder.length());
- if (valString.length() == 0)
- {
- return new LDAPControl(controlOID, controlCriticality);
- }
- if(valString.charAt(0) == ':')
- {
- controlValue =
- ByteString.valueOfBase64(valString.substring(1, valString.length()));
- } else if(valString.charAt(0) == '<')
- {
- // Read data from the file.
- String filePath = valString.substring(1, valString.length());
- try
- {
- byte[] val = readBytesFromFile(filePath, err);
- controlValue = ByteString.wrap(val);
- }
- catch (Exception e)
- {
- return null;
- }
- } else
- {
- controlValue = ByteString.valueOfUtf8(valString);
- }
-
- return new LDAPControl(controlOID, controlCriticality, controlValue);
- }
-
- /**
- * Read the data from the specified file and return it in a byte array.
- *
- * @param filePath The path to the file that should be read.
- * @param err A print stream to which error messages should be
- * written if a problem occurs.
- *
- * @return A byte array containing the contents of the requested file.
- *
- * @throws IOException If a problem occurs while trying to read the
- * specified file.
- */
- public static byte[] readBytesFromFile(String filePath, PrintStream err)
- throws IOException
- {
- byte[] val = null;
- FileInputStream fis = null;
- try
- {
- File file = new File(filePath);
- fis = new FileInputStream (file);
- long length = file.length();
- val = new byte[(int)length];
- // Read in the bytes
- int offset = 0;
- int numRead = 0;
- while (offset < val.length &&
- (numRead=fis.read(val, offset, val.length-offset)) >= 0) {
- offset += numRead;
- }
-
- // Ensure all the bytes have been read in
- if (offset < val.length)
- {
- printWrappedText(err, ERR_FILE_NOT_FULLY_READABLE.get(filePath));
- return null;
- }
-
- return val;
- } finally
- {
- if (fis != null)
- {
- fis.close();
- }
- }
- }
-
- /**
- * Prints a multi-line error message with the provided information to the
- * given print stream.
- *
- * @param err The print stream to use to write the error message.
- * @param explanation The general explanation to provide to the user, or
- * {@code null} if there is none.
- * @param resultCode The result code returned from the server, or -1 if
- * there is none.
- * @param errorMessage The additional information / error message returned
- * from the server, or {@code null} if there was none.
- * @param matchedDN The matched DN returned from the server, or
- * {@code null} if there was none.
- */
- public static void printErrorMessage(PrintStream err, LocalizableMessage explanation,
- int resultCode, LocalizableMessage errorMessage,
- DN matchedDN)
- {
- if (explanation != null && explanation.length() > 0)
- {
- err.println(explanation);
- }
-
- if (resultCode >= 0)
- {
- err.println(ERR_TOOL_RESULT_CODE.get(resultCode,
- LDAPResultCode.toString(resultCode)));
- }
-
- if (errorMessage != null && errorMessage.length() > 0)
- {
- err.println(ERR_TOOL_ERROR_MESSAGE.get(errorMessage));
- }
-
- if (matchedDN != null)
- {
- err.println(ERR_TOOL_MATCHED_DN.get(matchedDN));
- }
- }
-
- /**
- * Returns the message to be displayed to the user when an exception occurs.
- * <br>
- * The code simply checks that the exception corresponds to a client side
- * time out.
- * @param ae the DecodeException that occurred connecting to the server or
- * handling the response from the server.
- * @return the message to be displayed to the user when an exception occurs.
- */
- public static String getMessageForConnectionException(DecodeException ae)
- {
- Throwable cause = ae.getCause();
- if (cause != null)
- {
- boolean isTimeout = false;
- while (cause != null && !isTimeout)
- {
- isTimeout = cause instanceof SocketTimeoutException;
- cause = cause.getCause();
- }
- if (isTimeout)
- {
- return ERR_CLIENT_SIDE_TIMEOUT.get(ae.getMessageObject()).toString();
- }
- }
- return ae.getMessageObject().toString();
- }
-}
-
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/tools/LDIFDiff.java b/opendj-server-legacy/src/main/java/org/opends/server/tools/LDIFDiff.java
deleted file mode 100644
index e4c41f8..0000000
--- a/opendj-server-legacy/src/main/java/org/opends/server/tools/LDIFDiff.java
+++ /dev/null
@@ -1,918 +0,0 @@
-/*
- * The contents of this file are subject to the terms of the Common Development and
- * Distribution License (the License). You may not use this file except in compliance with the
- * License.
- *
- * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
- * specific language governing permission and limitations under the License.
- *
- * When distributing Covered Software, include this CDDL Header Notice in each file and include
- * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
- * Header, with the fields enclosed by brackets [] replaced by your own identifying
- * information: "Portions Copyright [year] [name of copyright owner]".
- *
- * Copyright 2006-2009 Sun Microsystems, Inc.
- * Portions Copyright 2013-2016 ForgeRock AS.
- */
-package org.opends.server.tools;
-
-import static com.forgerock.opendj.cli.CommonArguments.*;
-import static com.forgerock.opendj.cli.Utils.*;
-
-import static org.forgerock.opendj.ldap.ModificationType.*;
-import static org.forgerock.opendj.ldap.schema.CoreSchema.*;
-import static org.opends.messages.ToolMessages.*;
-import static org.opends.server.protocols.ldap.LDAPResultCode.*;
-import static org.opends.server.util.CollectionUtils.*;
-import static org.opends.server.util.ServerConstants.*;
-
-import java.io.BufferedReader;
-import java.io.FileReader;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.PrintStream;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedHashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.TreeMap;
-
-import org.forgerock.i18n.LocalizableMessage;
-import org.forgerock.i18n.LocalizedIllegalArgumentException;
-import org.forgerock.opendj.ldap.ByteString;
-import org.forgerock.opendj.ldap.DN;
-import org.forgerock.opendj.ldap.schema.AttributeType;
-import org.forgerock.opendj.ldap.schema.ObjectClass;
-import org.opends.server.core.DirectoryServer;
-import org.opends.server.core.DirectoryServer.DirectoryServerVersionHandler;
-import org.opends.server.loggers.JDKLogging;
-import org.opends.server.types.Attribute;
-import org.opends.server.types.AttributeBuilder;
-import org.opends.server.types.Entry;
-import org.opends.server.types.ExistingFileBehavior;
-import org.opends.server.types.LDIFExportConfig;
-import org.opends.server.types.LDIFImportConfig;
-import org.opends.server.types.Modification;
-import org.opends.server.types.NullOutputStream;
-import org.opends.server.util.LDIFReader;
-import org.opends.server.util.LDIFWriter;
-import org.opends.server.util.StaticUtils;
-
-import com.forgerock.opendj.cli.ArgumentException;
-import com.forgerock.opendj.cli.ArgumentParser;
-import com.forgerock.opendj.cli.BooleanArgument;
-import com.forgerock.opendj.cli.StringArgument;
-
-/**
- * This class provides a program that may be used to determine the differences
- * between two LDIF files, generating the output in LDIF change format. There
- * are several things to note about the operation of this program:
- * <BR>
- * <UL>
- * <LI>This program is only designed for cases in which both LDIF files to be
- * compared will fit entirely in memory at the same time.</LI>
- * <LI>This program will only compare live data in the LDIF files and will
- * ignore comments and other elements that do not have any real impact on
- * the way that the data is interpreted.</LI>
- * <LI>The differences will be generated in such a way as to provide the
- * maximum amount of information, so that there will be enough information
- * for the changes to be reversed (i.e., it will not use the "replace"
- * modification type but only the "add" and "delete" types, and contents
- * of deleted entries will be included as comments).</LI>
- * </UL>
- *
- *
- * Note
- * that this is only an option for cases in which both LDIF files can fit in
- * memory. Also note that this will only compare live data in the LDIF files
- * and will ignore comments and other elements that do not have any real impact
- * on the way that the data is interpreted.
- */
-public class LDIFDiff
-{
- /**
- * The fully-qualified name of this class.
- */
- private static final String CLASS_NAME = "org.opends.server.tools.LDIFDiff";
-
-
-
- /**
- * Provides the command line arguments to the <CODE>mainDiff</CODE> method
- * so that they can be processed.
- *
- * @param args The command line arguments provided to this program.
- */
- public static void main(String[] args)
- {
- int exitCode = mainDiff(args, false, System.out, System.err);
- if (exitCode != 0)
- {
- System.exit(filterExitCode(exitCode));
- }
- }
-
-
-
- /**
- * Parses the provided command line arguments and performs the appropriate
- * LDIF diff operation.
- *
- * @param args The command line arguments provided to this
- * program.
- * @param serverInitialized Indicates whether the Directory Server has
- * already been initialized (and therefore should
- * not be initialized a second time).
- * @param outStream The output stream to use for standard output, or
- * {@code null} if standard output is not needed.
- * @param errStream The output stream to use for standard error, or
- * {@code null} if standard error is not needed.
- *
- * @return The return code for this operation. A value of zero indicates
- * that all processing completed successfully. A nonzero value
- * indicates that some problem occurred during processing.
- */
- public static int mainDiff(String[] args, boolean serverInitialized,
- OutputStream outStream, OutputStream errStream)
- {
- PrintStream out = NullOutputStream.wrapOrNullStream(outStream);
- PrintStream err = NullOutputStream.wrapOrNullStream(errStream);
- JDKLogging.disableLogging();
-
- BooleanArgument overwriteExisting;
- BooleanArgument showUsage;
- BooleanArgument useCompareResultCode;
- BooleanArgument singleValueChanges;
- BooleanArgument doCheckSchema;
- StringArgument configFile;
- StringArgument outputLDIF;
- StringArgument sourceLDIF;
- StringArgument targetLDIF;
- StringArgument ignoreAttrsFile;
- StringArgument ignoreEntriesFile;
-
-
- LocalizableMessage toolDescription = INFO_LDIFDIFF_TOOL_DESCRIPTION.get();
- ArgumentParser argParser = new ArgumentParser(CLASS_NAME, toolDescription,
- false);
- argParser.setShortToolDescription(REF_SHORT_DESC_LDIFDIFF.get());
- argParser.setVersionHandler(new DirectoryServerVersionHandler());
- try
- {
- sourceLDIF =
- StringArgument.builder("sourceLDIF")
- .shortIdentifier('s')
- .description(INFO_LDIFDIFF_DESCRIPTION_SOURCE_LDIF.get())
- .required()
- .valuePlaceholder(INFO_FILE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- targetLDIF =
- StringArgument.builder("targetLDIF")
- .shortIdentifier('t')
- .description(INFO_LDIFDIFF_DESCRIPTION_TARGET_LDIF.get())
- .required()
- .valuePlaceholder(INFO_FILE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- outputLDIF =
- StringArgument.builder("outputLDIF")
- .shortIdentifier('o')
- .description(INFO_LDIFDIFF_DESCRIPTION_OUTPUT_LDIF.get())
- .valuePlaceholder(INFO_FILE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- ignoreAttrsFile =
- StringArgument.builder("ignoreAttrs")
- .shortIdentifier('a')
- .description(INFO_LDIFDIFF_DESCRIPTION_IGNORE_ATTRS.get())
- .valuePlaceholder(INFO_FILE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- ignoreEntriesFile =
- StringArgument.builder("ignoreEntries")
- .shortIdentifier('e')
- .description(INFO_LDIFDIFF_DESCRIPTION_IGNORE_ENTRIES.get())
- .valuePlaceholder(INFO_FILE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- overwriteExisting =
- BooleanArgument.builder("overwriteExisting")
- .shortIdentifier('O')
- .description(INFO_LDIFDIFF_DESCRIPTION_OVERWRITE_EXISTING.get())
- .buildAndAddToParser(argParser);
- singleValueChanges =
- BooleanArgument.builder("singleValueChanges")
- .shortIdentifier('S')
- .description(INFO_LDIFDIFF_DESCRIPTION_SINGLE_VALUE_CHANGES.get())
- .buildAndAddToParser(argParser);
- doCheckSchema =
- BooleanArgument.builder("checkSchema")
- .description(INFO_LDIFDIFF_DESCRIPTION_CHECK_SCHEMA.get())
- .buildAndAddToParser(argParser);
- configFile =
- StringArgument.builder("configFile")
- .shortIdentifier('c')
- .description(INFO_DESCRIPTION_CONFIG_FILE.get())
- .hidden()
- .valuePlaceholder(INFO_CONFIGFILE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
-
- showUsage = showUsageArgument();
- argParser.addArgument(showUsage);
-
- useCompareResultCode =
- BooleanArgument.builder("useCompareResultCode")
- .shortIdentifier('r')
- .description(INFO_LDIFDIFF_DESCRIPTION_USE_COMPARE_RESULT.get())
- .buildAndAddToParser(argParser);
-
- argParser.setUsageArgument(showUsage);
- }
- catch (ArgumentException ae)
- {
- printWrappedText(err, ERR_CANNOT_INITIALIZE_ARGS.get(ae.getMessage()));
- return OPERATIONS_ERROR;
- }
-
-
- // Parse the command-line arguments provided to the program.
- try
- {
- argParser.parseArguments(args);
- }
- catch (ArgumentException ae)
- {
- argParser.displayMessageAndUsageReference(err, ERR_ERROR_PARSING_ARGS.get(ae.getMessage()));
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
-
- // If we should just display usage or version information,
- // then print it and exit.
- if (argParser.usageOrVersionDisplayed())
- {
- return SUCCESS;
- }
-
- if (doCheckSchema.isPresent() && !configFile.isPresent())
- {
- String scriptName = System.getProperty(PROPERTY_SCRIPT_NAME);
- if (scriptName == null)
- {
- scriptName = "ldif-diff";
- }
- LocalizableMessage message = WARN_LDIFDIFF_NO_CONFIG_FILE.get(scriptName);
- err.println(message);
- }
-
-
- boolean checkSchema = configFile.isPresent() && doCheckSchema.isPresent();
- if (! serverInitialized)
- {
- DirectoryServer directoryServer = DirectoryServer.getInstance();
- DirectoryServer.bootstrapClient();
-
-
- // If we're to use the configuration then initialize it, along with the
- // schema.
- if (checkSchema)
- {
- try
- {
- DirectoryServer.initializeJMX();
- }
- catch (Exception e)
- {
- printWrappedText(err, ERR_LDIFDIFF_CANNOT_INITIALIZE_JMX.get(configFile.getValue(), e.getMessage()));
- return OPERATIONS_ERROR;
- }
-
- try
- {
- directoryServer.initializeConfiguration(configFile.getValue());
- }
- catch (Exception e)
- {
- printWrappedText(err, ERR_LDIFDIFF_CANNOT_INITIALIZE_CONFIG.get(configFile.getValue(), e.getMessage()));
- return OPERATIONS_ERROR;
- }
-
- try
- {
- directoryServer.initializeSchema();
- }
- catch (Exception e)
- {
- printWrappedText(err, ERR_LDIFDIFF_CANNOT_INITIALIZE_SCHEMA.get(configFile.getValue(), e.getMessage()));
- return OPERATIONS_ERROR;
- }
- }
- }
-
- // Read in ignored entries and attributes if any
- BufferedReader ignReader = null;
- Collection<DN> ignoreEntries = new HashSet<>();
- Collection<String> ignoreAttrs = new HashSet<>();
-
- if (ignoreAttrsFile.getValue() != null)
- {
- try
- {
- ignReader = new BufferedReader(
- new FileReader(ignoreAttrsFile.getValue()));
- String line = null;
- while ((line = ignReader.readLine()) != null)
- {
- ignoreAttrs.add(line.toLowerCase());
- }
- ignReader.close();
- }
- catch (Exception e)
- {
- printWrappedText(err, ERR_LDIFDIFF_CANNOT_READ_FILE_IGNORE_ATTRIBS.get(ignoreAttrsFile.getValue(), e));
- return OPERATIONS_ERROR;
- }
- finally
- {
- StaticUtils.close(ignReader);
- }
- }
-
- if (ignoreEntriesFile.getValue() != null)
- {
- try
- {
- ignReader = new BufferedReader(
- new FileReader(ignoreEntriesFile.getValue()));
- String line = null;
- while ((line = ignReader.readLine()) != null)
- {
- try
- {
- DN dn = DN.valueOf(line);
- ignoreEntries.add(dn);
- }
- catch (LocalizedIllegalArgumentException e)
- {
- LocalizableMessage message = INFO_LDIFDIFF_CANNOT_PARSE_STRING_AS_DN.get(
- line, ignoreEntriesFile.getValue());
- err.println(message);
- }
- }
- ignReader.close();
- }
- catch (Exception e)
- {
- printWrappedText(err, ERR_LDIFDIFF_CANNOT_READ_FILE_IGNORE_ENTRIES.get(ignoreEntriesFile.getValue(), e));
- return OPERATIONS_ERROR;
- }
- finally
- {
- StaticUtils.close(ignReader);
- }
- }
-
- // Open the source LDIF file and read it into a tree map.
- LDIFReader reader;
- LDIFImportConfig importConfig = new LDIFImportConfig(sourceLDIF.getValue());
- try
- {
- reader = new LDIFReader(importConfig);
- }
- catch (Exception e)
- {
- printWrappedText(err, ERR_LDIFDIFF_CANNOT_OPEN_SOURCE_LDIF.get(sourceLDIF.getValue(), e));
- return OPERATIONS_ERROR;
- }
-
- TreeMap<DN,Entry> sourceMap = new TreeMap<>();
- try
- {
- while (true)
- {
- Entry entry = reader.readEntry(checkSchema);
- if (entry == null)
- {
- break;
- }
-
- if (! ignoreEntries.contains(entry.getName()))
- {
- sourceMap.put(entry.getName(), entry);
- }
- }
- }
- catch (Exception e)
- {
- printWrappedText(err, ERR_LDIFDIFF_ERROR_READING_SOURCE_LDIF.get(sourceLDIF.getValue(), e));
- return OPERATIONS_ERROR;
- }
- finally
- {
- StaticUtils.close(reader);
- }
-
-
- // Open the target LDIF file and read it into a tree map.
- importConfig = new LDIFImportConfig(targetLDIF.getValue());
- try
- {
- reader = new LDIFReader(importConfig);
- }
- catch (Exception e)
- {
- printWrappedText(err, ERR_LDIFDIFF_CANNOT_OPEN_TARGET_LDIF.get(targetLDIF.getValue(), e));
- return OPERATIONS_ERROR;
- }
-
- TreeMap<DN,Entry> targetMap = new TreeMap<>();
- try
- {
- while (true)
- {
- Entry entry = reader.readEntry(checkSchema);
- if (entry == null)
- {
- break;
- }
-
- if (! ignoreEntries.contains(entry.getName()))
- {
- targetMap.put(entry.getName(), entry);
- }
- }
- }
- catch (Exception e)
- {
- printWrappedText(err, ERR_LDIFDIFF_ERROR_READING_TARGET_LDIF.get(targetLDIF.getValue(), e));
- return OPERATIONS_ERROR;
- }
- finally
- {
- StaticUtils.close(reader);
- }
-
-
- // Open the output writer that we'll use to write the differences.
- LDIFWriter writer;
- try
- {
- LDIFExportConfig exportConfig;
- if (outputLDIF.isPresent())
- {
- if (overwriteExisting.isPresent())
- {
- exportConfig = new LDIFExportConfig(outputLDIF.getValue(),
- ExistingFileBehavior.OVERWRITE);
- }
- else
- {
- exportConfig = new LDIFExportConfig(outputLDIF.getValue(),
- ExistingFileBehavior.APPEND);
- }
- }
- else
- {
- exportConfig = new LDIFExportConfig(out);
- }
-
- writer = new LDIFWriter(exportConfig);
- }
- catch (Exception e)
- {
- printWrappedText(err, ERR_LDIFDIFF_CANNOT_OPEN_OUTPUT.get(e));
- return OPERATIONS_ERROR;
- }
-
-
- try
- {
- boolean differenceFound;
-
- // Check to see if either or both of the source and target maps are empty.
- if (sourceMap.isEmpty())
- {
- if (targetMap.isEmpty())
- {
- // They're both empty, so there are no differences.
- differenceFound = false;
- }
- else
- {
- // The target isn't empty, so they're all adds.
- Iterator<DN> targetIterator = targetMap.keySet().iterator();
- while (targetIterator.hasNext())
- {
- writeAdd(writer, targetMap.get(targetIterator.next()));
- }
- differenceFound = true;
- }
- }
- else if (targetMap.isEmpty())
- {
- // The source isn't empty, so they're all deletes.
- Iterator<DN> sourceIterator = sourceMap.keySet().iterator();
- while (sourceIterator.hasNext())
- {
- writeDelete(writer, sourceMap.get(sourceIterator.next()));
- }
- differenceFound = true;
- }
- else
- {
- differenceFound = false;
- // Iterate through all the entries in the source and target maps and
- // identify the differences.
- Iterator<DN> sourceIterator = sourceMap.keySet().iterator();
- Iterator<DN> targetIterator = targetMap.keySet().iterator();
- DN sourceDN = sourceIterator.next();
- DN targetDN = targetIterator.next();
- Entry sourceEntry = sourceMap.get(sourceDN);
- Entry targetEntry = targetMap.get(targetDN);
-
- while (true)
- {
- // Compare the DNs to determine the relative order of the
- // entries.
- int comparatorValue = sourceDN.compareTo(targetDN);
- if (comparatorValue < 0)
- {
- // The source entry should be before the target entry, which means
- // that the source entry has been deleted.
- writeDelete(writer, sourceEntry);
- differenceFound = true;
- if (sourceIterator.hasNext())
- {
- sourceDN = sourceIterator.next();
- sourceEntry = sourceMap.get(sourceDN);
- }
- else
- {
- // There are no more source entries, so if there are more target
- // entries then they're all adds.
- writeAdd(writer, targetEntry);
-
- while (targetIterator.hasNext())
- {
- targetDN = targetIterator.next();
- targetEntry = targetMap.get(targetDN);
- writeAdd(writer, targetEntry);
- differenceFound = true;
- }
-
- break;
- }
- }
- else if (comparatorValue > 0)
- {
- // The target entry should be before the source entry, which means
- // that the target entry has been added.
- writeAdd(writer, targetEntry);
- differenceFound = true;
- if (targetIterator.hasNext())
- {
- targetDN = targetIterator.next();
- targetEntry = targetMap.get(targetDN);
- }
- else
- {
- // There are no more target entries so all of the remaining source
- // entries are deletes.
- writeDelete(writer, sourceEntry);
- differenceFound = true;
- while (sourceIterator.hasNext())
- {
- sourceDN = sourceIterator.next();
- sourceEntry = sourceMap.get(sourceDN);
- writeDelete(writer, sourceEntry);
- }
-
- break;
- }
- }
- else
- {
- // The DNs are the same, so check to see if the entries are the
- // same or have been modified.
- if (writeModify(writer, sourceEntry, targetEntry, ignoreAttrs,
- singleValueChanges.isPresent()))
- {
- differenceFound = true;
- }
-
- if (sourceIterator.hasNext())
- {
- sourceDN = sourceIterator.next();
- sourceEntry = sourceMap.get(sourceDN);
- }
- else
- {
- // There are no more source entries, so if there are more target
- // entries then they're all adds.
- while (targetIterator.hasNext())
- {
- targetDN = targetIterator.next();
- targetEntry = targetMap.get(targetDN);
- writeAdd(writer, targetEntry);
- differenceFound = true;
- }
-
- break;
- }
-
- if (targetIterator.hasNext())
- {
- targetDN = targetIterator.next();
- targetEntry = targetMap.get(targetDN);
- }
- else
- {
- // There are no more target entries so all of the remaining source
- // entries are deletes.
- writeDelete(writer, sourceEntry);
- differenceFound = true;
- while (sourceIterator.hasNext())
- {
- sourceDN = sourceIterator.next();
- sourceEntry = sourceMap.get(sourceDN);
- writeDelete(writer, sourceEntry);
- }
-
- break;
- }
- }
- }
- }
-
- if (!differenceFound)
- {
- LocalizableMessage message = INFO_LDIFDIFF_NO_DIFFERENCES.get();
- writer.writeComment(message, 0);
- }
- if (useCompareResultCode.isPresent())
- {
- return !differenceFound ? COMPARE_TRUE : COMPARE_FALSE;
- }
- }
- catch (IOException e)
- {
- printWrappedText(err, ERR_LDIFDIFF_ERROR_WRITING_OUTPUT.get(e));
- return OPERATIONS_ERROR;
- }
- finally
- {
- StaticUtils.close(writer);
- }
-
-
- // If we've gotten to this point, then everything was successful.
- return SUCCESS;
- }
-
-
-
- /**
- * Writes an add change record to the LDIF writer.
- *
- * @param writer The writer to which the add record should be written.
- * @param entry The entry that has been added.
- *
- * @throws IOException If a problem occurs while attempting to write the add
- * record.
- */
- private static void writeAdd(LDIFWriter writer, Entry entry)
- throws IOException
- {
- writer.writeAddChangeRecord(entry);
- writer.flush();
- }
-
-
-
- /**
- * Writes a delete change record to the LDIF writer, including a comment
- * with the contents of the deleted entry.
- *
- * @param writer The writer to which the delete record should be written.
- * @param entry The entry that has been deleted.
- *
- * @throws IOException If a problem occurs while attempting to write the
- * delete record.
- */
- private static void writeDelete(LDIFWriter writer, Entry entry)
- throws IOException
- {
- writer.writeDeleteChangeRecord(entry, true);
- writer.flush();
- }
-
-
-
- /**
- * Writes a modify change record to the LDIF writer. Note that this will
- * handle all the necessary logic for determining if the entries are actually
- * different, and if they are the same then no output will be generated. Also
- * note that this will only look at differences between the objectclasses and
- * user attributes. It will ignore differences in the DN and operational
- * attributes.
- *
- * @param writer The writer to which the modify record should be
- * written.
- * @param sourceEntry The source form of the entry.
- * @param targetEntry The target form of the entry.
- * @param ignoreAttrs Attributes that are ignored while calculating
- * the differences.
- * @param singleValueChanges Indicates whether each attribute-level change
- * should be written in a separate modification
- * per attribute value.
- *
- * @return <CODE>true</CODE> if there were any differences found between the
- * source and target entries, or <CODE>false</CODE> if not.
- *
- * @throws IOException If a problem occurs while attempting to write the
- * change record.
- */
- private static boolean writeModify(LDIFWriter writer, Entry sourceEntry,
- Entry targetEntry, Collection<String> ignoreAttrs, boolean singleValueChanges)
- throws IOException
- {
- // Create a list to hold the modifications that are found.
- LinkedList<Modification> modifications = new LinkedList<>();
-
-
- // Look at the set of objectclasses for the entries.
- LinkedHashSet<ObjectClass> sourceClasses = new LinkedHashSet<>(sourceEntry.getObjectClasses().keySet());
- LinkedHashSet<ObjectClass> targetClasses = new LinkedHashSet<>(targetEntry.getObjectClasses().keySet());
- Iterator<ObjectClass> sourceClassIterator = sourceClasses.iterator();
- while (sourceClassIterator.hasNext())
- {
- ObjectClass sourceClass = sourceClassIterator.next();
- if (targetClasses.remove(sourceClass))
- {
- sourceClassIterator.remove();
- }
- }
-
- if (!sourceClasses.isEmpty())
- {
- // Whatever is left must have been deleted.
- modifications.add(new Modification(DELETE, toObjectClassAttribute(sourceClasses)));
- }
-
- if (! targetClasses.isEmpty())
- {
- // Whatever is left must have been added.
- modifications.add(new Modification(ADD, toObjectClassAttribute(targetClasses)));
- }
-
-
- // Look at the user attributes for the entries.
- LinkedHashSet<AttributeType> sourceTypes = new LinkedHashSet<>(sourceEntry.getUserAttributes().keySet());
- Iterator<AttributeType> sourceTypeIterator = sourceTypes.iterator();
- while (sourceTypeIterator.hasNext())
- {
- AttributeType type = sourceTypeIterator.next();
- List<Attribute> sourceAttrs = sourceEntry.getUserAttribute(type);
- List<Attribute> targetAttrs = targetEntry.getUserAttribute(type);
- sourceEntry.removeAttribute(type);
-
- if (targetAttrs == null)
- {
- // The target entry doesn't have this attribute type, so it must have
- // been deleted. In order to make the delete reversible, delete each
- // value individually.
- for (Attribute a : sourceAttrs)
- {
- modifications.add(new Modification(DELETE, a));
- }
- }
- else
- {
- // Check the attributes for differences. We'll ignore differences in
- // the order of the values since that isn't significant.
- targetEntry.removeAttribute(type);
-
- for (Attribute sourceAttr : sourceAttrs)
- {
- Attribute targetAttr = null;
- Iterator<Attribute> attrIterator = targetAttrs.iterator();
- while (attrIterator.hasNext())
- {
- Attribute a = attrIterator.next();
- if (a.getAttributeDescription().equals(sourceAttr.getAttributeDescription()))
- {
- targetAttr = a;
- attrIterator.remove();
- break;
- }
- }
-
- if (targetAttr == null)
- {
- // The attribute doesn't exist in the target list, so it has been deleted.
- modifications.add(new Modification(DELETE, sourceAttr));
- }
- else
- {
- // Compare the values.
- Attribute addedValues = minusAttribute(targetAttr, sourceAttr);
- if (!addedValues.isEmpty())
- {
- modifications.add(new Modification(ADD, addedValues));
- }
-
- Attribute deletedValues = minusAttribute(sourceAttr, targetAttr);
- if (!deletedValues.isEmpty())
- {
- modifications.add(new Modification(DELETE, deletedValues));
- }
- }
- }
-
-
- // Any remaining target attributes have been added.
- for (Attribute targetAttr: targetAttrs)
- {
- modifications.add(new Modification(ADD, targetAttr));
- }
- }
- }
-
- // Any remaining target attribute types have been added.
- for (AttributeType type : targetEntry.getUserAttributes().keySet())
- {
- for (Attribute a : targetEntry.getUserAttribute(type))
- {
- modifications.add(new Modification(ADD, a));
- }
- }
-
- // Remove ignored attributes
- if (! ignoreAttrs.isEmpty())
- {
- ListIterator<Modification> modIter = modifications.listIterator();
- while (modIter.hasNext())
- {
- String name = modIter.next().getAttribute().getAttributeDescription().getNameOrOID().toLowerCase();
- if (ignoreAttrs.contains(name))
- {
- modIter.remove();
- }
- }
- }
-
- // Write the modification change record.
- if (modifications.isEmpty())
- {
- return false;
- }
-
- if (singleValueChanges)
- {
- for (Modification m : modifications)
- {
- Attribute a = m.getAttribute();
- if (a.isEmpty())
- {
- writer.writeModifyChangeRecord(sourceEntry.getName(), newLinkedList(m));
- }
- else
- {
- LinkedList<Modification> attrMods = new LinkedList<>();
- for (ByteString v : a)
- {
- AttributeBuilder builder = new AttributeBuilder(a.getAttributeDescription());
- builder.add(v);
- Attribute attr = builder.toAttribute();
-
- attrMods.clear();
- attrMods.add(new Modification(m.getModificationType(), attr));
- writer.writeModifyChangeRecord(sourceEntry.getName(), attrMods);
- }
- }
- }
- }
- else
- {
- writer.writeModifyChangeRecord(sourceEntry.getName(), modifications);
- }
-
- return true;
- }
-
- private static Attribute toObjectClassAttribute(Collection<ObjectClass> objectClasses)
- {
- AttributeBuilder builder = new AttributeBuilder(getObjectClassAttributeType());
- for (ObjectClass oc : objectClasses)
- {
- builder.add(oc.getNameOrOID());
- }
- return builder.toAttribute();
- }
-
- private static Attribute minusAttribute(Attribute sourceAttr, Attribute removeAttr)
- {
- AttributeBuilder builder = new AttributeBuilder(sourceAttr);
- builder.removeAll(removeAttr);
- return builder.toAttribute();
- }
-}
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/tools/LDIFModify.java b/opendj-server-legacy/src/main/java/org/opends/server/tools/LDIFModify.java
deleted file mode 100644
index 4454a80..0000000
--- a/opendj-server-legacy/src/main/java/org/opends/server/tools/LDIFModify.java
+++ /dev/null
@@ -1,614 +0,0 @@
-/*
- * The contents of this file are subject to the terms of the Common Development and
- * Distribution License (the License). You may not use this file except in compliance with the
- * License.
- *
- * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
- * specific language governing permission and limitations under the License.
- *
- * When distributing Covered Software, include this CDDL Header Notice in each file and include
- * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
- * Header, with the fields enclosed by brackets [] replaced by your own identifying
- * information: "Portions Copyright [year] [name of copyright owner]".
- *
- * Copyright 2006-2008 Sun Microsystems, Inc.
- * Portions Copyright 2012-2016 ForgeRock AS.
- */
-package org.opends.server.tools;
-
-import static org.opends.messages.ToolMessages.*;
-import static org.opends.server.protocols.ldap.LDAPResultCode.*;
-import static org.opends.server.util.StaticUtils.*;
-import static com.forgerock.opendj.cli.CommonArguments.*;
-import static com.forgerock.opendj.cli.Utils.*;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.PrintStream;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.TreeMap;
-
-import org.forgerock.i18n.LocalizableMessage;
-import org.forgerock.opendj.ldap.ByteString;
-import org.forgerock.opendj.ldap.DN;
-import org.forgerock.opendj.ldap.schema.AttributeType;
-import org.forgerock.opendj.ldap.schema.ObjectClass;
-import org.opends.server.core.DirectoryServer;
-import org.opends.server.core.DirectoryServer.DirectoryServerVersionHandler;
-import org.opends.server.loggers.JDKLogging;
-import org.opends.server.types.Attribute;
-import org.opends.server.types.DirectoryException;
-import org.opends.server.types.Entry;
-import org.opends.server.types.ExistingFileBehavior;
-import org.opends.server.types.InitializationException;
-import org.opends.server.types.LDAPException;
-import org.opends.server.types.LDIFExportConfig;
-import org.opends.server.types.LDIFImportConfig;
-import org.opends.server.types.Modification;
-import org.opends.server.types.NullOutputStream;
-import org.opends.server.types.RawModification;
-import org.opends.server.util.AddChangeRecordEntry;
-import org.opends.server.util.BuildVersion;
-import org.opends.server.util.ChangeRecordEntry;
-import org.opends.server.util.DeleteChangeRecordEntry;
-import org.opends.server.util.LDIFException;
-import org.opends.server.util.LDIFReader;
-import org.opends.server.util.LDIFWriter;
-import org.opends.server.util.ModifyChangeRecordEntry;
-
-import com.forgerock.opendj.cli.ArgumentException;
-import com.forgerock.opendj.cli.ArgumentParser;
-import com.forgerock.opendj.cli.BooleanArgument;
-import com.forgerock.opendj.cli.StringArgument;
-
-/**
- * This class provides a program that may be used to apply a set of changes (in
- * LDIF change format) to an LDIF file. It will first read all of the changes
- * into memory, and then will iterate through an LDIF file and apply them to the
- * entries contained in it. Note that because of the manner in which it
- * processes the changes, certain types of operations will not be allowed,
- * including:
- * <BR>
- * <UL>
- * <LI>Modify DN operations</LI>
- * <LI>Deleting an entry that has been added</LI>
- * <LI>Modifying an entry that has been added</LI>
- * </UL>
- */
-public class LDIFModify
-{
- /**
- * The fully-qualified name of this class.
- */
- private static final String CLASS_NAME = "org.opends.server.tools.LDIFModify";
-
-
-
- /**
- * Applies the specified changes to the source LDIF, writing the modified
- * file to the specified target. Neither the readers nor the writer will be
- * closed.
- *
- * @param sourceReader The LDIF reader that will be used to read the LDIF
- * content to be modified.
- * @param changeReader The LDIF reader that will be used to read the changes
- * to be applied.
- * @param targetWriter The LDIF writer that will be used to write the
- * modified LDIF.
- * @param errorList A list into which any error messages generated while
- * processing changes may be added.
- *
- * @return <CODE>true</CODE> if all updates were successfully applied, or
- * <CODE>false</CODE> if any errors were encountered.
- *
- * @throws IOException If a problem occurs while attempting to read the
- * source or changes, or write the target.
- *
- * @throws LDIFException If a problem occurs while attempting to decode the
- * source or changes, or trying to determine whether
- * to include the entry in the output.
- */
- public static boolean modifyLDIF(LDIFReader sourceReader,
- LDIFReader changeReader,
- LDIFWriter targetWriter,
- List<LocalizableMessage> errorList)
- throws IOException, LDIFException
- {
- // Read the changes into memory.
- TreeMap<DN,AddChangeRecordEntry> adds = new TreeMap<>();
- TreeMap<DN,Entry> ldifEntries = new TreeMap<>();
- HashMap<DN,DeleteChangeRecordEntry> deletes = new HashMap<>();
- HashMap<DN,LinkedList<Modification>> modifications = new HashMap<>();
-
- while (true)
- {
- ChangeRecordEntry changeRecord;
- try
- {
- changeRecord = changeReader.readChangeRecord(false);
- }
- catch (LDIFException le)
- {
- if (le.canContinueReading())
- {
- errorList.add(le.getMessageObject());
- continue;
- }
- else
- {
- throw le;
- }
- }
-
- if (changeRecord == null)
- {
- break;
- }
-
- DN changeDN = changeRecord.getDN();
- switch (changeRecord.getChangeOperationType())
- {
- case ADD:
- // The entry must not exist in the add list.
- if (adds.containsKey(changeDN))
- {
- errorList.add(ERR_LDIFMODIFY_CANNOT_ADD_ENTRY_TWICE.get(changeDN));
- continue;
- }
- else
- {
- adds.put(changeDN, (AddChangeRecordEntry) changeRecord);
- }
- break;
-
- case DELETE:
- // The entry must not exist in the add list. If it exists in the
- // modify list, then remove the changes since we won't need to apply
- // them.
- if (adds.containsKey(changeDN))
- {
- errorList.add(ERR_LDIFMODIFY_CANNOT_DELETE_AFTER_ADD.get(changeDN));
- continue;
- }
- else
- {
- modifications.remove(changeDN);
- deletes.put(changeDN, (DeleteChangeRecordEntry) changeRecord);
- }
- break;
-
- case MODIFY:
- // The entry must not exist in the add or delete lists.
- if (adds.containsKey(changeDN) || deletes.containsKey(changeDN))
- {
- errorList.add(ERR_LDIFMODIFY_CANNOT_MODIFY_ADDED_OR_DELETED.get(changeDN));
- continue;
- }
- else
- {
- LinkedList<Modification> mods =
- modifications.get(changeDN);
- if (mods == null)
- {
- mods = new LinkedList<>();
- modifications.put(changeDN, mods);
- }
-
- for (RawModification mod :
- ((ModifyChangeRecordEntry) changeRecord).getModifications())
- {
- try
- {
- mods.add(mod.toModification());
- }
- catch (LDAPException le)
- {
- errorList.add(le.getMessageObject());
- continue;
- }
- }
- }
- break;
-
- case MODIFY_DN:
- errorList.add(ERR_LDIFMODIFY_MODDN_NOT_SUPPORTED.get(changeDN));
- continue;
-
- default:
- errorList.add(ERR_LDIFMODIFY_UNKNOWN_CHANGETYPE.get(changeDN, changeRecord.getChangeOperationType()));
- continue;
- }
- }
-
-
- // Read the source an entry at a time and apply any appropriate changes
- // before writing to the target LDIF.
- while (true)
- {
- Entry entry;
- try
- {
- entry = sourceReader.readEntry();
- }
- catch (LDIFException le)
- {
- if (le.canContinueReading())
- {
- errorList.add(le.getMessageObject());
- continue;
- }
- else
- {
- throw le;
- }
- }
-
- if (entry == null)
- {
- break;
- }
-
-
- // If the entry is to be deleted, then just skip over it without writing
- // it to the output.
- DN entryDN = entry.getName();
- if (deletes.remove(entryDN) != null)
- {
- continue;
- }
-
-
- // If the entry is to be added, then that's an error, since it already
- // exists.
- if (adds.remove(entryDN) != null)
- {
- errorList.add(ERR_LDIFMODIFY_ADD_ALREADY_EXISTS.get(entryDN));
- continue;
- }
-
-
- // If the entry is to be modified, then process the changes.
- LinkedList<Modification> mods = modifications.remove(entryDN);
- if (mods != null && !mods.isEmpty())
- {
- try
- {
- entry.applyModifications(mods);
- }
- catch (DirectoryException de)
- {
- errorList.add(de.getMessageObject());
- continue;
- }
- }
-
-
- // If we've gotten here, then the (possibly updated) entry should be
- // written to the LDIF entry Map.
- ldifEntries.put(entry.getName(),entry);
- }
-
-
- // Perform any adds that may be necessary.
- for (AddChangeRecordEntry add : adds.values())
- {
- Map<ObjectClass,String> objectClasses = new LinkedHashMap<>();
- Map<AttributeType,List<Attribute>> userAttributes = new LinkedHashMap<>();
- Map<AttributeType,List<Attribute>> operationalAttributes = new LinkedHashMap<>();
-
- for (Attribute a : add.getAttributes())
- {
- AttributeType t = a.getAttributeDescription().getAttributeType();
- if (t.isObjectClass())
- {
- for (ByteString v : a)
- {
- String ocName = v.toString();
- objectClasses.put(DirectoryServer.getSchema().getObjectClass(ocName), ocName);
- }
- }
- else if (t.isOperational())
- {
- List<Attribute> attrList = operationalAttributes.get(t);
- if (attrList == null)
- {
- attrList = new LinkedList<>();
- operationalAttributes.put(t, attrList);
- }
- attrList.add(a);
- }
- else
- {
- List<Attribute> attrList = userAttributes.get(t);
- if (attrList == null)
- {
- attrList = new LinkedList<>();
- userAttributes.put(t, attrList);
- }
- attrList.add(a);
- }
- }
-
- Entry e = new Entry(add.getDN(), objectClasses, userAttributes,
- operationalAttributes);
- //Put the entry to be added into the LDIF entry map.
- ldifEntries.put(e.getName(),e);
- }
-
-
- // If there are any entries left in the delete or modify lists, then that's
- // a problem because they didn't exist.
- if (! deletes.isEmpty())
- {
- for (DN dn : deletes.keySet())
- {
- errorList.add(ERR_LDIFMODIFY_DELETE_NO_SUCH_ENTRY.get(dn));
- }
- }
-
- if (! modifications.isEmpty())
- {
- for (DN dn : modifications.keySet())
- {
- errorList.add(ERR_LDIFMODIFY_MODIFY_NO_SUCH_ENTRY.get(dn));
- }
- }
- return targetWriter.writeEntries(ldifEntries.values()) &&
- errorList.isEmpty();
- }
-
-
-
- /**
- * Invokes <CODE>ldifModifyMain</CODE> to perform the appropriate processing.
- *
- * @param args The command-line arguments provided to the client.
- */
- public static void main(String[] args)
- {
- int returnCode = ldifModifyMain(args, false, System.out, System.err);
- if (returnCode != 0)
- {
- System.exit(filterExitCode(returnCode));
- }
- }
-
-
-
- /**
- * Processes the command-line arguments and makes the appropriate updates to
- * the LDIF file.
- *
- * @param args The command line arguments provided to this
- * program.
- * @param serverInitialized Indicates whether the Directory Server has
- * already been initialized (and therefore should
- * not be initialized a second time).
- * @param outStream The output stream to use for standard output, or
- * {@code null} if standard output is not needed.
- * @param errStream The output stream to use for standard error, or
- * {@code null} if standard error is not needed.
- *
- * @return A value of zero if everything completed properly, or nonzero if
- * any problem(s) occurred.
- */
- public static int ldifModifyMain(String[] args, boolean serverInitialized,
- OutputStream outStream,
- OutputStream errStream)
- {
- PrintStream err = NullOutputStream.wrapOrNullStream(errStream);
- JDKLogging.disableLogging();
-
- // Prepare the argument parser.
- BooleanArgument showUsage;
- StringArgument changesFile;
- StringArgument configFile;
- StringArgument sourceFile;
- StringArgument targetFile;
-
- LocalizableMessage toolDescription = INFO_LDIFMODIFY_TOOL_DESCRIPTION.get();
- ArgumentParser argParser = new ArgumentParser(CLASS_NAME, toolDescription,
- false);
- argParser.setShortToolDescription(REF_SHORT_DESC_LDIFMODIFY.get());
- argParser.setVersionHandler(new DirectoryServerVersionHandler());
-
- try
- {
- configFile =
- StringArgument.builder("configFile")
- .shortIdentifier('c')
- .description(INFO_DESCRIPTION_CONFIG_FILE.get())
- .hidden()
- .required()
- .valuePlaceholder(INFO_CONFIGFILE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- sourceFile =
- StringArgument.builder("sourceLDIF")
- .shortIdentifier('s')
- .description(INFO_LDIFMODIFY_DESCRIPTION_SOURCE.get())
- .required()
- .valuePlaceholder(INFO_LDIFFILE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- changesFile =
- StringArgument.builder("changesLDIF")
- .shortIdentifier('m')
- .description(INFO_LDIFMODIFY_DESCRIPTION_CHANGES.get())
- .required()
- .valuePlaceholder(INFO_LDIFFILE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- targetFile =
- StringArgument.builder("targetLDIF")
- .shortIdentifier('t')
- .description(INFO_LDIFMODIFY_DESCRIPTION_TARGET.get())
- .required()
- .valuePlaceholder(INFO_LDIFFILE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
-
- showUsage = showUsageArgument();
- argParser.addArgument(showUsage);
- argParser.setUsageArgument(showUsage);
- }
- catch (ArgumentException ae)
- {
- printWrappedText(err, ERR_CANNOT_INITIALIZE_ARGS.get(ae.getMessage()));
- return 1;
- }
-
-
- // Parse the command-line arguments provided to the program.
- try
- {
- argParser.parseArguments(args);
- }
- catch (ArgumentException ae)
- {
- argParser.displayMessageAndUsageReference(err, ERR_ERROR_PARSING_ARGS.get(ae.getMessage()));
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
-
- // If we should just display usage or version information,
- // then print it and exit.
- if (argParser.usageOrVersionDisplayed())
- {
- return 0;
- }
-
- // Checks the version - if upgrade required, the tool is unusable
- try
- {
- BuildVersion.checkVersionMismatch();
- }
- catch (InitializationException e)
- {
- printWrappedText(err, e.getMessage());
- return 1;
- }
-
- if (! serverInitialized)
- {
- DirectoryServer directoryServer = DirectoryServer.getInstance();
- DirectoryServer.bootstrapClient();
-
-
- // If we're to use the configuration then initialize it, along with the
- // schema.
- boolean checkSchema = configFile.isPresent();
- if (checkSchema)
- {
- try
- {
- DirectoryServer.initializeJMX();
- }
- catch (Exception e)
- {
- printWrappedText(err, ERR_LDIFMODIFY_CANNOT_INITIALIZE_JMX.get(configFile.getValue(), e.getMessage()));
- return 1;
- }
-
- try
- {
- directoryServer.initializeConfiguration(configFile.getValue());
- }
- catch (Exception e)
- {
- printWrappedText(err, ERR_LDIFMODIFY_CANNOT_INITIALIZE_CONFIG.get(configFile.getValue(), e.getMessage()));
- return 1;
- }
-
- try
- {
- directoryServer.initializeSchema();
- }
- catch (Exception e)
- {
- printWrappedText(err, ERR_LDIFMODIFY_CANNOT_INITIALIZE_SCHEMA.get(configFile.getValue(), e.getMessage()));
- return 1;
- }
- }
- }
-
-
- // Create the LDIF readers and writer from the arguments.
- File source = new File(sourceFile.getValue());
- if (! source.exists())
- {
- printWrappedText(err, ERR_LDIFMODIFY_SOURCE_DOES_NOT_EXIST.get(sourceFile.getValue()));
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
- LDIFImportConfig importConfig = new LDIFImportConfig(sourceFile.getValue());
- LDIFReader sourceReader;
- try
- {
- sourceReader = new LDIFReader(importConfig);
- }
- catch (IOException ioe)
- {
- printWrappedText(err, ERR_LDIFMODIFY_CANNOT_OPEN_SOURCE.get(sourceFile.getValue(), ioe));
- return CLIENT_SIDE_LOCAL_ERROR;
- }
-
-
- File changes = new File(changesFile.getValue());
- if (! changes.exists())
- {
- printWrappedText(err, ERR_LDIFMODIFY_CHANGES_DOES_NOT_EXIST.get(changesFile.getValue()));
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
- importConfig = new LDIFImportConfig(changesFile.getValue());
- LDIFReader changeReader;
- try
- {
- changeReader = new LDIFReader(importConfig);
- }
- catch (IOException ioe)
- {
- printWrappedText(err, ERR_LDIFMODIFY_CANNOT_OPEN_CHANGES.get(sourceFile.getValue(), ioe.getMessage()));
- return CLIENT_SIDE_LOCAL_ERROR;
- }
-
-
- LDIFExportConfig exportConfig =
- new LDIFExportConfig(targetFile.getValue(),
- ExistingFileBehavior.OVERWRITE);
- LDIFWriter targetWriter;
- try
- {
- targetWriter = new LDIFWriter(exportConfig);
- }
- catch (IOException ioe)
- {
- printWrappedText(err, ERR_LDIFMODIFY_CANNOT_OPEN_TARGET.get(sourceFile.getValue(), ioe.getMessage()));
- return CLIENT_SIDE_LOCAL_ERROR;
- }
-
-
- // Actually invoke the LDIF processing.
- LinkedList<LocalizableMessage> errorList = new LinkedList<>();
- boolean successful;
- try
- {
- successful = modifyLDIF(sourceReader, changeReader, targetWriter, errorList);
- }
- catch (Exception e)
- {
- err.println(ERR_LDIFMODIFY_ERROR_PROCESSING_LDIF.get(e));
- successful = false;
- }
-
- close(sourceReader, changeReader, targetWriter);
-
- for (LocalizableMessage s : errorList)
- {
- err.println(s);
- }
- return successful ? 0 : 1;
- }
-}
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/tools/LDIFSearch.java b/opendj-server-legacy/src/main/java/org/opends/server/tools/LDIFSearch.java
deleted file mode 100644
index 9f4ca64..0000000
--- a/opendj-server-legacy/src/main/java/org/opends/server/tools/LDIFSearch.java
+++ /dev/null
@@ -1,782 +0,0 @@
-/*
- * The contents of this file are subject to the terms of the Common Development and
- * Distribution License (the License). You may not use this file except in compliance with the
- * License.
- *
- * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
- * specific language governing permission and limitations under the License.
- *
- * When distributing Covered Software, include this CDDL Header Notice in each file and include
- * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
- * Header, with the fields enclosed by brackets [] replaced by your own identifying
- * information: "Portions Copyright [year] [name of copyright owner]".
- *
- * Copyright 2006-2008 Sun Microsystems, Inc.
- * Portions Copyright 2013-2016 ForgeRock AS.
- */
-package org.opends.server.tools;
-
-import static com.forgerock.opendj.cli.ArgumentConstants.*;
-import static com.forgerock.opendj.cli.Utils.*;
-import static com.forgerock.opendj.cli.CommonArguments.*;
-
-import static org.opends.messages.ToolMessages.*;
-import static org.opends.server.util.CollectionUtils.*;
-import static org.opends.server.protocols.ldap.LDAPResultCode.*;
-import static org.opends.server.util.StaticUtils.*;
-
-import java.io.BufferedReader;
-import java.io.FileReader;
-import java.io.OutputStream;
-import java.io.PrintStream;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.LinkedHashSet;
-import java.util.LinkedList;
-
-import org.forgerock.i18n.LocalizableMessage;
-import org.forgerock.opendj.ldap.DN;
-import org.forgerock.opendj.ldap.SearchScope;
-import org.opends.server.core.DirectoryServer;
-import org.opends.server.core.DirectoryServer.DirectoryServerVersionHandler;
-import org.opends.server.loggers.JDKLogging;
-import org.opends.server.protocols.ldap.LDAPResultCode;
-import org.forgerock.opendj.ldap.schema.AttributeType;
-import org.forgerock.opendj.ldap.schema.ObjectClass;
-import org.opends.server.types.*;
-import org.opends.server.util.BuildVersion;
-import org.opends.server.util.LDIFException;
-import org.opends.server.util.LDIFReader;
-import org.opends.server.util.LDIFWriter;
-
-import com.forgerock.opendj.cli.*;
-
-/**
- * This class provides a program that may be used to search LDIF files. It is
- * modeled after the LDAPSearch tool, with the primary differencing being that
- * all of its data comes from LDIF rather than communicating over LDAP.
- * However, it does have a number of differences that allow it to perform
- * multiple operations in a single pass rather than requiring multiple passes
- * through the LDIF.
- */
-public class LDIFSearch
-{
- /** The fully-qualified name of this class. */
- private static final String CLASS_NAME = "org.opends.server.tools.LDIFSearch";
-
- /** The search scope string that will be used for baseObject searches. */
- private static final String SCOPE_STRING_BASE = "base";
- /** The search scope string that will be used for singleLevel searches. */
- private static final String SCOPE_STRING_ONE = "one";
- /** The search scope string that will be used for wholeSubtree searches. */
- private static final String SCOPE_STRING_SUB = "sub";
- /** The search scope string that will be used for subordinateSubtree searches. */
- private static final String SCOPE_STRING_SUBORDINATE = "subordinate";
-
- /**
- * Provides the command line arguments to the <CODE>mainSearch</CODE> method
- * so that they can be processed.
- *
- * @param args The command line arguments provided to this program.
- */
- public static void main(String[] args)
- {
- int exitCode = mainSearch(args, true, System.out, System.err);
- if (exitCode != 0)
- {
- System.exit(filterExitCode(exitCode));
- }
- }
-
-
-
- /**
- * Parses the provided command line arguments and performs the appropriate
- * search operation.
- *
- * @param args The command line arguments provided to this
- * program.
- * @param initializeServer True if server initialization should be done.
- * @param outStream The output stream to use for standard output, or
- * {@code null} if standard output is not needed.
- * @param errStream The output stream to use for standard error, or
- * {@code null} if standard error is not needed.
- *
- * @return The return code for this operation. A value of zero indicates
- * that all processing completed successfully. A nonzero value
- * indicates that some problem occurred during processing.
- */
- public static int mainSearch(String[] args, boolean initializeServer,
- OutputStream outStream, OutputStream errStream)
- {
- PrintStream out = NullOutputStream.wrapOrNullStream(outStream);
- PrintStream err = NullOutputStream.wrapOrNullStream(errStream);
- JDKLogging.disableLogging();
-
- LinkedHashSet<String> scopeStrings = new LinkedHashSet<>(4);
- scopeStrings.add(SCOPE_STRING_BASE);
- scopeStrings.add(SCOPE_STRING_ONE);
- scopeStrings.add(SCOPE_STRING_SUB);
- scopeStrings.add(SCOPE_STRING_SUBORDINATE);
-
-
- BooleanArgument dontWrap;
- BooleanArgument overwriteExisting;
- BooleanArgument showUsage;
- StringArgument filterFile;
- IntegerArgument sizeLimit;
- IntegerArgument timeLimit;
- MultiChoiceArgument<String> scopeString;
- StringArgument baseDNString;
- StringArgument configFile;
- StringArgument ldifFile;
- StringArgument outputFile;
-
-
- LocalizableMessage toolDescription = INFO_LDIFSEARCH_TOOL_DESCRIPTION.get();
- ArgumentParser argParser = new ArgumentParser(CLASS_NAME, toolDescription,
- false, true, 0, 0,
- "[filter] [attributes ...]");
- argParser.setShortToolDescription(REF_SHORT_DESC_LDIFSEARCH.get());
- argParser.setVersionHandler(new DirectoryServerVersionHandler());
-
- try
- {
- ldifFile =
- StringArgument.builder("ldifFile")
- .shortIdentifier('l')
- .description(INFO_LDIFSEARCH_DESCRIPTION_LDIF_FILE.get())
- .multiValued()
- .valuePlaceholder(INFO_LDIFFILE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- baseDNString =
- StringArgument.builder(OPTION_LONG_BASEDN)
- .shortIdentifier(OPTION_SHORT_BASEDN)
- .description(INFO_LDIFSEARCH_DESCRIPTION_BASEDN.get())
- .multiValued()
- .defaultValue("")
- .valuePlaceholder(INFO_BASEDN_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- scopeString =
- MultiChoiceArgument.<String>builder("searchScope")
- .shortIdentifier('s')
- .description(INFO_LDIFSEARCH_DESCRIPTION_SCOPE.get())
- .allowedValues(scopeStrings)
- .defaultValue(SCOPE_STRING_SUB)
- .valuePlaceholder(INFO_SCOPE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- configFile =
- StringArgument.builder("configFile")
- .shortIdentifier('c')
- .description(INFO_DESCRIPTION_CONFIG_FILE.get())
- .hidden()
- .valuePlaceholder(INFO_CONFIGFILE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- filterFile =
- StringArgument.builder("filterFile")
- .shortIdentifier('f')
- .description(INFO_LDIFSEARCH_DESCRIPTION_FILTER_FILE.get())
- .valuePlaceholder(INFO_FILTER_FILE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- outputFile =
- StringArgument.builder("outputFile")
- .shortIdentifier('o')
- .description(INFO_LDIFSEARCH_DESCRIPTION_OUTPUT_FILE.get())
- .valuePlaceholder(INFO_OUTPUT_FILE_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- overwriteExisting =
- BooleanArgument.builder("overwriteExisting")
- .shortIdentifier('O')
- .description(INFO_LDIFSEARCH_DESCRIPTION_OVERWRITE_EXISTING.get())
- .buildAndAddToParser(argParser);
- dontWrap =
- BooleanArgument.builder("dontWrap")
- .shortIdentifier('T')
- .description(INFO_LDIFSEARCH_DESCRIPTION_DONT_WRAP.get())
- .buildAndAddToParser(argParser);
- sizeLimit =
- IntegerArgument.builder("sizeLimit")
- .shortIdentifier('z')
- .description(INFO_LDIFSEARCH_DESCRIPTION_SIZE_LIMIT.get())
- .lowerBound(0)
- .defaultValue(0)
- .valuePlaceholder(INFO_SIZE_LIMIT_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
- timeLimit =
- IntegerArgument.builder("timeLimit")
- .shortIdentifier('t')
- .description(INFO_LDIFSEARCH_DESCRIPTION_TIME_LIMIT.get())
- .lowerBound(0)
- .defaultValue(0)
- .valuePlaceholder(INFO_TIME_LIMIT_PLACEHOLDER.get())
- .buildAndAddToParser(argParser);
-
- showUsage = showUsageArgument();
- argParser.addArgument(showUsage);
- argParser.setUsageArgument(showUsage);
- }
- catch (ArgumentException ae)
- {
- printWrappedText(err, ERR_CANNOT_INITIALIZE_ARGS.get(ae.getMessage()));
- return 1;
- }
-
-
- // Parse the command-line arguments provided to the program.
- try
- {
- argParser.parseArguments(args);
- }
- catch (ArgumentException ae)
- {
- argParser.displayMessageAndUsageReference(err, ERR_ERROR_PARSING_ARGS.get(ae.getMessage()));
- return CLIENT_SIDE_PARAM_ERROR;
- }
-
-
- // If we should just display usage or version information,
- // then print it and exit.
- if (argParser.usageOrVersionDisplayed())
- {
- return 0;
- }
-
- // Checks the version - if upgrade required, the tool is unusable
- try
- {
- BuildVersion.checkVersionMismatch();
- }
- catch (InitializationException e)
- {
- printWrappedText(err, e.getMessage());
- return 1;
- }
-
- // Make sure that at least one filter was provided. Also get the attribute
- // list at the same time because it may need to be specified in the same
- // way.
- boolean allUserAttrs = false;
- boolean allOperationalAttrs = false;
- //Return objectclass attribute unless analysis of the arguments determines
- //otherwise.
- boolean includeObjectclassAttrs = true;
- final LinkedList<String> attributeNames = new LinkedList<>();
- LinkedList<String> objectClassNames = new LinkedList<>();
- LinkedList<String> filterStrings = new LinkedList<>();
- if (filterFile.isPresent())
- {
- BufferedReader in = null;
- try
- {
- String fileNameValue = filterFile.getValue();
- in = new BufferedReader(new FileReader(fileNameValue));
- String line = null;
-
- while ((line = in.readLine()) != null)
- {
- if(line.trim().equals(""))
- {
- // ignore empty lines.
- continue;
- }
- filterStrings.add(line);
- }
- } catch(Exception e)
- {
- printWrappedText(err, e.getMessage());
- return 1;
- }
- finally
- {
- close(in);
- }
-
- ArrayList<String> trailingArguments = argParser.getTrailingArguments();
- if (trailingArguments != null && !trailingArguments.isEmpty())
- {
- for (String attributeName : trailingArguments)
- {
- String lowerName = toLowerCase(attributeName);
- if (lowerName.equals("*"))
- {
- allUserAttrs = true;
- }
- else if (lowerName.equals("+"))
- {
- allOperationalAttrs = true;
- }
- else if (lowerName.startsWith("@"))
- {
- objectClassNames.add(lowerName.substring(1));
- }
- else
- {
- attributeNames.add(lowerName);
- }
- }
- }
- }
- else
- {
- ArrayList<String> trailingArguments = argParser.getTrailingArguments();
- if (trailingArguments == null || trailingArguments.isEmpty())
- {
- argParser.displayMessageAndUsageReference(err, ERR_LDIFSEARCH_NO_FILTER.get());
- return 1;
- }
-
- Iterator<String> iterator = trailingArguments.iterator();
- filterStrings = newLinkedList(iterator.next());
-
- while (iterator.hasNext())
- {
- String lowerName = toLowerCase(iterator.next());
- if (lowerName.equals("*"))
- {
- allUserAttrs = true;
- }
- else if (lowerName.equals("+"))
- {
- allOperationalAttrs = true;
- }
- else if (lowerName.startsWith("@"))
- {
- objectClassNames.add(lowerName.substring(1));
- }
- else
- {
- attributeNames.add(lowerName);
- }
- }
- }
-
- if (attributeNames.isEmpty()
- && objectClassNames.isEmpty()
- && !allOperationalAttrs)
- {
- // This will be true if no attributes were requested, which is effectively
- // all user attributes. It will also be true if just "*" was included,
- // but the net result will be the same.
- allUserAttrs = true;
- }
-
- //Determine if objectclass attribute should be returned.
- if(!allUserAttrs) {
- //Single '+', never return objectclass.
- if(allOperationalAttrs && objectClassNames.isEmpty() &&
- attributeNames.isEmpty())
- {
- includeObjectclassAttrs=false;
- }
- //If "objectclass" isn't specified in the attributes to return, then
- //don't include objectclass attribute.
- if(!attributeNames.isEmpty() && objectClassNames.isEmpty() &&
- !attributeNames.contains("objectclass"))
- {
- includeObjectclassAttrs=false;
- }
- }
-
-
- // Bootstrap the Directory Server configuration for use as a client.
- DirectoryServer directoryServer = DirectoryServer.getInstance();
-
- // If we're to use the configuration then initialize it, along with the
- // schema.
- boolean checkSchema = configFile.isPresent();
-
- if (initializeServer)
- {
- DirectoryServer.bootstrapClient();
-
- if (checkSchema)
- {
- try
- {
- DirectoryServer.initializeJMX();
- }
- catch (Exception e)
- {
- printWrappedText(err, ERR_LDIFSEARCH_CANNOT_INITIALIZE_JMX.get(configFile.getValue(), e.getMessage()));
- return 1;
- }
-
- try
- {
- directoryServer.initializeConfiguration(configFile.getValue());
- }
- catch (Exception e)
- {
- printWrappedText(err, ERR_LDIFSEARCH_CANNOT_INITIALIZE_CONFIG.get(configFile.getValue(), e.getMessage()));
- return 1;
- }
-
- try
- {
- directoryServer.initializeSchema();
- }
- catch (Exception e)
- {
- printWrappedText(err, ERR_LDIFSEARCH_CANNOT_INITIALIZE_SCHEMA.get(configFile.getValue(), e.getMessage()));
- return 1;
- }
- }
- }
-
- // Choose the desired search scope.
- SearchScope searchScope;
- if (scopeString.isPresent())
- {
- String scopeStr = toLowerCase(scopeString.getValue());
- if (scopeStr.equals(SCOPE_STRING_BASE))
- {
- searchScope = SearchScope.BASE_OBJECT;
- }
- else if (scopeStr.equals(SCOPE_STRING_ONE))
- {
- searchScope = SearchScope.SINGLE_LEVEL;
- }
- else if (scopeStr.equals(SCOPE_STRING_SUBORDINATE))
- {
- searchScope = SearchScope.SUBORDINATES;
- }
- else
- {
- searchScope = SearchScope.WHOLE_SUBTREE;
- }
- }
- else
- {
- searchScope = SearchScope.WHOLE_SUBTREE;
- }
-
-
- // Create the list of filters that will be used to process the searches.
- LinkedList<SearchFilter> searchFilters = new LinkedList<>();
- for (String filterString : filterStrings)
- {
- try
- {
- searchFilters.add(SearchFilter.createFilterFromString(filterString));
- }
- catch (Exception e)
- {
- printWrappedText(err, ERR_LDIFSEARCH_CANNOT_PARSE_FILTER.get(filterString, e.getMessage()));
- return 1;
- }
- }
-
-
- // Transform the attributes to return from strings to attribute types.
- LinkedHashSet<AttributeType> userAttributeTypes = new LinkedHashSet<>();
- LinkedHashSet<AttributeType> operationalAttributeTypes = new LinkedHashSet<>();
- for (String attributeName : attributeNames)
- {
- AttributeType t = DirectoryServer.getSchema().getAttributeType(attributeName);
- if (t.isOperational())
- {
- operationalAttributeTypes.add(t);
- }
- else
- {
- userAttributeTypes.add(t);
- }
- }
-
- for (String objectClassName : objectClassNames)
- {
- ObjectClass c = DirectoryServer.getSchema().getObjectClass(objectClassName);
- for (AttributeType t : c.getRequiredAttributes())
- {
- if (t.isOperational())
- {
- operationalAttributeTypes.add(t);
- }
- else
- {
- userAttributeTypes.add(t);
- }
- }
-
- for (AttributeType t : c.getOptionalAttributes())
- {
- if (t.isOperational())
- {
- operationalAttributeTypes.add(t);
- }
- else
- {
- userAttributeTypes.add(t);
- }
- }
- }
-
-
- // Set the base DNs for the import config.
- LinkedList<DN> baseDNs = new LinkedList<>();
- if (baseDNString.isPresent())
- {
- for (String dnString : baseDNString.getValues())
- {
- try
- {
- baseDNs.add(DN.valueOf(dnString));
- }
- catch (Exception e)
- {
- printWrappedText(err, ERR_LDIFSEARCH_CANNOT_PARSE_BASE_DN.get(dnString, e.getMessage()));
- return 1;
- }
- }
- }
- else
- {
- baseDNs.add(DN.rootDN());
- }
-
-
- // Get the time limit in milliseconds.
- long timeLimitMillis;
- try
- {
- if (timeLimit.isPresent())
- {
- timeLimitMillis = 1000L * timeLimit.getIntValue();
- }
- else
- {
- timeLimitMillis = 0;
- }
- }
- catch (Exception e)
- {
- printWrappedText(err, ERR_LDIFSEARCH_CANNOT_PARSE_TIME_LIMIT.get(e));
- return 1;
- }
-
-
- // Convert the size limit to an integer.
- int sizeLimitValue;
- try
- {
- if (sizeLimit.isPresent())
- {
- sizeLimitValue = sizeLimit.getIntValue();
- }
- else
- {
- sizeLimitValue =0;
- }
- }
- catch (Exception e)
- {
- printWrappedText(err, ERR_LDIFSEARCH_CANNOT_PARSE_SIZE_LIMIT.get(e));
- return 1;
- }
-
-
- // Create the LDIF import configuration that will be used to read the source
- // data.
- LDIFImportConfig importConfig;
- if (ldifFile.isPresent())
- {
- importConfig = new LDIFImportConfig(ldifFile.getValues());
- }
- else
- {
- importConfig = new LDIFImportConfig(System.in);
- }
-
-
- // Create the LDIF export configuration that will be used to write the
- // matching entries.
- LDIFExportConfig exportConfig;
- if (outputFile.isPresent())
- {
- if (overwriteExisting.isPresent())
- {
- exportConfig = new LDIFExportConfig(outputFile.getValue(),
- ExistingFileBehavior.OVERWRITE);
- }
- else
- {
- exportConfig = new LDIFExportConfig(outputFile.getValue(),
- ExistingFileBehavior.APPEND);
- }
- }
- else
- {
- exportConfig = new LDIFExportConfig(out);
- }
-
- exportConfig.setIncludeObjectClasses(includeObjectclassAttrs);
- if (dontWrap.isPresent())
- {
- exportConfig.setWrapColumn(0);
- }
- else
- {
- exportConfig.setWrapColumn(75);
- }
-
-
- // Create the LDIF reader/writer from the import/export config.
- LDIFReader reader;
- LDIFWriter writer;
- try
- {
- reader = new LDIFReader(importConfig);
- }
- catch (Exception e)
- {
- printWrappedText(err, ERR_LDIFSEARCH_CANNOT_CREATE_READER.get(e));
- return 1;
- }
-
- try
- {
- writer = new LDIFWriter(exportConfig);
- }
- catch (Exception e)
- {
- close(reader);
- printWrappedText(err, ERR_LDIFSEARCH_CANNOT_CREATE_WRITER.get(e));
- return 1;
- }
-
-
- // Start reading data from the LDIF reader.
- long startTime = System.currentTimeMillis();
- long stopTime = startTime + timeLimitMillis;
- long matchCount = 0;
- int resultCode = LDAPResultCode.SUCCESS;
- while (true)
- {
- // If the time limit has been reached, then stop now.
- if (timeLimitMillis > 0 && System.currentTimeMillis() > stopTime)
- {
- resultCode = LDAPResultCode.TIME_LIMIT_EXCEEDED;
-
- LocalizableMessage message = WARN_LDIFSEARCH_TIME_LIMIT_EXCEEDED.get();
- err.println(message);
- break;
- }
-
-
- try
- {
- Entry entry = reader.readEntry(checkSchema);
- if (entry == null)
- {
- break;
- }
-
-
- // Check to see if the entry has an acceptable base and scope.
- boolean matchesBaseAndScope = false;
- for (DN baseDN : baseDNs)
- {
- if (entry.matchesBaseAndScope(baseDN, searchScope))
- {
- matchesBaseAndScope = true;
- break;
- }
- }
-
- if (! matchesBaseAndScope)
- {
- continue;
- }
-
-
- // Check to see if the entry matches any of the filters.
- boolean matchesFilter = false;
- for (SearchFilter filter : searchFilters)
- {
- if (filter.matchesEntry(entry))
- {
- matchesFilter = true;
- break;
- }
- }
-
- if (! matchesFilter)
- {
- continue;
- }
-
-
- // Prepare the entry to return to the client.
- if (! allUserAttrs)
- {
- Iterator<AttributeType> iterator =
- entry.getUserAttributes().keySet().iterator();
- while (iterator.hasNext())
- {
- if (! userAttributeTypes.contains(iterator.next()))
- {
- iterator.remove();
- }
- }
- }
-
- if (! allOperationalAttrs)
- {
- Iterator<AttributeType> iterator =
- entry.getOperationalAttributes().keySet().iterator();
- while (iterator.hasNext())
- {
- if (! operationalAttributeTypes.contains(iterator.next()))
- {
- iterator.remove();
- }
- }
- }
-
-
- // Write the entry to the client and increase the count.
- // FIXME -- Should we include a comment about which base+filter matched?
- writer.writeEntry(entry);
- writer.flush();
-
- matchCount++;
- if (sizeLimitValue > 0 && matchCount >= sizeLimitValue)
- {
- resultCode = LDAPResultCode.SIZE_LIMIT_EXCEEDED;
-
- LocalizableMessage message = WARN_LDIFSEARCH_SIZE_LIMIT_EXCEEDED.get();
- err.println(message);
- break;
- }
- }
- catch (LDIFException le)
- {
- if (le.canContinueReading())
- {
- LocalizableMessage message = ERR_LDIFSEARCH_CANNOT_READ_ENTRY_RECOVERABLE.get(
- le.getMessage());
- err.println(message);
- }
- else
- {
- LocalizableMessage message = ERR_LDIFSEARCH_CANNOT_READ_ENTRY_FATAL.get(
- le.getMessage());
- err.println(message);
- resultCode = LDAPResultCode.CLIENT_SIDE_LOCAL_ERROR;
- break;
- }
- }
- catch (Exception e)
- {
- err.println(ERR_LDIFSEARCH_ERROR_DURING_PROCESSING.get(e));
- resultCode = LDAPResultCode.CLIENT_SIDE_LOCAL_ERROR;
- break;
- }
- }
-
- close(reader, writer);
-
- return resultCode;
- }
-}
-
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/tools/StopDS.java b/opendj-server-legacy/src/main/java/org/opends/server/tools/StopDS.java
index 48e1d6f..01095ea 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/tools/StopDS.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/tools/StopDS.java
@@ -366,7 +366,7 @@
if (quietMode.isPresent())
{
- out = NullOutputStream.printStream();
+ out = NullOutputStream.nullPrintStream();
}
if (checkStoppability.isPresent())
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/types/BackupInfo.java b/opendj-server-legacy/src/main/java/org/opends/server/types/BackupInfo.java
index e663235..be67a9d 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/types/BackupInfo.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/types/BackupInfo.java
@@ -33,7 +33,7 @@
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.i18n.slf4j.LocalizedLogger;
import org.forgerock.opendj.config.server.ConfigException;
-import org.opends.server.util.Base64;
+import org.forgerock.opendj.ldap.Base64;
/**
* This class defines a data structure for holding information about a
@@ -453,11 +453,11 @@
}
else if (name.equals(PROPERTY_UNSIGNED_HASH))
{
- unsignedHash = Base64.decode(value);
+ unsignedHash = Base64.decode(value).toByteArray();
}
else if (name.equals(PROPERTY_SIGNED_HASH))
{
- signedHash = Base64.decode(value);
+ signedHash = Base64.decode(value).toByteArray();
}
else if (name.equals(PROPERTY_DEPENDENCY))
{
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/types/NullOutputStream.java b/opendj-server-legacy/src/main/java/org/opends/server/types/NullOutputStream.java
index 144af8c..8604be6 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/types/NullOutputStream.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/types/NullOutputStream.java
@@ -12,7 +12,7 @@
* information: "Portions Copyright [year] [name of copyright owner]".
*
* Copyright 2006-2008 Sun Microsystems, Inc.
- * Portions Copyright 2013 ForgeRock AS.
+ * Portions Copyright 2013-2016 ForgeRock AS.
*/
package org.opends.server.types;
@@ -64,7 +64,7 @@
*
* @return A print stream using this null output stream.
*/
- public static PrintStream printStream()
+ public static PrintStream nullPrintStream()
{
return printStream;
}
@@ -72,12 +72,12 @@
/**
* Returns s wrapped into a {@link PrintStream} if is not null,
- * {@link NullOutputStream#printStream()} otherwise.
+ * {@link NullOutputStream#nullPrintStream()} otherwise.
*
* @param s
* the OutputStream to wrap into a {@link PrintStream}. Can be null.
* @return a PrintStream wrapping s if not null,
- * {@link NullOutputStream#printStream()} otherwise.
+ * {@link NullOutputStream#nullPrintStream()} otherwise.
*/
public static PrintStream wrapOrNullStream(OutputStream s)
{
@@ -85,7 +85,7 @@
{
return new PrintStream(s);
}
- return NullOutputStream.printStream();
+ return NullOutputStream.nullPrintStream();
}
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/util/Base64.java b/opendj-server-legacy/src/main/java/org/opends/server/util/Base64.java
deleted file mode 100644
index f198224..0000000
--- a/opendj-server-legacy/src/main/java/org/opends/server/util/Base64.java
+++ /dev/null
@@ -1,752 +0,0 @@
-/*
- * The contents of this file are subject to the terms of the Common Development and
- * Distribution License (the License). You may not use this file except in compliance with the
- * License.
- *
- * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
- * specific language governing permission and limitations under the License.
- *
- * When distributing Covered Software, include this CDDL Header Notice in each file and include
- * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
- * Header, with the fields enclosed by brackets [] replaced by your own identifying
- * information: "Portions Copyright [year] [name of copyright owner]".
- *
- * Copyright 2006-2009 Sun Microsystems, Inc.
- * Portions Copyright 2014-2016 ForgeRock AS.
- */
-package org.opends.server.util;
-
-import static org.forgerock.util.Reject.*;
-import static org.opends.messages.ToolMessages.*;
-import static org.opends.messages.UtilityMessages.*;
-import static org.opends.server.util.StaticUtils.*;
-
-import static com.forgerock.opendj.cli.CommonArguments.*;
-
-import java.io.BufferedReader;
-import java.io.BufferedWriter;
-import java.io.ByteArrayOutputStream;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.FileReader;
-import java.io.FileWriter;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.UnsupportedEncodingException;
-import java.nio.ByteBuffer;
-import java.text.ParseException;
-import java.util.ArrayList;
-import java.util.StringTokenizer;
-
-import org.forgerock.i18n.LocalizableMessage;
-import org.forgerock.opendj.ldap.ByteSequence;
-import org.opends.server.core.DirectoryServer.DirectoryServerVersionHandler;
-import org.opends.server.types.NullOutputStream;
-
-import com.forgerock.opendj.cli.ArgumentException;
-import com.forgerock.opendj.cli.BooleanArgument;
-import com.forgerock.opendj.cli.StringArgument;
-import com.forgerock.opendj.cli.SubCommand;
-import com.forgerock.opendj.cli.SubCommandArgumentParser;
-
-/**
- * This class provides methods for performing base64 encoding and decoding.
- * Base64 is a mechanism for encoding binary data in ASCII form by converting
- * sets of three bytes with eight significant bits each to sets of four bytes
- * with six significant bits each.
- */
-@org.opends.server.types.PublicAPI(
- stability=org.opends.server.types.StabilityLevel.UNCOMMITTED,
- mayInstantiate=false,
- mayExtend=false,
- mayInvoke=true)
-public final class Base64
-{
- /** The set of characters that may be used in base64-encoded values. */
- private static final char[] BASE64_ALPHABET =
- "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray();
-
- /** Prevent instance creation. */
- private Base64() {
- // No implementation required.
- }
-
- /**
- * Encodes the provided raw data using base64.
- *
- * @param rawData The raw data to encode. It must not be <CODE>null</CODE>.
- *
- * @return The base64-encoded representation of the provided raw data.
- */
- public static String encode(byte[] rawData)
- {
- ifNull(rawData);
-
-
- StringBuilder buffer = new StringBuilder(4 * rawData.length / 3);
-
- int pos = 0;
- int iterations = rawData.length / 3;
- for (int i=0; i < iterations; i++)
- {
- int value = ((rawData[pos++] & 0xFF) << 16) |
- ((rawData[pos++] & 0xFF) << 8) | (rawData[pos++] & 0xFF);
-
- buffer.append(BASE64_ALPHABET[(value >>> 18) & 0x3F]);
- buffer.append(BASE64_ALPHABET[(value >>> 12) & 0x3F]);
- buffer.append(BASE64_ALPHABET[(value >>> 6) & 0x3F]);
- buffer.append(BASE64_ALPHABET[value & 0x3F]);
- }
-
-
- switch (rawData.length % 3)
- {
- case 1:
- buffer.append(BASE64_ALPHABET[(rawData[pos] >>> 2) & 0x3F]);
- buffer.append(BASE64_ALPHABET[(rawData[pos] << 4) & 0x3F]);
- buffer.append("==");
- break;
- case 2:
- int value = ((rawData[pos++] & 0xFF) << 8) | (rawData[pos] & 0xFF);
- buffer.append(BASE64_ALPHABET[(value >>> 10) & 0x3F]);
- buffer.append(BASE64_ALPHABET[(value >>> 4) & 0x3F]);
- buffer.append(BASE64_ALPHABET[(value << 2) & 0x3F]);
- buffer.append("=");
- break;
- }
-
- return buffer.toString();
- }
-
- /**
- * Encodes the provided raw data using base64.
- *
- * @param rawData The raw data to encode. It must not be <CODE>null</CODE>.
- *
- * @return The base64-encoded representation of the provided raw data.
- */
- public static String encode(ByteSequence rawData)
- {
- ifNull(rawData);
-
-
- StringBuilder buffer = new StringBuilder(4 * rawData.length() / 3);
-
- int pos = 0;
- int iterations = rawData.length() / 3;
- for (int i=0; i < iterations; i++)
- {
- int value = ((rawData.byteAt(pos++) & 0xFF) << 16) |
- ((rawData.byteAt(pos++) & 0xFF) << 8) |
- (rawData.byteAt(pos++) & 0xFF);
-
- buffer.append(BASE64_ALPHABET[(value >>> 18) & 0x3F]);
- buffer.append(BASE64_ALPHABET[(value >>> 12) & 0x3F]);
- buffer.append(BASE64_ALPHABET[(value >>> 6) & 0x3F]);
- buffer.append(BASE64_ALPHABET[value & 0x3F]);
- }
-
-
- switch (rawData.length() % 3)
- {
- case 1:
- buffer.append(BASE64_ALPHABET[(rawData.byteAt(pos) >>> 2) & 0x3F]);
- buffer.append(BASE64_ALPHABET[(rawData.byteAt(pos) << 4) & 0x3F]);
- buffer.append("==");
- break;
- case 2:
- int value = ((rawData.byteAt(pos++) & 0xFF) << 8) |
- (rawData.byteAt(pos) & 0xFF);
- buffer.append(BASE64_ALPHABET[(value >>> 10) & 0x3F]);
- buffer.append(BASE64_ALPHABET[(value >>> 4) & 0x3F]);
- buffer.append(BASE64_ALPHABET[(value << 2) & 0x3F]);
- buffer.append("=");
- break;
- }
-
- return buffer.toString();
- }
-
-
-
- /**
- * Decodes the provided set of base64-encoded data.
- *
- * @param encodedData The base64-encoded data to decode. It must not be
- * <CODE>null</CODE>.
- *
- * @return The decoded raw data.
- *
- * @throws ParseException If a problem occurs while attempting to decode the
- * provided data.
- */
- public static byte[] decode(String encodedData)
- throws ParseException
- {
- ifNull(encodedData);
-
-
- // The encoded value must have length that is a multiple of four bytes.
- int length = encodedData.length();
- if (length % 4 != 0)
- {
- LocalizableMessage message = ERR_BASE64_DECODE_INVALID_LENGTH.get(encodedData);
- throw new ParseException(message.toString(), 0);
- }
-
-
- ByteBuffer buffer = ByteBuffer.allocate(length);
- for (int i=0; i < length; i += 4)
- {
- boolean append = true;
- int value = 0;
-
- for (int j=0; j < 4; j++)
- {
- switch (encodedData.charAt(i+j))
- {
- case 'A':
- value <<= 6;
- break;
- case 'B':
- value = (value << 6) | 0x01;
- break;
- case 'C':
- value = (value << 6) | 0x02;
- break;
- case 'D':
- value = (value << 6) | 0x03;
- break;
- case 'E':
- value = (value << 6) | 0x04;
- break;
- case 'F':
- value = (value << 6) | 0x05;
- break;
- case 'G':
- value = (value << 6) | 0x06;
- break;
- case 'H':
- value = (value << 6) | 0x07;
- break;
- case 'I':
- value = (value << 6) | 0x08;
- break;
- case 'J':
- value = (value << 6) | 0x09;
- break;
- case 'K':
- value = (value << 6) | 0x0A;
- break;
- case 'L':
- value = (value << 6) | 0x0B;
- break;
- case 'M':
- value = (value << 6) | 0x0C;
- break;
- case 'N':
- value = (value << 6) | 0x0D;
- break;
- case 'O':
- value = (value << 6) | 0x0E;
- break;
- case 'P':
- value = (value << 6) | 0x0F;
- break;
- case 'Q':
- value = (value << 6) | 0x10;
- break;
- case 'R':
- value = (value << 6) | 0x11;
- break;
- case 'S':
- value = (value << 6) | 0x12;
- break;
- case 'T':
- value = (value << 6) | 0x13;
- break;
- case 'U':
- value = (value << 6) | 0x14;
- break;
- case 'V':
- value = (value << 6) | 0x15;
- break;
- case 'W':
- value = (value << 6) | 0x16;
- break;
- case 'X':
- value = (value << 6) | 0x17;
- break;
- case 'Y':
- value = (value << 6) | 0x18;
- break;
- case 'Z':
- value = (value << 6) | 0x19;
- break;
- case 'a':
- value = (value << 6) | 0x1A;
- break;
- case 'b':
- value = (value << 6) | 0x1B;
- break;
- case 'c':
- value = (value << 6) | 0x1C;
- break;
- case 'd':
- value = (value << 6) | 0x1D;
- break;
- case 'e':
- value = (value << 6) | 0x1E;
- break;
- case 'f':
- value = (value << 6) | 0x1F;
- break;
- case 'g':
- value = (value << 6) | 0x20;
- break;
- case 'h':
- value = (value << 6) | 0x21;
- break;
- case 'i':
- value = (value << 6) | 0x22;
- break;
- case 'j':
- value = (value << 6) | 0x23;
- break;
- case 'k':
- value = (value << 6) | 0x24;
- break;
- case 'l':
- value = (value << 6) | 0x25;
- break;
- case 'm':
- value = (value << 6) | 0x26;
- break;
- case 'n':
- value = (value << 6) | 0x27;
- break;
- case 'o':
- value = (value << 6) | 0x28;
- break;
- case 'p':
- value = (value << 6) | 0x29;
- break;
- case 'q':
- value = (value << 6) | 0x2A;
- break;
- case 'r':
- value = (value << 6) | 0x2B;
- break;
- case 's':
- value = (value << 6) | 0x2C;
- break;
- case 't':
- value = (value << 6) | 0x2D;
- break;
- case 'u':
- value = (value << 6) | 0x2E;
- break;
- case 'v':
- value = (value << 6) | 0x2F;
- break;
- case 'w':
- value = (value << 6) | 0x30;
- break;
- case 'x':
- value = (value << 6) | 0x31;
- break;
- case 'y':
- value = (value << 6) | 0x32;
- break;
- case 'z':
- value = (value << 6) | 0x33;
- break;
- case '0':
- value = (value << 6) | 0x34;
- break;
- case '1':
- value = (value << 6) | 0x35;
- break;
- case '2':
- value = (value << 6) | 0x36;
- break;
- case '3':
- value = (value << 6) | 0x37;
- break;
- case '4':
- value = (value << 6) | 0x38;
- break;
- case '5':
- value = (value << 6) | 0x39;
- break;
- case '6':
- value = (value << 6) | 0x3A;
- break;
- case '7':
- value = (value << 6) | 0x3B;
- break;
- case '8':
- value = (value << 6) | 0x3C;
- break;
- case '9':
- value = (value << 6) | 0x3D;
- break;
- case '+':
- value = (value << 6) | 0x3E;
- break;
- case '/':
- value = (value << 6) | 0x3F;
- break;
- case '=':
- append = false;
- switch (j)
- {
- case 2:
- buffer.put((byte) ((value >>> 4) & 0xFF));
- break;
- case 3:
- buffer.put((byte) ((value >>> 10) & 0xFF));
- buffer.put((byte) ((value >>> 2) & 0xFF));
- break;
- }
- break;
- default:
- LocalizableMessage message = ERR_BASE64_DECODE_INVALID_CHARACTER.get(
- encodedData, encodedData.charAt(i+j));
- throw new ParseException(message.toString(), i+j);
- }
-
-
- if (! append)
- {
- break;
- }
- }
-
-
- if (append)
- {
- buffer.put((byte) ((value >>> 16) & 0xFF));
- buffer.put((byte) ((value >>> 8) & 0xFF));
- buffer.put((byte) (value & 0xFF));
- }
- else
- {
- break;
- }
- }
-
-
- buffer.flip();
- byte[] returnArray = new byte[buffer.limit()];
- buffer.get(returnArray);
- return returnArray;
- }
-
-
-
- /**
- * Provide a command-line utility that may be used to base64-encode and
- * decode strings and file contents.
- *
- * @param args The command-line arguments provided to this program.
- */
- public static void main(String[] args)
- {
- LocalizableMessage description = INFO_BASE64_TOOL_DESCRIPTION.get();
- SubCommandArgumentParser argParser =
- new SubCommandArgumentParser(Base64.class.getName(), description,
- false);
- argParser.setShortToolDescription(REF_SHORT_DESC_BASE64.get());
- argParser.setVersionHandler(new DirectoryServerVersionHandler());
-
- BooleanArgument showUsage = null;
- StringArgument encodedData = null;
- StringArgument encodedFile = null;
- StringArgument rawData = null;
- StringArgument rawFile = null;
- StringArgument toEncodedFile = null;
- StringArgument toRawFile = null;
- SubCommand decodeSubCommand = null;
- SubCommand encodeSubCommand = null;
-
- try
- {
- decodeSubCommand = new SubCommand(argParser, "decode",
- INFO_BASE64_DECODE_DESCRIPTION.get());
-
- encodeSubCommand = new SubCommand(argParser, "encode",
- INFO_BASE64_ENCODE_DESCRIPTION.get());
-
- encodedData =
- StringArgument.builder("encodedData")
- .shortIdentifier('d')
- .description(INFO_BASE64_ENCODED_DATA_DESCRIPTION.get())
- .valuePlaceholder(INFO_DATA_PLACEHOLDER.get())
- .buildAndAddToSubCommand(decodeSubCommand);
- encodedFile =
- StringArgument.builder("encodedDataFile")
- .shortIdentifier('f')
- .description(INFO_BASE64_ENCODED_FILE_DESCRIPTION.get())
- .valuePlaceholder(INFO_PATH_PLACEHOLDER.get())
- .buildAndAddToSubCommand(decodeSubCommand);
- toRawFile =
- StringArgument.builder("toRawFile")
- .shortIdentifier('o')
- .description(INFO_BASE64_TO_RAW_FILE_DESCRIPTION.get())
- .valuePlaceholder(INFO_PATH_PLACEHOLDER.get())
- .buildAndAddToSubCommand(decodeSubCommand);
- rawData =
- StringArgument.builder("rawData")
- .shortIdentifier('d')
- .description(INFO_BASE64_RAW_DATA_DESCRIPTION.get())
- .valuePlaceholder(INFO_DATA_PLACEHOLDER.get())
- .buildAndAddToSubCommand(encodeSubCommand);
- rawFile =
- StringArgument.builder("rawDataFile")
- .shortIdentifier('f')
- .description(INFO_BASE64_RAW_FILE_DESCRIPTION.get())
- .valuePlaceholder(INFO_PATH_PLACEHOLDER.get())
- .buildAndAddToSubCommand(encodeSubCommand);
- toEncodedFile =
- StringArgument.builder("toEncodedFile")
- .shortIdentifier('o')
- .description(INFO_BASE64_TO_ENCODED_FILE_DESCRIPTION.get())
- .valuePlaceholder(INFO_PATH_PLACEHOLDER.get())
- .buildAndAddToSubCommand(encodeSubCommand);
-
- ArrayList<SubCommand> subCommandList = new ArrayList<>(2);
- subCommandList.add(decodeSubCommand);
- subCommandList.add(encodeSubCommand);
-
- showUsage = showUsageArgument();
- argParser.addGlobalArgument(showUsage);
- argParser.setUsageGroupArgument(showUsage, subCommandList);
- argParser.setUsageArgument(showUsage, NullOutputStream.printStream());
- }
- catch (ArgumentException ae)
- {
- System.err.println(ERR_CANNOT_INITIALIZE_ARGS.get(ae.getMessage()));
- System.exit(1);
- }
-
- try
- {
- argParser.parseArguments(args);
- }
- catch (ArgumentException ae)
- {
- argParser.displayMessageAndUsageReference(System.err, ERR_ERROR_PARSING_ARGS.get(ae.getMessage()));
- System.exit(1);
- }
-
- SubCommand subCommand = argParser.getSubCommand();
- if (argParser.isUsageArgumentPresent())
- {
- if (subCommand == null)
- {
- System.out.println(argParser.getUsage());
- }
- else
- {
- final StringBuilder messageBuilder = new StringBuilder();
- argParser.getSubCommandUsage(messageBuilder, subCommand);
- System.out.println(messageBuilder.toString());
- }
-
- return;
- }
-
- if (argParser.isVersionArgumentPresent())
- {
- // version has already been printed
- System.exit(0);
- }
-
- if (subCommand == null)
- {
- System.err.println(argParser.getUsage());
- System.exit(1);
- }
- if (subCommand.getName().equals(encodeSubCommand.getName()))
- {
- byte[] dataToEncode = null;
- if (rawData.isPresent())
- {
- try
- {
- dataToEncode = rawData.getValue().getBytes("UTF-8");
- }
- catch(UnsupportedEncodingException ex)
- {
- System.err.println(ERR_UNEXPECTED.get(ex));
- System.exit(1);
- }
- }
- else
- {
- try
- {
- boolean shouldClose;
- InputStream inputStream;
- if (rawFile.isPresent())
- {
- inputStream = new FileInputStream(rawFile.getValue());
- shouldClose = true;
- }
- else
- {
- inputStream = System.in;
- shouldClose = false;
- }
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- byte[] buffer = new byte[8192];
- while (true)
- {
- int bytesRead = inputStream.read(buffer);
- if (bytesRead < 0)
- {
- break;
- }
- else
- {
- baos.write(buffer, 0, bytesRead);
- }
- }
-
- if (shouldClose)
- {
- inputStream.close();
- }
-
- dataToEncode = baos.toByteArray();
- }
- catch (Exception e)
- {
- System.err.println(ERR_BASE64_CANNOT_READ_RAW_DATA.get(
- getExceptionMessage(e)));
- System.exit(1);
- }
- }
-
- String base64Data = encode(dataToEncode);
- if (toEncodedFile.isPresent())
- {
- try
- {
- BufferedWriter writer =
- new BufferedWriter(new FileWriter(toEncodedFile.getValue()));
- writer.write(base64Data);
- writer.newLine();
- writer.close();
- }
- catch (Exception e)
- {
- System.err.println(ERR_BASE64_CANNOT_WRITE_ENCODED_DATA.get(
- getExceptionMessage(e)));
- System.exit(1);
- }
- }
- else
- {
- System.out.println(base64Data);
- }
- }
- else if (subCommand.getName().equals(decodeSubCommand.getName()))
- {
- String dataToDecode = null;
- if (encodedData.isPresent())
- {
- dataToDecode = encodedData.getValue();
- }
- else
- {
- try
- {
- boolean shouldClose;
- BufferedReader reader;
- if (encodedFile.isPresent())
- {
- reader = new BufferedReader(new FileReader(encodedFile.getValue()));
- shouldClose = true;
- }
- else
- {
- reader = new BufferedReader(new InputStreamReader(System.in));
- shouldClose = false;
- }
-
- StringBuilder buffer = new StringBuilder();
- while (true)
- {
- String line = reader.readLine();
- if (line == null)
- {
- break;
- }
-
- StringTokenizer tokenizer = new StringTokenizer(line);
- while (tokenizer.hasMoreTokens())
- {
- buffer.append(tokenizer.nextToken());
- }
- }
-
- if (shouldClose)
- {
- reader.close();
- }
-
- dataToDecode = buffer.toString();
- }
- catch (Exception e)
- {
- System.err.println(ERR_BASE64_CANNOT_READ_ENCODED_DATA.get(
- getExceptionMessage(e)));
- System.exit(1);
- }
- }
-
- byte[] decodedData = null;
- try
- {
- decodedData = decode(dataToDecode);
- }
- catch (ParseException pe)
- {
- System.err.println(pe.getMessage());
- System.exit(1);
- }
-
- try
- {
- if (toRawFile.isPresent())
- {
- FileOutputStream outputStream =
- new FileOutputStream(toRawFile.getValue());
- outputStream.write(decodedData);
- outputStream.close();
- }
- else
- {
- System.out.write(decodedData);
- System.out.println();
- System.out.flush();
- }
- }
- catch (Exception e)
- {
- System.err.println(ERR_BASE64_CANNOT_WRITE_RAW_DATA.get(
- getExceptionMessage(e)));
- System.exit(1);
- }
- }
- else
- {
- System.err.println(ERR_BASE64_UNKNOWN_SUBCOMMAND.get(
- subCommand.getName()));
- System.exit(1);
- }
- }
-}
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/util/LDIFReader.java b/opendj-server-legacy/src/main/java/org/opends/server/util/LDIFReader.java
index c307e4f..7f4e99a 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/util/LDIFReader.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/util/LDIFReader.java
@@ -39,6 +39,7 @@
import org.forgerock.i18n.slf4j.LocalizedLogger;
import org.forgerock.opendj.ldap.AVA;
import org.forgerock.opendj.ldap.AttributeDescription;
+import org.forgerock.opendj.ldap.Base64;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.ByteStringBuilder;
import org.forgerock.opendj.ldap.DN;
@@ -599,7 +600,7 @@
{
try
{
- return new String(Base64.decode(encodedStr), "UTF-8");
+ return new String(Base64.decode(encodedStr).toByteArray(), "UTF-8");
}
catch (Exception e)
{
@@ -1379,7 +1380,7 @@
try
{
- value = ByteString.wrap(Base64.decode(line.substring(pos)));
+ value = ByteString.wrap(Base64.decode(line.substring(pos)).toByteArray());
}
catch (Exception e)
{
diff --git a/opendj-server-legacy/src/main/java/org/opends/server/util/LDIFWriter.java b/opendj-server-legacy/src/main/java/org/opends/server/util/LDIFWriter.java
index 97928d4..03f8a8d 100644
--- a/opendj-server-legacy/src/main/java/org/opends/server/util/LDIFWriter.java
+++ b/opendj-server-legacy/src/main/java/org/opends/server/util/LDIFWriter.java
@@ -25,6 +25,7 @@
import java.util.regex.Pattern;
import org.forgerock.i18n.LocalizableMessage;
+import org.forgerock.opendj.ldap.Base64;
import org.forgerock.opendj.ldap.ByteSequence;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.DN;
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/TestCaseUtils.java b/opendj-server-legacy/src/test/java/org/opends/server/TestCaseUtils.java
index 58d721c..990fc58 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/TestCaseUtils.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/TestCaseUtils.java
@@ -24,11 +24,13 @@
import static org.opends.server.loggers.TextAccessLogPublisher.getStartupTextAccessPublisher;
import static org.opends.server.loggers.TextErrorLogPublisher.getToolStartupTextErrorPublisher;
import static org.opends.server.loggers.TextHTTPAccessLogPublisher.getStartupTextHTTPAccessPublisher;
+import static org.opends.server.types.NullOutputStream.nullPrintStream;
import static org.opends.server.util.ServerConstants.PROPERTY_RUNNING_UNIT_TESTS;
import static org.testng.Assert.assertTrue;
import java.io.BufferedReader;
import java.io.BufferedWriter;
+import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
@@ -67,6 +69,7 @@
import java.util.logging.LogManager;
import java.util.logging.Logger;
+import com.forgerock.opendj.ldap.tools.LDAPSearch;
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.opendj.config.dsconfig.DSConfig;
import org.forgerock.opendj.config.server.ConfigException;
@@ -98,7 +101,7 @@
import org.opends.server.protocols.ldap.BindResponseProtocolOp;
import org.opends.server.protocols.ldap.LDAPMessage;
import org.opends.server.protocols.ldap.LDAPReader;
-import org.opends.server.tools.LDAPModify;
+import com.forgerock.opendj.ldap.tools.LDAPModify;
import org.opends.server.types.Attribute;
import org.opends.server.types.DirectoryException;
import org.opends.server.types.Entry;
@@ -1460,7 +1463,6 @@
"-p", String.valueOf(ports.serverLdapPort),
"-D", "cn=Directory Manager",
"-w", "password",
- "-a",
"-f", path
};
String[] adminArgs =
@@ -1471,14 +1473,13 @@
"-Z", "-X",
"-D", "cn=Directory Manager",
"-w", "password",
- "-a",
"-f", path
};
if (useAdminPort) {
- return LDAPModify.mainModify(adminArgs, false, null, null);
+ return LDAPModify.run(nullPrintStream(), nullPrintStream(), adminArgs);
}
- return LDAPModify.mainModify(args, false, null, null);
+ return LDAPModify.run(nullPrintStream(), nullPrintStream(), args);
}
/**
@@ -1923,4 +1924,29 @@
return;
}
}
+
+ public static int runLdapSearchTrustCertificateForSession(final String[] args)
+ {
+ return runLdapSearchTrustCertificateForSession(nullPrintStream(), System.err, args);
+ }
+
+ public static int runLdapSearchTrustCertificateForSession(final PrintStream out,
+ final PrintStream err,
+ final String[] args)
+ {
+ final InputStream stdin = System.in;
+ try
+ {
+ // Since hostnames are different between the client.truststore (CN=OpenDJ Test Certificate, O=OpenDJ.org) and the
+ // one given in parameter (127.0.0.1), ldapsearch tool prompt user to know what to do (either untrust the server
+ // certificate, trust it for the session only or trust it permanently).
+ // Default option is session trust, we just hit enter in stdin to have a non blocking unit test.
+ System.setIn(new ByteArrayInputStream(System.lineSeparator().getBytes()));
+ return LDAPSearch.run(nullPrintStream(), System.err, args);
+ }
+ finally
+ {
+ System.setIn(stdin);
+ }
+ }
}
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/api/PasswordValidatorTestCase.java b/opendj-server-legacy/src/test/java/org/opends/server/api/PasswordValidatorTestCase.java
index 20ac02b..30cb4ec 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/api/PasswordValidatorTestCase.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/api/PasswordValidatorTestCase.java
@@ -19,6 +19,7 @@
import static org.forgerock.opendj.ldap.ModificationType.*;
import static org.forgerock.opendj.ldap.requests.Requests.*;
import static org.opends.server.TestCaseUtils.*;
+import static org.opends.server.types.NullOutputStream.nullPrintStream;
import static org.testng.Assert.*;
import java.util.Set;
@@ -29,7 +30,7 @@
import org.opends.server.extensions.TestPasswordValidator;
import org.opends.server.protocols.ldap.LDAPMessage;
import org.opends.server.protocols.ldap.ModifyResponseProtocolOp;
-import org.opends.server.tools.LDAPPasswordModify;
+import com.forgerock.opendj.ldap.tools.LDAPPasswordModify;
import org.opends.server.tools.RemoteConnection;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
@@ -115,8 +116,7 @@
"-c", "password",
"-n", "newPassword"
};
- assertEquals(LDAPPasswordModify.mainPasswordModify(args, false, null, null),
- 0);
+ assertEquals(LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args), 0);
assertEquals(TestPasswordValidator.getLastNewPassword(),
ByteString.valueOfUtf8("newPassword"));
@@ -165,8 +165,7 @@
"-n", "newPassword"
};
- int returnCode = LDAPPasswordModify.mainPasswordModify(args, false, null,
- null);
+ int returnCode = LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args);
assertNotEquals(returnCode, 0);
assertEquals(TestPasswordValidator.getLastNewPassword(),
@@ -214,8 +213,7 @@
"-w", "password",
"-n", "newPassword"
};
- assertEquals(LDAPPasswordModify.mainPasswordModify(args, false, null, null),
- 0);
+ assertEquals(LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args), 0);
Set<ByteString> currentPasswords =
TestPasswordValidator.getLastCurrentPasswords();
@@ -262,8 +260,7 @@
"-c", "password",
"-n", "newPassword"
};
- assertEquals(LDAPPasswordModify.mainPasswordModify(args, false, null, null),
- 0);
+ assertEquals(LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args), 0);
Set<ByteString> currentPasswords =
TestPasswordValidator.getLastCurrentPasswords();
@@ -314,8 +311,7 @@
"-w", "password",
"-n", "newPassword"
};
- assertEquals(LDAPPasswordModify.mainPasswordModify(args, false, null, null),
- 0);
+ assertEquals(LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args), 0);
Set<ByteString> currentPasswords =
TestPasswordValidator.getLastCurrentPasswords();
@@ -367,8 +363,7 @@
"-c", "password",
"-n", "newPassword"
};
- assertEquals(LDAPPasswordModify.mainPasswordModify(args, false, null, null),
- 0);
+ assertEquals(LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args), 0);
Set<ByteString> currentPasswords =
TestPasswordValidator.getLastCurrentPasswords();
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/authorization/dseecompat/AciTestCase.java b/opendj-server-legacy/src/test/java/org/opends/server/authorization/dseecompat/AciTestCase.java
index 52f66d8..9b50ab7 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/authorization/dseecompat/AciTestCase.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/authorization/dseecompat/AciTestCase.java
@@ -24,6 +24,7 @@
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
+import java.io.PrintStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
@@ -49,10 +50,10 @@
import org.opends.server.core.DirectoryServer;
import org.opends.server.core.ModifyOperation;
import org.opends.server.protocols.ldap.LDAPResultCode;
-import org.opends.server.tools.LDAPDelete;
-import org.opends.server.tools.LDAPModify;
-import org.opends.server.tools.LDAPPasswordModify;
-import org.opends.server.tools.LDAPSearch;
+import com.forgerock.opendj.ldap.tools.LDAPDelete;
+import com.forgerock.opendj.ldap.tools.LDAPModify;
+import com.forgerock.opendj.ldap.tools.LDAPPasswordModify;
+import com.forgerock.opendj.ldap.tools.LDAPSearch;
import org.opends.server.types.Attribute;
import org.opends.server.types.Entry;
import org.opends.server.types.Modification;
@@ -190,12 +191,15 @@
argList.add("-J");
argList.add(pwdPolicyControl);
}
+
String[] args = new String[argList.size()];
oStream.reset();
- int ret = LDAPPasswordModify.mainPasswordModify(argList.toArray(args),
- false, oStream, oStream);
- Assert.assertEquals(ret, expectedRc, "Returned error: " + oStream);
- return oStream.toString();
+ try (final PrintStream printStream = new PrintStream(oStream)) {
+ int ret = LDAPPasswordModify.run(printStream, printStream, argList.toArray(args));
+ final String output = oStream.toString();
+ Assert.assertEquals(ret, expectedRc, "ldappasswordmodify output: " + output);
+ return output;
+ }
}
/**
@@ -231,12 +235,9 @@
}
argList.add("-f");
argList.add(tempFile.getAbsolutePath());
- String[] args = new String[argList.size()];
oStream.reset();
- int retVal =LDAPModify.mainModify(argList.toArray(args), false, oStream, oStream);
- Assert.assertEquals(retVal, 0, "Returned error: " + oStream);
- return oStream.toString();
+ return runLdapModify(argList, 0);
}
protected String LDAPSearchCtrl(String bindDn, String bindPassword,
@@ -251,7 +252,8 @@
argList.add(bindDn);
argList.add("-w");
argList.add(bindPassword);
- argList.add("-T");
+ argList.add("-t");
+ argList.add("0");
if(proxyDN != null) {
argList.add("-Y");
argList.add("dn:" + proxyDN);
@@ -266,12 +268,8 @@
argList.add("sub");
argList.add(filter);
Collections.addAll(argList, attr.split("\\s+"));
- String[] args = new String[argList.size()];
oStream.reset();
- int retVal =
- LDAPSearch.mainSearch(argList.toArray(args), false, oStream, oStream);
- Assert.assertEquals(retVal, 0, "Returned error: " + oStream);
- return oStream.toString();
+ return runLdapSearch(argList);
}
protected String
@@ -307,7 +305,8 @@
argList.add(bindDn);
argList.add("-w");
argList.add(bindPassword);
- argList.add("-T");
+ argList.add("-t");
+ argList.add("0");
if(proxyDN != null) {
argList.add("-Y");
argList.add("dn:" + proxyDN);
@@ -336,40 +335,37 @@
if(attr != null) {
Collections.addAll(argList, attr.split("\\s+"));
}
- String[] args = new String[argList.size()];
oStream.reset();
- int retVal = LDAPSearch.mainSearch(argList.toArray(args), false, oStream, oStream);
- Assert.assertEquals(retVal, expectedRc, "Returned error: " + oStream);
- return oStream.toString();
+ return runLdapSearch(argList);
}
protected void LDIFAdd(String ldif, String bindDn, String bindPassword,
String controlStr, int expectedRc) throws Exception
{
- _LDIFModify(ldif, bindDn, bindPassword, controlStr, true, expectedRc, false);
+ _LDIFModify(ldif, bindDn, bindPassword, controlStr, expectedRc, false);
}
protected void LDIFModify(String ldif, String bindDn, String bindPassword,
String controlStr, int expectedRc) throws Exception
{
- _LDIFModify(ldif, bindDn, bindPassword, controlStr, false, expectedRc, false);
+ _LDIFModify(ldif, bindDn, bindPassword, controlStr, expectedRc, false);
}
protected void LDIFModify(String ldif, String bindDn, String bindPassword)
throws Exception {
- _LDIFModify(ldif, bindDn, bindPassword, null, false, -1, false);
+ _LDIFModify(ldif, bindDn, bindPassword, null, -1, false);
}
protected void LDIFAdminModify (String ldif, String bindDn,
String bindPassword)
throws Exception {
- _LDIFModify(ldif, bindDn, bindPassword, null, false, -1, true);
+ _LDIFModify(ldif, bindDn, bindPassword, null, -1, true);
}
protected void LDIFModify(String ldif, String bindDn, String bindPassword,
String ctrlString)
throws Exception {
- _LDIFModify(ldif, bindDn, bindPassword, ctrlString, false, -1, false);
+ _LDIFModify(ldif, bindDn, bindPassword, ctrlString, -1, false);
}
protected void LDIFDelete(String dn, String bindDn, String bindPassword,
@@ -402,13 +398,16 @@
private void ldapDelete(String[] args, int expectedRc)
{
oStream.reset();
- int retVal = LDAPDelete.mainDelete(args, false, oStream, oStream);
- Assert.assertEquals(retVal, expectedRc, "Returned error: " + oStream);
+ try (final PrintStream printStream = new PrintStream(oStream))
+ {
+ final int retVal = LDAPDelete.run(printStream, printStream, args);
+ Assert.assertEquals(retVal, expectedRc, "ldapdelete output: " + oStream.toString());
+ }
}
private void _LDIFModify(String ldif, String bindDn, String bindPassword,
- String controlStr, boolean add, int expectedRc, boolean useAdminPort)
+ String controlStr, int expectedRc, boolean useAdminPort)
throws Exception
{
File tempFile = getTemporaryLdifFile();
@@ -432,13 +431,9 @@
argList.add("-J");
argList.add(controlStr);
}
- if(add) {
- argList.add("-a");
- }
argList.add("-f");
argList.add(tempFile.getAbsolutePath());
- String[] args = new String[argList.size()];
- ldapModify(argList.toArray(args), expectedRc);
+ runLdapModify(argList, expectedRc);
}
protected void JNDIModify(Hashtable<?, ?> env, String name, String attr,
@@ -484,18 +479,7 @@
}
argList.add("-f");
argList.add(tempFile.getAbsolutePath());
- String[] args = new String[argList.size()];
- ldapModify(argList.toArray(args), expectedRc);
- }
-
- private void ldapModify(String[] args, int expectedRc)
- {
- oStream.reset();
- int retVal =LDAPModify.mainModify(args, false, oStream, oStream);
- if (expectedRc != -1)
- {
- Assert.assertEquals(retVal, expectedRc, "Returned error: " + oStream);
- }
+ runLdapModify(argList, expectedRc);
}
protected void deleteAttrFromEntry(String dn, String attr) throws Exception {
@@ -802,4 +786,28 @@
return attrMap;
}
+ private String runLdapModify(final List<String> argList, final int expectedReturnCode)
+ {
+ try (final PrintStream printStream = new PrintStream(oStream))
+ {
+ final int retVal = LDAPModify.run(printStream, printStream, argList.toArray(new String[argList.size()]));
+ final String output = oStream.toString();
+ if (expectedReturnCode != -1)
+ {
+ Assert.assertEquals(retVal, expectedReturnCode, "ldapmodify output: " + output);
+ }
+ return output;
+ }
+ }
+
+ private String runLdapSearch(final List<String> argList)
+ {
+ try (final PrintStream printStream = new PrintStream(oStream))
+ {
+ final int retVal = LDAPSearch.run(printStream, printStream, argList.toArray(new String[argList.size()]));
+ final String output = oStream.toString();
+ Assert.assertEquals(retVal, 0, "ldapsearch output: " + output);
+ return output;
+ }
+ }
}
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/authorization/dseecompat/AciTests.java b/opendj-server-legacy/src/test/java/org/opends/server/authorization/dseecompat/AciTests.java
index ebbdd04..1ff81f0 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/authorization/dseecompat/AciTests.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/authorization/dseecompat/AciTests.java
@@ -27,7 +27,7 @@
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
-import java.io.StringReader;
+import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
@@ -41,18 +41,12 @@
import java.util.Set;
import java.util.regex.Pattern;
-import org.forgerock.i18n.LocalizableMessage;
+import com.forgerock.opendj.ldap.tools.LDAPCompare;
+import com.forgerock.opendj.ldap.tools.LDIFDiff;
import org.opends.server.TestCaseUtils;
import org.opends.server.protocols.ldap.LDAPResultCode;
-import org.opends.server.tools.LDAPCompare;
-import org.opends.server.tools.LDAPModify;
-import org.opends.server.tools.LDAPSearch;
-import org.opends.server.tools.LDIFDiff;
-import org.opends.server.tools.LDIFModify;
-import org.opends.server.types.LDIFExportConfig;
-import org.opends.server.types.LDIFImportConfig;
-import org.opends.server.util.LDIFReader;
-import org.opends.server.util.LDIFWriter;
+import com.forgerock.opendj.ldap.tools.LDAPModify;
+import com.forgerock.opendj.ldap.tools.LDAPSearch;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
@@ -1733,7 +1727,6 @@
"-p", getServerLdapPort(),
"-D", _bindDn,
"-w", _bindPw,
- "--useCompareResultCode",
attrAssertion,
_searchBaseDn};
}
@@ -1760,24 +1753,6 @@
searchFilter, searchScope, expectedResultsLdif, _initialDitLdif, equivalentAci));
}
}
-
- /**
- * @return the LDIF result of applying changesLdif to changesLdif
- */
- private String applyChangesToLdif(String baseLdif, String changesLdif) throws Exception {
- LDIFReader baseReader = new LDIFReader(new LDIFImportConfig(new StringReader(baseLdif)));
- LDIFReader changesReader = new LDIFReader(new LDIFImportConfig(new StringReader(changesLdif)));
-
- ByteArrayOutputStream updatedEntriesStream = new ByteArrayOutputStream();
- LDIFWriter ldifWriter = new LDIFWriter(new LDIFExportConfig(updatedEntriesStream));
-
- List<LocalizableMessage> errors = new ArrayList<>();
- LDIFModify.modifyLDIF(baseReader, changesReader, ldifWriter, errors);
- Assert.assertTrue(errors.isEmpty(), "Unexpected errors applying LDIF changes: " + errors);
- ldifWriter.flush();
-
- return updatedEntriesStream.toString();
- }
}
@DataProvider
@@ -2290,7 +2265,6 @@
"-p", getServerLdapPort(),
"-D", bindDn,
"-w", bindPassword,
- "-a",
"-f", tempFile.getAbsolutePath()
};
@@ -2299,20 +2273,20 @@
private void ldapModify(String[] args, boolean expectSuccess) throws Exception {
clearOutputStream();
- int retVal = LDAPModify.mainModify(args, false, getOutputStream(), getOutputStream());
+ int retVal = LDAPModify.run(getOutputPrintStream(), getOutputPrintStream(), args);
assertEquals(retVal == 0, expectSuccess, "Return value = " + retVal);
}
private String ldapSearch(String[] args) throws Exception {
clearOutputStream();
- int retVal = LDAPSearch.mainSearch(args, false, getOutputStream(), getOutputStream());
+ int retVal = LDAPSearch.run(getOutputPrintStream(), getOutputPrintStream(), args);
Assert.assertEquals(retVal, 0, "Non-zero return code because, error: " + getOutputStreamContents());
return getOutputStreamContents();
}
private String ldapCompare(String[] args, int expectedRc) throws Exception {
clearOutputStream();
- int retVal = LDAPCompare.mainCompare(args, false, getOutputStream(), getOutputStream());
+ int retVal = LDAPCompare.run(getOutputPrintStream(), getOutputPrintStream(), args);
Assert.assertEquals(retVal, expectedRc, "Non-zero return code because, error: " + getOutputStreamContents());
return getOutputStreamContents();
}
@@ -2450,12 +2424,12 @@
String[] args =
{
- "--sourceLDIF", actualLdifFile.getAbsolutePath(),
- "--targetLDIF", expectedLdifFile.getAbsolutePath(),
- "--outputLDIF", diffLdifFile.getAbsolutePath()
+ "--outputLDIF", diffLdifFile.getAbsolutePath(),
+ actualLdifFile.getAbsolutePath(),
+ expectedLdifFile.getAbsolutePath()
};
- int retVal = LDIFDiff.mainDiff(args, true, System.out, System.err);
+ int retVal = LDIFDiff.run(System.out, System.err, args);
assertEquals(retVal, 0, "LDIFDiff failed");
if (diffLdifFile.exists()) {
@@ -2531,6 +2505,9 @@
return _cmdOutput;
}
+ private static PrintStream getOutputPrintStream() {
+ return new PrintStream(getOutputStream());
+ }
private static String makeUserLdif(String dn, String givenName, String sn, String password) {
String cn = givenName + " " + sn;
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/authorization/dseecompat/ReferencesTestCase.java b/opendj-server-legacy/src/test/java/org/opends/server/authorization/dseecompat/ReferencesTestCase.java
index 6128233..827464b 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/authorization/dseecompat/ReferencesTestCase.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/authorization/dseecompat/ReferencesTestCase.java
@@ -12,7 +12,7 @@
* information: "Portions Copyright [year] [name of copyright owner]".
*
* Copyright 2008-2009 Sun Microsystems, Inc.
- * Portions Copyright 2015 ForgeRock AS.
+ * Portions Copyright 2015-2016 ForgeRock AS.
*/
package org.opends.server.authorization.dseecompat;
@@ -187,7 +187,7 @@
{
break;
}
- if(s.startsWith("SearchReference")) {
+ if(s.startsWith("SearchResultReference")) {
return true;
}
}
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/authorization/dseecompat/TargetControlTestCase.java b/opendj-server-legacy/src/test/java/org/opends/server/authorization/dseecompat/TargetControlTestCase.java
index 99616ee..3867f7b 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/authorization/dseecompat/TargetControlTestCase.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/authorization/dseecompat/TargetControlTestCase.java
@@ -12,7 +12,7 @@
* information: "Portions Copyright [year] [name of copyright owner]".
*
* Copyright 2008-2009 Sun Microsystems, Inc.
- * Portions Copyright 2012-2015 ForgeRock AS.
+ * Portions Copyright 2012-2016 ForgeRock AS.
*/
package org.opends.server.authorization.dseecompat;
@@ -245,8 +245,7 @@
String noOpCtrlStr=OID_LDAP_NOOP_OPENLDAP_ASSIGNED + ":true";
//This pwd change should return no-op since the no-op control is
//specified and it is allowed for authorization dn.
- pwdModify(level3User, PWD, newPWD, noOpCtrlStr, null,
- LDAPResultCode.NO_OPERATION);
+ pwdModify(level3User, PWD, newPWD, noOpCtrlStr, null, LDAPResultCode.SUCCESS);
//This pwd change should fail even though the no-op is specified, since
//since the no-op control is not allowed for this authorization dn.
pwdModify(superUser, PWD, newPWD, noOpCtrlStr, null,
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/backends/LDIFBackendTestCase.java b/opendj-server-legacy/src/test/java/org/opends/server/backends/LDIFBackendTestCase.java
index e4d25ad..67763a9 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/backends/LDIFBackendTestCase.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/backends/LDIFBackendTestCase.java
@@ -40,8 +40,8 @@
import org.opends.server.protocols.internal.SearchRequest;
import org.opends.server.tasks.LdifFileWriter;
import org.opends.server.tasks.TasksTestCase;
-import org.opends.server.tools.LDAPModify;
-import org.opends.server.tools.LDAPSearch;
+import com.forgerock.opendj.ldap.tools.LDAPModify;
+import com.forgerock.opendj.ldap.tools.LDAPSearch;
import org.forgerock.opendj.ldap.DN;
import org.opends.server.types.DirectoryException;
import org.opends.server.types.Entry;
@@ -177,7 +177,7 @@
"-w", "password",
"-f", subtreeDeletePath
};
- resultCode = LDAPModify.mainModify(args, false, System.out, System.err);
+ resultCode = LDAPModify.run(System.out, System.err, args);
assertEquals(resultCode, ResultCode.NOT_ALLOWED_ON_NONLEAF.intValue());
@@ -192,7 +192,7 @@
"-J", "subtreeDelete",
"-f", subtreeDeletePath
};
- resultCode = LDAPModify.mainModify(args, false, System.out, System.err);
+ resultCode = LDAPModify.run(System.out, System.err, args);
assertEquals(resultCode, 0);
}
@@ -270,7 +270,7 @@
"-J", "subtreeDelete",
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, System.out, System.err), 0);
+ assertEquals(LDAPModify.run(System.out, System.err, args), 0);
assertFalse(DirectoryServer.entryExists(DN.valueOf("o=ldif")));
assertFalse(DirectoryServer.entryExists(
DN.valueOf("uid=user.1,ou=People,o=ldif")));
@@ -312,7 +312,7 @@
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, System.out, System.err), 0);
+ assertEquals(LDAPSearch.run(System.out, System.err, args), 0);
}
@@ -356,7 +356,7 @@
"-w", "password",
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, System.out, System.err), 0);
+ assertEquals(LDAPModify.run(System.out, System.err, args), 0);
}
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/backends/SchemaBackendTestCase.java b/opendj-server-legacy/src/test/java/org/opends/server/backends/SchemaBackendTestCase.java
index 0619d92..131b9e0 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/backends/SchemaBackendTestCase.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/backends/SchemaBackendTestCase.java
@@ -24,6 +24,7 @@
import static org.opends.server.protocols.internal.InternalClientConnection.*;
import static org.opends.server.protocols.internal.Requests.*;
import static org.opends.server.types.ExistingFileBehavior.*;
+import static org.opends.server.types.NullOutputStream.nullPrintStream;
import static org.opends.server.util.StaticUtils.*;
import static org.testng.Assert.*;
@@ -62,7 +63,7 @@
import org.opends.server.schema.SchemaConstants;
import org.opends.server.schema.SchemaHandler;
import org.opends.server.schema.SchemaHandler.SchemaUpdater;
-import org.opends.server.tools.LDAPModify;
+import com.forgerock.opendj.ldap.tools.LDAPModify;
import org.opends.server.types.DirectoryException;
import org.opends.server.types.Entry;
import org.opends.server.types.LDIFExportConfig;
@@ -4284,7 +4285,7 @@
private void runModify(String[] args, String ldifContent, ResultCode expectedRC)
{
- runModify(args, ldifContent, null, expectedRC);
+ runModify(args, ldifContent, nullPrintStream(), expectedRC);
}
private void runModify(String[] args, String ldifContent, PrintStream stderr, ResultCode expectedRC)
@@ -4300,7 +4301,7 @@
try
{
System.setIn(new ByteArrayInputStream(ldifContent.getBytes()));
- return LDAPModify.mainModify(args, false, stdout, stderr);
+ return LDAPModify.run(stdout, stderr, args);
}
finally
{
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/controls/MatchedValuesControlTest.java b/opendj-server-legacy/src/test/java/org/opends/server/controls/MatchedValuesControlTest.java
index f4c9056..2a457a1 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/controls/MatchedValuesControlTest.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/controls/MatchedValuesControlTest.java
@@ -21,6 +21,7 @@
import java.util.ArrayList;
import java.util.List;
+import org.forgerock.opendj.ldap.Base64;
import org.forgerock.opendj.ldap.schema.CoreSchema;
import org.forgerock.opendj.ldap.schema.MatchingRule;
import org.opends.server.core.DirectoryServer;
@@ -29,7 +30,6 @@
import org.forgerock.opendj.ldap.ByteStringBuilder;
import org.forgerock.opendj.io.ASN1Writer;
import org.forgerock.opendj.io.ASN1;
-import org.opends.server.util.Base64;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
@@ -782,7 +782,7 @@
"{ serialNumber 13233831500277100508, issuer rdnSequence:\""+
"CN=Babs Jensen,OU=Product Development,L=Cupertione,C=US\" }";
return new Object[][]{
- {"userCertificate", ByteString.wrap(Base64.decode(BASE64_CERT_VALUE)),
+ {"userCertificate", ByteString.wrap(Base64.decode(BASE64_CERT_VALUE).toByteArray()),
CERT_EXACT_ASSERTION}};
}
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/controls/PersistentSearchControlTest.java b/opendj-server-legacy/src/test/java/org/opends/server/controls/PersistentSearchControlTest.java
index ca32d4f..d3fbf32 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/controls/PersistentSearchControlTest.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/controls/PersistentSearchControlTest.java
@@ -22,6 +22,7 @@
import static org.opends.server.controls.PersistentSearchChangeType.*;
import static org.opends.server.protocols.internal.InternalClientConnection.*;
import static org.opends.server.protocols.internal.Requests.*;
+import static org.opends.server.types.NullOutputStream.nullPrintStream;
import static org.opends.server.util.ServerConstants.*;
import static org.testng.Assert.*;
@@ -48,7 +49,7 @@
import org.opends.server.protocols.internal.SearchRequest;
import org.opends.server.protocols.ldap.LDAPControl;
import org.opends.server.protocols.ldap.LDAPReader;
-import org.opends.server.tools.LDAPSearch;
+import com.forgerock.opendj.ldap.tools.LDAPSearch;
import org.opends.server.types.CancelRequest;
import org.opends.server.types.DirectoryException;
import org.opends.server.types.LDAPException;
@@ -550,8 +551,7 @@
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false,
- true, null, System.err),11);
+ assertEquals(LDAPSearch.run(nullPrintStream(), System.err, args), 11);
//cancel the persisting persistent search.
search.cancel(new CancelRequest(true,LocalizableMessage.EMPTY));
}
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/core/AddOperationTestCase.java b/opendj-server-legacy/src/test/java/org/opends/server/core/AddOperationTestCase.java
index c3cac98..643e9b5 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/core/AddOperationTestCase.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/core/AddOperationTestCase.java
@@ -22,6 +22,7 @@
import static org.opends.server.TestCaseUtils.*;
import static org.opends.server.protocols.internal.InternalClientConnection.*;
import static org.opends.server.protocols.ldap.LDAPConstants.*;
+import static org.opends.server.types.NullOutputStream.nullPrintStream;
import static org.opends.server.util.CollectionUtils.*;
import static org.testng.Assert.*;
@@ -45,7 +46,7 @@
import org.opends.server.protocols.ldap.AddRequestProtocolOp;
import org.opends.server.protocols.ldap.LDAPAttribute;
import org.opends.server.protocols.ldap.LDAPMessage;
-import org.opends.server.tools.LDAPModify;
+import com.forgerock.opendj.ldap.tools.LDAPModify;
import org.opends.server.tools.RemoteConnection;
import org.opends.server.types.Attribute;
import org.opends.server.types.Attributes;
@@ -1577,7 +1578,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
assertTrue(DirectoryServer.getSchema().hasAttributeType(attrName));
path = TestCaseUtils.createTempFile(
@@ -1598,7 +1599,7 @@
"-f", path
};
- assertFalse(LDAPModify.mainModify(args, false, null, null) == 0);
+ assertFalse(LDAPModify.run(nullPrintStream(), nullPrintStream(), args) == 0);
}
/**
@@ -1633,7 +1634,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
assertTrue(DirectoryServer.getSchema().hasAttributeType(attrName));
path = TestCaseUtils.createTempFile(
@@ -1654,7 +1655,7 @@
"-f", path
};
- assertFalse(LDAPModify.mainModify(args, false, null, null) == 0);
+ assertFalse(LDAPModify.run(nullPrintStream(), nullPrintStream(), args) == 0);
}
/**
@@ -1688,7 +1689,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
assertTrue(DirectoryServer.getSchema().hasObjectClass(ocName));
path = TestCaseUtils.createTempFile(
@@ -1708,7 +1709,7 @@
"-f", path
};
- assertFalse(LDAPModify.mainModify(args, false, null, null) == 0);
+ assertFalse(LDAPModify.run(nullPrintStream(), nullPrintStream(), args) == 0);
}
/**
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/core/BindOperationTestCase.java b/opendj-server-legacy/src/test/java/org/opends/server/core/BindOperationTestCase.java
index 0737d31..fed6ee3 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/core/BindOperationTestCase.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/core/BindOperationTestCase.java
@@ -34,9 +34,9 @@
import org.opends.server.protocols.ldap.LDAPControl;
import org.opends.server.protocols.ldap.LDAPMessage;
import org.opends.server.protocols.ldap.LDAPResultCode;
-import org.opends.server.tools.LDAPDelete;
-import org.opends.server.tools.LDAPModify;
-import org.opends.server.tools.LDAPSearch;
+import com.forgerock.opendj.ldap.tools.LDAPDelete;
+import com.forgerock.opendj.ldap.tools.LDAPModify;
+import com.forgerock.opendj.ldap.tools.LDAPSearch;
import org.opends.server.tools.RemoteConnection;
import org.opends.server.types.AuthenticationInfo;
import org.opends.server.types.AuthenticationType;
@@ -52,6 +52,7 @@
import static org.forgerock.opendj.ldap.requests.Requests.*;
import static org.opends.server.protocols.internal.InternalClientConnection.*;
import static org.opends.server.protocols.ldap.LDAPConstants.*;
+import static org.opends.server.types.NullOutputStream.nullPrintStream;
import static org.opends.server.util.ServerConstants.*;
import static org.testng.Assert.*;
@@ -1523,7 +1524,7 @@
"--noPropertiesFile",
"ou=people,dc=example,dc=com"
};
- assertEquals(LDAPDelete.mainDelete(args, false, null, System.err), 0);
+ assertEquals(LDAPDelete.run(nullPrintStream(), System.err, args), 0);
assertNull(DirectoryServer.getAuthenticatedUsers().get(userDN));
}
@@ -1587,7 +1588,7 @@
"--noPropertiesFile",
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
DN newUserDN = DN.valueOf("uid=test,ou=users,dc=example,dc=com");
assertNotNull(DirectoryServer.getAuthenticatedUsers().get(newUserDN));
@@ -1654,8 +1655,7 @@
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, System.out, System.err),
- 0);
+ assertEquals(LDAPSearch.run(System.out, System.err, args), 0);
args = new String[]
{
@@ -1668,8 +1668,7 @@
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, System.out, System.err),
- 0);
+ assertEquals(LDAPSearch.run(System.out, System.err, args), 0);
}
finally
{
@@ -1746,7 +1745,7 @@
"(objectClass=*)"
};
- int rc = LDAPSearch.mainSearch(args, false, System.out, System.err);
+ int rc = LDAPSearch.run(System.out, System.err, args);
assertFalse(rc == 0);
assertFalse(rc == LDAPResultCode.INVALID_CREDENTIALS);
@@ -1761,8 +1760,7 @@
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, System.out, System.err),
- 0);
+ assertEquals(LDAPSearch.run(System.out, System.err, args), 0);
}
finally
{
@@ -1839,8 +1837,7 @@
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, System.out, System.err),
- LDAPResultCode.INVALID_CREDENTIALS);
+ assertEquals(LDAPSearch.run(System.out, System.err, args), LDAPResultCode.INVALID_CREDENTIALS);
args = new String[]
{
@@ -1853,8 +1850,7 @@
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, System.out, System.err),
- 0);
+ assertEquals(LDAPSearch.run(System.out, System.err, args), 0);
}
finally
{
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/core/DeleteOperationTestCase.java b/opendj-server-legacy/src/test/java/org/opends/server/core/DeleteOperationTestCase.java
index 2558b53..1f01167 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/core/DeleteOperationTestCase.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/core/DeleteOperationTestCase.java
@@ -19,6 +19,7 @@
import java.util.ArrayList;
import java.util.List;
+import com.forgerock.opendj.ldap.tools.LDAPDelete;
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.DN;
@@ -29,7 +30,6 @@
import org.opends.server.plugins.ShortCircuitPlugin;
import org.opends.server.protocols.ldap.DeleteRequestProtocolOp;
import org.opends.server.protocols.ldap.LDAPMessage;
-import org.opends.server.tools.LDAPDelete;
import org.opends.server.tools.RemoteConnection;
import org.opends.server.types.CancelRequest;
import org.opends.server.types.CancelResult;
@@ -45,6 +45,7 @@
import static org.opends.server.TestCaseUtils.*;
import static org.opends.server.protocols.internal.InternalClientConnection.*;
import static org.opends.server.protocols.ldap.LDAPConstants.*;
+import static org.opends.server.types.NullOutputStream.nullPrintStream;
import static org.testng.Assert.*;
/**
@@ -256,7 +257,7 @@
TestCaseUtils.initializeTestBackend(true);
String[] args = getArgs("o=test");
- assertEquals(LDAPDelete.mainDelete(args, false, null, null), 0);
+ assertEquals(LDAPDelete.run(nullPrintStream(), nullPrintStream(), args), 0);
}
@@ -550,7 +551,7 @@
DirectoryServer.setWritabilityMode(WritabilityMode.INTERNAL_ONLY);
String[] args = getArgs("o=test");
- assertFalse(LDAPDelete.mainDelete(args, false, null, null) == 0);
+ assertFalse(LDAPDelete.run(nullPrintStream(), nullPrintStream(), args) == 0);
DirectoryServer.setWritabilityMode(WritabilityMode.ENABLED);
}
@@ -616,7 +617,7 @@
backend.setWritabilityMode(WritabilityMode.INTERNAL_ONLY);
String[] args = getArgs("o=test");
- assertFalse(LDAPDelete.mainDelete(args, false, null, null) == 0);
+ assertFalse(LDAPDelete.run(nullPrintStream(), nullPrintStream(), args) == 0);
backend.setWritabilityMode(WritabilityMode.ENABLED);
}
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/core/GroupManagerTestCase.java b/opendj-server-legacy/src/test/java/org/opends/server/core/GroupManagerTestCase.java
index 64b8036..140f825 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/core/GroupManagerTestCase.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/core/GroupManagerTestCase.java
@@ -34,8 +34,8 @@
import org.opends.server.protocols.internal.InternalClientConnection;
import org.opends.server.protocols.internal.InternalSearchOperation;
import org.opends.server.protocols.internal.SearchRequest;
-import org.opends.server.tools.LDAPDelete;
-import org.opends.server.tools.LDAPModify;
+import com.forgerock.opendj.ldap.tools.LDAPDelete;
+import com.forgerock.opendj.ldap.tools.LDAPModify;
import org.opends.server.types.DirectoryException;
import org.opends.server.types.Entry;
import org.opends.server.types.MemberList;
@@ -49,6 +49,7 @@
import static org.forgerock.opendj.ldap.requests.Requests.*;
import static org.opends.server.protocols.internal.InternalClientConnection.*;
import static org.opends.server.protocols.internal.Requests.*;
+import static org.opends.server.types.NullOutputStream.nullPrintStream;
import static org.opends.server.util.ServerConstants.*;
import static org.testng.Assert.*;
@@ -2203,7 +2204,7 @@
"--noPropertiesFile",
"ou=groups,dc=example,dc=com"
};
- assertEquals(LDAPDelete.mainDelete(args, false, null, System.err), 0);
+ assertEquals(LDAPDelete.run(nullPrintStream(), System.err, args), 0);
InternalClientConnection conn1 =
new InternalClientConnection(userDN);
@@ -2265,7 +2266,7 @@
"--noPropertiesFile",
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
InternalClientConnection conn1 =
new InternalClientConnection(userDN);
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/core/ModifyOperationTestCase.java b/opendj-server-legacy/src/test/java/org/opends/server/core/ModifyOperationTestCase.java
index 14419ab..7e52763 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/core/ModifyOperationTestCase.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/core/ModifyOperationTestCase.java
@@ -25,6 +25,7 @@
import static org.opends.server.protocols.internal.InternalClientConnection.*;
import static org.opends.server.protocols.internal.Requests.newSearchRequest;
import static org.opends.server.protocols.ldap.LDAPConstants.*;
+import static org.opends.server.types.NullOutputStream.nullPrintStream;
import static org.opends.server.util.CollectionUtils.*;
import static org.opends.server.util.ServerConstants.*;
import static org.testng.Assert.*;
@@ -34,6 +35,7 @@
import java.util.List;
import org.forgerock.i18n.LocalizableMessage;
+import org.forgerock.opendj.ldap.Base64;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.DN;
import org.forgerock.opendj.ldap.ModificationType;
@@ -54,7 +56,7 @@
import org.opends.server.protocols.ldap.LDAPModification;
import org.opends.server.protocols.ldap.ModifyRequestProtocolOp;
import org.opends.server.protocols.ldap.ModifyResponseProtocolOp;
-import org.opends.server.tools.LDAPModify;
+import com.forgerock.opendj.ldap.tools.LDAPModify;
import org.opends.server.tools.RemoteConnection;
import org.opends.server.types.Attribute;
import org.opends.server.types.Attributes;
@@ -68,7 +70,6 @@
import org.opends.server.types.Operation;
import org.opends.server.types.RawModification;
import org.opends.server.types.WritabilityMode;
-import org.opends.server.util.Base64;
import org.opends.server.workflowelement.localbackend.LocalBackendModifyOperation;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
@@ -2854,7 +2855,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
assertTrue(DirectoryServer.getSchema().hasAttributeType(attrName));
path = TestCaseUtils.createTempFile(
@@ -2875,7 +2876,7 @@
"-f", path
};
- assertFalse(LDAPModify.mainModify(args, false, null, null) == 0);
+ assertFalse(LDAPModify.run(nullPrintStream(), nullPrintStream(), args) == 0);
}
@@ -2912,7 +2913,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
assertTrue(DirectoryServer.getSchema().hasObjectClass(ocName));
path = TestCaseUtils.createTempFile(
@@ -2930,7 +2931,7 @@
"-f", path
};
- assertFalse(LDAPModify.mainModify(args, false, null, null) == 0);
+ assertFalse(LDAPModify.run(nullPrintStream(), nullPrintStream(), args) == 0);
}
@@ -3098,7 +3099,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
}
/**
@@ -3144,7 +3145,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
}
/**
@@ -3194,7 +3195,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
}
private String firstValue(List<Attribute> attrs)
@@ -3406,7 +3407,7 @@
"axuJ8LFNbZtsp1ldW3i84+F5+SYT+xI67ZcoAtwx/VFVI9s5I/Gkmu9f9nxjPpK7" +
"1AIUXiE3Qcck";
- ByteString value = ByteString.wrap(Base64.decode(certificateValue));
+ ByteString value = ByteString.wrap(Base64.decode(certificateValue).toByteArray());
LDAPAttribute attr = new LDAPAttribute("usercertificate", value);
ModifyOperation modifyOperation = processModify("uid=test.user," + baseDN, new LDAPModification(ADD, attr));
assertEquals(modifyOperation.getResultCode(), ResultCode.SUCCESS);
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/core/PasswordPolicyTestCase.java b/opendj-server-legacy/src/test/java/org/opends/server/core/PasswordPolicyTestCase.java
index 1327b27..027e245 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/core/PasswordPolicyTestCase.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/core/PasswordPolicyTestCase.java
@@ -30,7 +30,7 @@
import org.opends.server.api.PasswordStorageScheme;
import org.opends.server.extensions.InitializationUtils;
import org.opends.server.schema.UserPasswordSyntax;
-import org.opends.server.tools.LDAPModify;
+import com.forgerock.opendj.ldap.tools.LDAPModify;
import org.opends.server.types.Attribute;
import org.opends.server.types.DirectoryException;
import org.opends.server.types.Entry;
@@ -42,6 +42,7 @@
import static org.assertj.core.api.Assertions.*;
import static org.forgerock.opendj.ldap.schema.CoreSchema.*;
+import static org.opends.server.types.NullOutputStream.nullPrintStream;
import static org.testng.Assert.*;
/**
@@ -4247,7 +4248,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
}
finally
{
@@ -4378,7 +4379,7 @@
"-f", newPWsPath
};
- assertEquals(LDAPModify.mainModify(args, false, System.out, System.err),
+ assertEquals(LDAPModify.run(System.out, System.err, args),
0);
@@ -4402,7 +4403,7 @@
"-f", newPWsPath
};
- assertEquals(LDAPModify.mainModify(args, false, System.out, System.err),
+ assertEquals(LDAPModify.run(System.out, System.err, args),
0);
@@ -4467,7 +4468,7 @@
"-f", origPWPath
};
- assertEquals(LDAPModify.mainModify(args, false, System.out, System.err), 0);
+ assertEquals(LDAPModify.run(System.out, System.err, args), 0);
TestCaseUtils.dsconfig(
"set-password-policy-prop",
@@ -4478,8 +4479,7 @@
{
// Make sure that we cannot re-use the original password as a new
// password.
- assertFalse(LDAPModify.mainModify(args, false, System.out, System.err) ==
- 0);
+ assertFalse(LDAPModify.run(System.out, System.err, args) == 0);
// Change the password three times.
@@ -4508,8 +4508,7 @@
"-f", newPWsPath
};
- assertEquals(LDAPModify.mainModify(args, false, System.out, System.err),
- 0);
+ assertEquals(LDAPModify.run(System.out, System.err, args), 0);
advanceTimeThread();
@@ -4525,8 +4524,7 @@
"-f", origPWPath
};
- assertFalse(LDAPModify.mainModify(args, false, System.out, System.err) ==
- 0);
+ assertFalse(LDAPModify.run(System.out, System.err, args) == 0);
// Change the password one more time and then verify that we can use the
@@ -4551,8 +4549,7 @@
"-f", newPWsPath2
};
- assertEquals(LDAPModify.mainModify(args, false, System.out, System.err),
- 0);
+ assertEquals(LDAPModify.run(System.out, System.err, args), 0);
advanceTimeThread();
@@ -4574,8 +4571,7 @@
"-f", firstPWPath
};
- assertFalse(LDAPModify.mainModify(args, false, System.out, System.err) ==
- 0);
+ assertFalse(LDAPModify.run(System.out, System.err, args) == 0);
advanceTimeThread();
@@ -4588,8 +4584,7 @@
"--policy-name", "Default Password Policy",
"--set", "password-history-count:2");
- assertEquals(LDAPModify.mainModify(args, false, System.out, System.err),
- 0);
+ assertEquals(LDAPModify.run(System.out, System.err, args), 0);
}
finally
{
@@ -4643,7 +4638,7 @@
"-f", origPWPath
};
- assertEquals(LDAPModify.mainModify(args, false, System.out, System.err), 0);
+ assertEquals(LDAPModify.run(System.out, System.err, args), 0);
TestCaseUtils.dsconfig(
"set-password-policy-prop",
@@ -4654,8 +4649,7 @@
{
// Make sure that we can no longer re-use the original password as a new
// password.
- assertFalse(LDAPModify.mainModify(args, false, System.out, System.err) ==
- 0);
+ assertFalse(LDAPModify.run(System.out, System.err, args) == 0);
// Change the password three times.
@@ -4684,8 +4678,7 @@
"-f", newPWsPath
};
- assertEquals(LDAPModify.mainModify(args, false, System.out, System.err),
- 0);
+ assertEquals(LDAPModify.run(System.out, System.err, args), 0);
// Make sure that we still can't use the original password.
@@ -4698,15 +4691,13 @@
"-f", origPWPath
};
- assertFalse(LDAPModify.mainModify(args, false, System.out, System.err) ==
- 0);
+ assertFalse(LDAPModify.run(System.out, System.err, args) == 0);
// Sleep for six seconds and then verify that we can use the original
// password again.
Thread.sleep(6000);
- assertEquals(LDAPModify.mainModify(args, false, System.out, System.err),
- 0);
+ assertEquals(LDAPModify.run(System.out, System.err, args), 0);
}
finally
{
@@ -4748,7 +4739,7 @@
"-f", path
};
- assertFalse(LDAPModify.mainModify(args, false, System.out, System.err) ==
+ assertFalse(LDAPModify.run(System.out, System.err, args) ==
0);
}
@@ -4786,7 +4777,7 @@
"-f", path
};
- assertFalse(LDAPModify.mainModify(args, false, System.out, System.err) ==
+ assertFalse(LDAPModify.run(System.out, System.err, args) ==
0);
}
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/core/RejectUnauthReqTests.java b/opendj-server-legacy/src/test/java/org/opends/server/core/RejectUnauthReqTests.java
index 71bf3f0..ab71f03 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/core/RejectUnauthReqTests.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/core/RejectUnauthReqTests.java
@@ -19,16 +19,16 @@
import java.util.ArrayList;
import java.util.List;
+import com.forgerock.opendj.ldap.tools.LDAPCompare;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.DN;
import org.forgerock.opendj.ldap.ResultCode;
import org.opends.server.TestCaseUtils;
import org.opends.server.protocols.internal.InternalClientConnection;
import org.opends.server.tools.LDAPAuthenticationHandler;
-import org.opends.server.tools.LDAPCompare;
-import org.opends.server.tools.LDAPDelete;
-import org.opends.server.tools.LDAPModify;
-import org.opends.server.tools.LDAPSearch;
+import com.forgerock.opendj.ldap.tools.LDAPDelete;
+import com.forgerock.opendj.ldap.tools.LDAPModify;
+import com.forgerock.opendj.ldap.tools.LDAPSearch;
import org.opends.server.tools.RemoteConnection;
import org.opends.server.types.AuthenticationInfo;
import org.opends.server.types.Control;
@@ -38,6 +38,7 @@
import static org.opends.server.TestCaseUtils.*;
import static org.opends.server.protocols.internal.InternalClientConnection.*;
+import static org.opends.server.types.NullOutputStream.nullPrintStream;
import static org.opends.server.util.ServerConstants.*;
import static org.testng.Assert.*;
@@ -90,20 +91,15 @@
"dn: o=rejectTestCase,o=test", "objectclass: top",
"objectclass: organization", "o: rejectTestCase",
"description: Reject Test Case");
- return LDAPModify.mainModify(addArgs(authenticate, filePath), false, null, null);
+ return LDAPModify.run(nullPrintStream(), nullPrintStream(), modifyArgs(authenticate, filePath));
}
private String[] modifyArgs(boolean authenticate, String filePath)
{
- return args(authenticate, false, filePath);
+ return args(authenticate, filePath);
}
- private String[] addArgs(boolean authenticate, String filePath)
- {
- return args(authenticate, true, filePath);
- }
-
- private String[] args(boolean authenticate, boolean add, String filePath)
+ private String[] args(boolean authenticate, String filePath)
{
Args args = new Args();
args.add("--noPropertiesFile");
@@ -114,10 +110,6 @@
args.add("-D", "cn=directory manager");
args.add("-w", "password");
}
- if (add)
- {
- args.add("-a");
- }
args.add("-f", filePath);
return args.toArray();
}
@@ -136,7 +128,7 @@
String path = TestCaseUtils.createTempFile("dn: o=rejectTestCase,o=test",
"changetype: modify", "replace: description",
"description: New Description");
- return LDAPModify.mainModify(modifyArgs(authenticate, path), false, null, null);
+ return LDAPModify.run(nullPrintStream(), nullPrintStream(), modifyArgs(authenticate, path));
}
@@ -153,7 +145,7 @@
*/
private int performCompareOperation(boolean authentication) throws Exception
{
- return LDAPCompare.mainCompare(compareArgs(authentication), false, null, null);
+ return LDAPCompare.run(nullPrintStream(), nullPrintStream(), compareArgs(authentication));
}
private String[] compareArgs(boolean authenticate)
@@ -186,7 +178,7 @@
String path = TestCaseUtils
.createTempFile("dn: o=rejectTestCase,o=Test", "changetype: modrdn",
"newrdn: o=mod_rejectTestCase", "deleteoldrdn: 0");
- return LDAPModify.mainModify(modRdnArgs(authentication, path), false, null, null);
+ return LDAPModify.run(nullPrintStream(), nullPrintStream(), modRdnArgs(authentication, path));
}
private String[] modRdnArgs(boolean authenticate, String path)
@@ -216,7 +208,7 @@
*/
private int performDeleteOperation(boolean authentication) throws Exception
{
- return LDAPDelete.mainDelete(deleteArgs(authentication), false, null, null);
+ return LDAPDelete.run(nullPrintStream(), nullPrintStream(), deleteArgs(authentication));
}
private String[] deleteArgs(boolean authenticate)
@@ -227,7 +219,6 @@
args.add("-p", TestCaseUtils.getServerLdapPort());
if (authenticate)
{
- args.add("-V", "3");
args.add("-D", "cn=Directory Manager");
args.add("-w", "password");
}
@@ -284,7 +275,7 @@
public void testAuthSearchDefCfg()
{
DirectoryServer.setRejectUnauthenticatedRequests(false);
- assertEquals(LDAPSearch.mainSearch(searchArgs(Auth.SIMPLE), false, null, System.err), 0);
+ assertEquals(LDAPSearch.run(nullPrintStream(), System.err, searchArgs(Auth.SIMPLE)), 0);
}
/**
@@ -295,7 +286,7 @@
public void testUnauthSearchDefCfg()
{
DirectoryServer.setRejectUnauthenticatedRequests(false);
- assertEquals(LDAPSearch.mainSearch(searchArgs(Auth.ANONYMOUS), false, null, System.err), 0);
+ assertEquals(LDAPSearch.run(nullPrintStream(), System.err, searchArgs(Auth.ANONYMOUS)), 0);
}
/**
@@ -396,7 +387,7 @@
public void testStartTLSUnauthDefCfg() throws Exception
{
DirectoryServer.setRejectUnauthenticatedRequests(false);
- assertEquals(LDAPSearch.mainSearch(searchArgs(Auth.START_TLS), false, null, System.err), 0);
+ assertEquals(LDAPSearch.run(nullPrintStream(), System.err, searchArgs(Auth.START_TLS)), 0);
}
/**
@@ -454,8 +445,8 @@
{
DirectoryServer.setRejectUnauthenticatedRequests(true);
- assertFalse(LDAPSearch.mainSearch(searchArgs(Auth.ANONYMOUS), false, null, null) == 0);
- assertEquals(LDAPSearch.mainSearch(searchArgs(Auth.START_TLS), false, null, System.err), 0);
+ assertFalse(LDAPSearch.run(nullPrintStream(), nullPrintStream(), searchArgs(Auth.ANONYMOUS)) == 0);
+ assertEquals(LDAPSearch.run(nullPrintStream(), System.err, searchArgs(Auth.START_TLS)), 0);
}
finally
{
@@ -507,8 +498,7 @@
try
{
DirectoryServer.setRejectUnauthenticatedRequests(true);
-
- assertEquals(LDAPSearch.mainSearch(searchArgs(Auth.START_TLS), false, null, System.err), 0);
+ assertEquals(LDAPSearch.run(nullPrintStream(), System.err, searchArgs(Auth.START_TLS)), 0);
}
finally
{
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/core/SearchOperationTestCase.java b/opendj-server-legacy/src/test/java/org/opends/server/core/SearchOperationTestCase.java
index de6744e..6ffeb7d 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/core/SearchOperationTestCase.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/core/SearchOperationTestCase.java
@@ -19,6 +19,7 @@
import static org.assertj.core.api.Assertions.*;
import static org.opends.server.protocols.internal.InternalClientConnection.*;
import static org.opends.server.protocols.internal.Requests.*;
+import static org.opends.server.types.NullOutputStream.nullPrintStream;
import static org.opends.server.util.CollectionUtils.*;
import static org.opends.server.util.ServerConstants.*;
import static org.testng.Assert.*;
@@ -57,7 +58,7 @@
import org.opends.server.protocols.ldap.SearchRequestProtocolOp;
import org.opends.server.protocols.ldap.SearchResultDoneProtocolOp;
import org.opends.server.protocols.ldap.SearchResultEntryProtocolOp;
-import org.opends.server.tools.LDAPModify;
+import com.forgerock.opendj.ldap.tools.LDAPModify;
import org.opends.server.tools.RemoteConnection;
import org.opends.server.types.Attribute;
import org.opends.server.types.Control;
@@ -1261,10 +1262,9 @@
"-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
"-D","cn=directory manager",
"-w","password",
- "-a",
"-f", filePath
};
- int err = LDAPModify.mainModify(args, false, null,null);
+ int err = LDAPModify.run(nullPrintStream(), nullPrintStream(), args);
assertEquals(err,0);
@@ -1295,10 +1295,9 @@
"-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
"-D","cn=directory manager",
"-w","password",
- "-a",
"-f", filePath
};
- int err = LDAPModify.mainModify(args, false, null,null);
+ int err = LDAPModify.run(nullPrintStream(), nullPrintStream(), args);
assertEquals(err, 0);
}
}
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/core/SubentryManagerTestCase.java b/opendj-server-legacy/src/test/java/org/opends/server/core/SubentryManagerTestCase.java
index 2324943..be790a2 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/core/SubentryManagerTestCase.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/core/SubentryManagerTestCase.java
@@ -22,6 +22,7 @@
import static org.opends.server.TestCaseUtils.*;
import static org.opends.server.protocols.internal.InternalClientConnection.*;
import static org.opends.server.protocols.internal.Requests.*;
+import static org.opends.server.types.NullOutputStream.nullPrintStream;
import static org.opends.server.util.CollectionUtils.*;
import static org.opends.server.util.ServerConstants.*;
import static org.testng.Assert.*;
@@ -38,8 +39,8 @@
import org.opends.server.TestCaseUtils;
import org.opends.server.protocols.internal.InternalSearchOperation;
import org.opends.server.protocols.internal.SearchRequest;
-import org.opends.server.tools.LDAPDelete;
-import org.opends.server.tools.LDAPModify;
+import com.forgerock.opendj.ldap.tools.LDAPDelete;
+import com.forgerock.opendj.ldap.tools.LDAPModify;
import org.opends.server.types.Attribute;
import org.opends.server.types.Attributes;
import org.opends.server.types.DirectoryException;
@@ -418,7 +419,7 @@
"--noPropertiesFile",
SUFFIX
};
- assertEquals(LDAPDelete.mainDelete(args, false, null, System.err), 0);
+ assertEquals(LDAPDelete.run(nullPrintStream(), System.err, args), 0);
assertTrue(DirectoryServer.getSubentryManager().getCollectiveSubentries(
DN.valueOf("uid=rogasawara," + BASE)).isEmpty());
@@ -450,7 +451,7 @@
"--noPropertiesFile",
"-f", newPath
};
- assertEquals(LDAPModify.mainModify(newArgs, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, newArgs), 0);
assertNotNull(DirectoryServer.getEntry(DN.valueOf(
"uid=rogasawara," + NEWBASE + "," + SUFFIX)));
@@ -476,7 +477,7 @@
"--noPropertiesFile",
"-f", oldPath
};
- assertEquals(LDAPModify.mainModify(oldArgs, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, oldArgs), 0);
assertNotNull(DirectoryServer.getEntry(DN.valueOf(
"uid=rogasawara," + OLDBASE + "," + SUFFIX)));
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/core/TestModifyDNOperation.java b/opendj-server-legacy/src/test/java/org/opends/server/core/TestModifyDNOperation.java
index 9e413a8..6ad97bf 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/core/TestModifyDNOperation.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/core/TestModifyDNOperation.java
@@ -22,6 +22,7 @@
import static org.forgerock.opendj.ldap.requests.Requests.*;
import static org.opends.server.TestCaseUtils.*;
import static org.opends.server.protocols.internal.InternalClientConnection.*;
+import static org.opends.server.types.NullOutputStream.nullPrintStream;
import static org.opends.server.util.ServerConstants.*;
import static org.testng.Assert.*;
@@ -47,7 +48,7 @@
import org.opends.server.protocols.ldap.LDAPResultCode;
import org.opends.server.protocols.ldap.ModifyDNRequestProtocolOp;
import org.opends.server.protocols.ldap.ModifyDNResponseProtocolOp;
-import org.opends.server.tools.LDAPModify;
+import com.forgerock.opendj.ldap.tools.LDAPModify;
import org.opends.server.tools.RemoteConnection;
import org.opends.server.types.Attribute;
import org.opends.server.types.CancelRequest;
@@ -844,7 +845,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
assertTrue(DirectoryServer.getSchema().hasAttributeType(attrName));
path = TestCaseUtils.createTempFile(
@@ -870,7 +871,7 @@
"-f", path
};
- assertFalse(LDAPModify.mainModify(args, false, null, null) == 0);
+ assertFalse(LDAPModify.run(nullPrintStream(), nullPrintStream(), args) == 0);
}
/**
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/extensions/AnonymousSASLMechanismHandlerTestCase.java b/opendj-server-legacy/src/test/java/org/opends/server/extensions/AnonymousSASLMechanismHandlerTestCase.java
index fd08d31..bac59cc 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/extensions/AnonymousSASLMechanismHandlerTestCase.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/extensions/AnonymousSASLMechanismHandlerTestCase.java
@@ -23,12 +23,13 @@
import org.forgerock.opendj.ldap.ResultCode;
import org.opends.server.TestCaseUtils;
import org.opends.server.core.BindOperationBasis;
-import org.opends.server.tools.LDAPSearch;
+import com.forgerock.opendj.ldap.tools.LDAPSearch;
import org.opends.server.types.Control;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static org.opends.server.protocols.internal.InternalClientConnection.*;
+import static org.opends.server.types.NullOutputStream.nullPrintStream;
import static org.opends.server.util.ServerConstants.*;
import static org.testng.Assert.*;
@@ -182,12 +183,11 @@
"--noPropertiesFile",
"-h", "127.0.0.1",
"-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
- "-o", "mech=ANONYMOUS",
"-b", "",
"-s", "base",
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
+ assertEquals(LDAPSearch.run(nullPrintStream(), System.err, args), 0);
handler.finalizeSASLMechanismHandler();
}
@@ -209,13 +209,12 @@
"--noPropertiesFile",
"-h", "127.0.0.1",
"-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
- "-o", "mech=ANONYMOUS",
"-o", "trace=LDAP Trace String",
"-b", "",
"-s", "base",
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
+ assertEquals(LDAPSearch.run(nullPrintStream(), System.err, args), 0);
handler.finalizeSASLMechanismHandler();
}
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/extensions/CRAMMD5SASLMechanismHandlerTestCase.java b/opendj-server-legacy/src/test/java/org/opends/server/extensions/CRAMMD5SASLMechanismHandlerTestCase.java
index 8ada8c4..010b7cd 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/extensions/CRAMMD5SASLMechanismHandlerTestCase.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/extensions/CRAMMD5SASLMechanismHandlerTestCase.java
@@ -27,13 +27,14 @@
import org.opends.server.core.BindOperation;
import org.opends.server.core.DirectoryServer;
import org.opends.server.protocols.internal.InternalClientConnection;
-import org.opends.server.tools.LDAPSearch;
+import com.forgerock.opendj.ldap.tools.LDAPSearch;
import org.opends.server.types.*;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.opends.server.TestCaseUtils.*;
+import static org.opends.server.types.NullOutputStream.nullPrintStream;
import static org.opends.server.util.ServerConstants.*;
import static org.testng.Assert.*;
@@ -189,7 +190,7 @@
"-s", "base",
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
+ assertEquals(LDAPSearch.run(nullPrintStream(), System.err, args), 0);
}
@@ -231,7 +232,7 @@
"-s", "base",
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
+ assertEquals(LDAPSearch.run(nullPrintStream(), System.err, args), 0);
}
@@ -276,7 +277,7 @@
"-s", "base",
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
+ assertEquals(LDAPSearch.run(nullPrintStream(), System.err, args), 0);
}
@@ -318,7 +319,7 @@
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(LDAPSearch.run(nullPrintStream(), nullPrintStream(), args) == 0);
}
@@ -360,7 +361,7 @@
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(LDAPSearch.run(nullPrintStream(), nullPrintStream(), args) == 0);
}
@@ -400,7 +401,7 @@
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(LDAPSearch.run(nullPrintStream(), nullPrintStream(), args) == 0);
}
@@ -440,7 +441,7 @@
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(LDAPSearch.run(nullPrintStream(), nullPrintStream(), args) == 0);
}
@@ -480,7 +481,7 @@
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(LDAPSearch.run(nullPrintStream(), nullPrintStream(), args) == 0);
}
@@ -520,7 +521,7 @@
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(LDAPSearch.run(nullPrintStream(), nullPrintStream(), args) == 0);
}
@@ -547,7 +548,7 @@
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(LDAPSearch.run(nullPrintStream(), nullPrintStream(), args) == 0);
}
@@ -575,7 +576,7 @@
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(LDAPSearch.run(nullPrintStream(), nullPrintStream(), args) == 0);
}
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/extensions/DigestMD5SASLMechanismHandlerTestCase.java b/opendj-server-legacy/src/test/java/org/opends/server/extensions/DigestMD5SASLMechanismHandlerTestCase.java
index f8354d2..fc3b3eb 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/extensions/DigestMD5SASLMechanismHandlerTestCase.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/extensions/DigestMD5SASLMechanismHandlerTestCase.java
@@ -27,7 +27,7 @@
import org.opends.server.core.DeleteOperation;
import org.opends.server.core.DirectoryServer;
import org.opends.server.protocols.internal.InternalClientConnection;
-import org.opends.server.tools.LDAPSearch;
+import com.forgerock.opendj.ldap.tools.LDAPSearch;
import org.opends.server.types.AuthenticationInfo;
import org.forgerock.opendj.ldap.DN;
import org.opends.server.types.Entry;
@@ -39,6 +39,7 @@
import static org.opends.server.TestCaseUtils.*;
import static org.opends.server.protocols.internal.InternalClientConnection.*;
+import static org.opends.server.types.NullOutputStream.nullPrintStream;
import static org.opends.server.util.ServerConstants.*;
import static org.testng.Assert.*;
@@ -217,7 +218,7 @@
"-s", "base",
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
+ assertEquals(LDAPSearch.run(nullPrintStream(), System.err, args), 0);
}
@@ -260,7 +261,7 @@
"-s", "base",
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
+ assertEquals(LDAPSearch.run(nullPrintStream(), System.err, args), 0);
}
@@ -303,7 +304,7 @@
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(LDAPSearch.run(nullPrintStream(), nullPrintStream(), args) == 0);
}
@@ -346,7 +347,7 @@
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(LDAPSearch.run(nullPrintStream(), nullPrintStream(), args) == 0);
}
@@ -387,7 +388,7 @@
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(LDAPSearch.run(nullPrintStream(), nullPrintStream(), args) == 0);
}
@@ -428,7 +429,7 @@
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(LDAPSearch.run(nullPrintStream(), nullPrintStream(), args) == 0);
}
@@ -469,7 +470,7 @@
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(LDAPSearch.run(nullPrintStream(), nullPrintStream(), args) == 0);
}
@@ -510,7 +511,7 @@
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(LDAPSearch.run(nullPrintStream(), nullPrintStream(), args) == 0);
}
@@ -551,7 +552,7 @@
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(LDAPSearch.run(nullPrintStream(), nullPrintStream(), args) == 0);
}
@@ -581,7 +582,7 @@
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(LDAPSearch.run(nullPrintStream(), nullPrintStream(), args) == 0);
}
@@ -611,7 +612,7 @@
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(LDAPSearch.run(nullPrintStream(), nullPrintStream(), args) == 0);
}
@@ -641,7 +642,7 @@
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(LDAPSearch.run(nullPrintStream(), nullPrintStream(), args) == 0);
}
@@ -685,7 +686,7 @@
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(LDAPSearch.run(nullPrintStream(), nullPrintStream(), args) == 0);
}
@@ -714,7 +715,7 @@
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(LDAPSearch.run(nullPrintStream(), nullPrintStream(), args) == 0);
}
@@ -758,7 +759,7 @@
"-s", "base",
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
+ assertEquals(LDAPSearch.run(nullPrintStream(), System.err, args), 0);
DeleteOperation deleteOperation = getRootConnection().processDelete(e.getName());
@@ -806,7 +807,7 @@
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(LDAPSearch.run(nullPrintStream(), nullPrintStream(), args) == 0);
}
@@ -850,7 +851,7 @@
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(LDAPSearch.run(nullPrintStream(), nullPrintStream(), args) == 0);
}
@@ -894,7 +895,7 @@
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(LDAPSearch.run(nullPrintStream(), nullPrintStream(), args) == 0);
}
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/extensions/ExternalSASLMechanismHandlerTestCase.java b/opendj-server-legacy/src/test/java/org/opends/server/extensions/ExternalSASLMechanismHandlerTestCase.java
index ffb2ae2..c0cc186 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/extensions/ExternalSASLMechanismHandlerTestCase.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/extensions/ExternalSASLMechanismHandlerTestCase.java
@@ -23,6 +23,7 @@
import java.util.List;
import org.forgerock.opendj.config.server.ConfigException;
+import org.forgerock.opendj.ldap.Base64;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.ModificationType;
import org.forgerock.opendj.ldap.ResultCode;
@@ -34,20 +35,21 @@
import org.opends.server.protocols.ldap.BindRequestProtocolOp;
import org.opends.server.protocols.ldap.BindResponseProtocolOp;
import org.opends.server.protocols.ldap.LDAPMessage;
-import org.opends.server.tools.LDAPSearch;
+import com.forgerock.opendj.ldap.tools.LDAPSearch;
import org.opends.server.tools.RemoteConnection;
import org.opends.server.types.Attributes;
import org.forgerock.opendj.ldap.DN;
import org.opends.server.types.Entry;
import org.opends.server.types.InitializationException;
import org.opends.server.types.Modification;
-import org.opends.server.util.Base64;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.forgerock.opendj.ldap.ModificationType.*;
+import static org.opends.server.TestCaseUtils.runLdapSearchTrustCertificateForSession;
import static org.opends.server.protocols.internal.InternalClientConnection.*;
+import static org.opends.server.types.NullOutputStream.nullPrintStream;
import static org.opends.server.util.CollectionUtils.*;
import static org.testng.Assert.*;
@@ -202,13 +204,14 @@
"-K", keyStorePath,
"-W", "password",
"-P", trustStorePath,
- "-r",
+ "-o", "mech=EXTERNAL",
+ "-N", "client-cert",
"-b", "",
"-s", "base",
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
+ assertEquals(runLdapSearchTrustCertificateForSession(args), 0);
}
@@ -247,13 +250,14 @@
"-K", keyStorePath,
"-W", "password",
"-X",
- "-r",
+ "-o", "mech=EXTERNAL",
+ "-N", "client-cert",
"-b", "",
"-s", "base",
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
+ assertEquals(LDAPSearch.run(nullPrintStream(), System.err, args), 0);
}
@@ -308,13 +312,13 @@
"-K", keyStorePath,
"-W", "password",
"-X",
- "-r",
+ "-o", "mech=EXTERNAL",
"-b", "",
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(LDAPSearch.run(nullPrintStream(), nullPrintStream(), args) == 0);
}
@@ -363,13 +367,13 @@
"-K", keyStorePath,
"-W", "password",
"-X",
- "-r",
+ "-o", "mech=EXTERNAL",
"-b", "",
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(LDAPSearch.run(nullPrintStream(), nullPrintStream(), args) == 0);
mods.clear();
@@ -425,13 +429,14 @@
"-K", keyStorePath,
"-W", "password",
"-X",
- "-r",
+ "-o", "mech=EXTERNAL",
+ "-N", "client-cert",
"-b", "",
"-s", "base",
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
+ assertEquals(LDAPSearch.run(nullPrintStream(), System.err, args), 0);
}
@@ -491,13 +496,13 @@
"-K", keyStorePath,
"-W", "password",
"-X",
- "-r",
+ "-o", "mech=EXTERNAL",
"-b", "",
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(LDAPSearch.run(nullPrintStream(), nullPrintStream(), args) == 0);
}
@@ -554,13 +559,14 @@
"-K", keyStorePath,
"-W", "password",
"-X",
- "-r",
+ "-o", "mech=EXTERNAL",
+ "-N", "client-cert",
"-b", "",
"-s", "base",
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
+ assertEquals(LDAPSearch.run(nullPrintStream(), System.err, args), 0);
mods.clear();
@@ -635,13 +641,13 @@
"-K", keyStorePath,
"-W", "password",
"-X",
- "-r",
+ "-o", "mech=EXTERNAL",
"-b", "",
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(LDAPSearch.run(nullPrintStream(), nullPrintStream(), args) == 0);
mods.clear();
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/extensions/FingerprintCertificateMapperTestCase.java b/opendj-server-legacy/src/test/java/org/opends/server/extensions/FingerprintCertificateMapperTestCase.java
index 46ed8ec..874681b 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/extensions/FingerprintCertificateMapperTestCase.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/extensions/FingerprintCertificateMapperTestCase.java
@@ -18,7 +18,9 @@
import static org.forgerock.opendj.ldap.ModificationType.*;
import static org.forgerock.opendj.ldap.requests.Requests.*;
+import static org.opends.server.TestCaseUtils.runLdapSearchTrustCertificateForSession;
import static org.opends.server.protocols.internal.InternalClientConnection.*;
+import static org.opends.server.types.NullOutputStream.nullPrintStream;
import static org.testng.Assert.*;
import java.io.File;
@@ -31,7 +33,6 @@
import org.forgerock.opendj.server.config.meta.FingerprintCertificateMapperCfgDefn;
import org.opends.server.core.DirectoryServer;
import org.opends.server.core.ModifyOperation;
-import org.opends.server.tools.LDAPSearch;
import org.opends.server.types.DirectoryException;
import org.opends.server.types.Entry;
import org.opends.server.types.InitializationException;
@@ -205,13 +206,13 @@
"-K", keyStorePath,
"-W", "password",
"-P", trustStorePath,
- "-r",
+ "-o", "mech=EXTERNAL",
+ "-N", "client-cert",
"-b", "",
"-s", "base",
"(objectClass=*)"
};
-
- assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
+ assertEquals(runLdapSearchTrustCertificateForSession(args), 0);
}
finally
{
@@ -267,13 +268,13 @@
"-K", keyStorePath,
"-W", "password",
"-P", trustStorePath,
- "-r",
+ "-o", "mech=EXTERNAL",
+ "-N", "client-cert",
"-b", "",
"-s", "base",
"(objectClass=*)"
};
-
- assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
+ assertEquals(runLdapSearchTrustCertificateForSession(args), 0);
}
finally
{
@@ -326,13 +327,13 @@
"-K", keyStorePath,
"-W", "password",
"-P", trustStorePath,
- "-r",
+ "-o", "mech=EXTERNAL",
+ "-N", "client-cert",
"-b", "",
"-s", "base",
"(objectClass=*)"
};
-
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(runLdapSearchTrustCertificateForSession(nullPrintStream(), nullPrintStream(), args) == 0);
}
finally
{
@@ -399,13 +400,13 @@
"-K", keyStorePath,
"-W", "password",
"-P", trustStorePath,
- "-r",
+ "-o", "mech=EXTERNAL",
+ "-N", "client-cert",
"-b", "",
"-s", "base",
"(objectClass=*)"
};
-
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(runLdapSearchTrustCertificateForSession(nullPrintStream(), nullPrintStream(), args) == 0);
}
finally
{
@@ -600,13 +601,13 @@
"-K", keyStorePath,
"-W", "password",
"-P", trustStorePath,
- "-r",
+ "-o", "mech=EXTERNAL",
+ "-N", "client-cert",
"-b", "cn=config",
"-s", "sub",
"(objectClass=*)"
};
-
- assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
+ assertEquals(runLdapSearchTrustCertificateForSession(args), 0);
}
finally
{
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/extensions/PasswordModifyExtendedOperationTestCase.java b/opendj-server-legacy/src/test/java/org/opends/server/extensions/PasswordModifyExtendedOperationTestCase.java
index c5e7cf5..c11cf4c 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/extensions/PasswordModifyExtendedOperationTestCase.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/extensions/PasswordModifyExtendedOperationTestCase.java
@@ -34,7 +34,7 @@
import org.opends.server.core.ExtendedOperation;
import org.opends.server.core.ModifyOperation;
import org.opends.server.protocols.internal.InternalClientConnection;
-import org.opends.server.tools.LDAPPasswordModify;
+import com.forgerock.opendj.ldap.tools.LDAPPasswordModify;
import org.opends.server.types.AuthenticationInfo;
import org.forgerock.opendj.ldap.DN;
import org.opends.server.types.DirectoryException;
@@ -47,6 +47,7 @@
import static org.forgerock.opendj.ldap.ModificationType.*;
import static org.opends.server.extensions.ExtensionsConstants.*;
import static org.opends.server.protocols.internal.InternalClientConnection.*;
+import static org.opends.server.types.NullOutputStream.nullPrintStream;
import static org.opends.server.util.ServerConstants.*;
import static org.testng.Assert.*;
@@ -161,7 +162,7 @@
"-c", "password",
"-n", "newPassword"
};
- assertEquals(LDAPPasswordModify.mainPasswordModify(args, false, null, null), 0);
+ assertEquals(LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args), 0);
verifyPasswordPerformingInternalBind(DN.valueOf("cn=Directory Manager"), "newPassword");
@@ -176,7 +177,7 @@
"-c", "newPassword",
"-n", "password"
};
- assertEquals(LDAPPasswordModify.mainPasswordModify(args, false, null, null), 0);
+ assertEquals(LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args), 0);
}
@@ -204,10 +205,9 @@
"-D", "cn=Directory Manager",
"-w", "password",
"-c", "password",
- "-n", "newPassword",
- "-A"
+ "-n", "newPassword"
};
- assertEquals(LDAPPasswordModify.mainPasswordModify(args, false, null, null), 0);
+ assertEquals(LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args), 0);
verifyPasswordPerformingInternalBind(DN.valueOf("cn=Directory Manager"), "newPassword");
@@ -220,10 +220,9 @@
"-D", "cn=Directory Manager",
"-w", "newPassword",
"-c", "newPassword",
- "-n", "password",
- "-A"
+ "-n", "password"
};
- assertEquals(LDAPPasswordModify.mainPasswordModify(args, false, null, null), 0);
+ assertEquals(LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args), 0);
}
@@ -252,7 +251,7 @@
"-c", "password",
"-n", "newPassword"
};
- assertEquals(LDAPPasswordModify.mainPasswordModify(args, false, null, null), 0);
+ assertEquals(LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args), 0);
verifyPasswordPerformingInternalBind(DN.valueOf("cn=Directory Manager"), "newPassword");
@@ -266,7 +265,7 @@
"-c", "newPassword",
"-n", "password"
};
- assertEquals(LDAPPasswordModify.mainPasswordModify(args, false, null, null), 0);
+ assertEquals(LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args), 0);
}
@@ -300,7 +299,7 @@
"-c", "password",
"-n", "newPassword"
};
- assertEquals(LDAPPasswordModify.mainPasswordModify(args, false, null, null), 0);
+ assertEquals(LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args), 0);
verifyPasswordPerformingInternalBind(userEntry.getName(), "newPassword");
}
@@ -335,7 +334,7 @@
"-w", "password",
"-n", "newPassword"
};
- assertEquals(LDAPPasswordModify.mainPasswordModify(args, false, null, null), 0);
+ assertEquals(LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args), 0);
verifyPasswordPerformingInternalBind(userEntry.getName(), "newPassword");
}
@@ -381,7 +380,7 @@
"-D", "uid=test.user,o=test",
"-w", "password"
};
- assertEquals(LDAPPasswordModify.mainPasswordModify(args, false, null, null), 0);
+ assertEquals(LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args), 0);
}
@@ -415,7 +414,7 @@
"-a", "dn:uid=test.user,o=test",
"-n", "newPassword"
};
- assertEquals(LDAPPasswordModify.mainPasswordModify(args, false, null, null), 0);
+ assertEquals(LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args), 0);
verifyPasswordPerformingInternalBind(userEntry.getName(), "newPassword");
}
@@ -452,7 +451,7 @@
"-a", "u:test.user",
"-n", "newPassword"
};
- assertEquals(LDAPPasswordModify.mainPasswordModify(args, false, null, null), 0);
+ assertEquals(LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args), 0);
verifyPasswordPerformingInternalBind(userEntry.getName(), "newPassword");
}
@@ -489,7 +488,7 @@
"-a", "uid=test.user,o=test",
"-n", "newPassword"
};
- assertEquals(LDAPPasswordModify.mainPasswordModify(args, false, null, null), 0);
+ assertEquals(LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args), 0);
verifyPasswordPerformingInternalBind(userEntry.getName(), "newPassword");
}
@@ -526,7 +525,7 @@
"-a", "test.user",
"-n", "newPassword"
};
- assertEquals(LDAPPasswordModify.mainPasswordModify(args, false, null, null), 0);
+ assertEquals(LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args), 0);
verifyPasswordPerformingInternalBind(userEntry.getName(), "newPassword");
}
@@ -561,7 +560,7 @@
"-c", "password",
"-n", "newPassword"
};
- assertEquals(LDAPPasswordModify.mainPasswordModify(args, false, null, null), 0);
+ assertEquals(LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args), 0);
verifyPasswordPerformingInternalBind(userEntry.getName(), "newPassword");
}
@@ -596,7 +595,7 @@
"-c", "password",
"-n", "newPassword"
};
- assertEquals(LDAPPasswordModify.mainPasswordModify(args, false, null, null), 0);
+ assertEquals(LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args), 0);
verifyPasswordPerformingInternalBind(userEntry.getName(), "newPassword");
}
@@ -632,7 +631,7 @@
"-a", "dn:uid=test.user,o=test",
"-n", "newPassword"
};
- assertEquals(LDAPPasswordModify.mainPasswordModify(args, false, null, null), 0);
+ assertEquals(LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args), 0);
verifyPasswordPerformingInternalBind(userEntry.getName(), "newPassword");
}
@@ -663,7 +662,7 @@
"-n", "newPassword"
};
- assertFalse(0 == LDAPPasswordModify.mainPasswordModify(args, false, null, null));
+ assertFalse(0 == LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args));
}
@@ -691,7 +690,7 @@
"-n", "newPassword"
};
- assertFalse(0 == LDAPPasswordModify.mainPasswordModify(args, false, null, null));
+ assertFalse(0 == LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args));
}
@@ -720,7 +719,7 @@
"-n", "newPassword"
};
- assertFalse(0 == LDAPPasswordModify.mainPasswordModify(args, false, null, null));
+ assertFalse(0 == LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args));
}
@@ -749,7 +748,7 @@
"-n", "newPassword"
};
- assertFalse(0 == LDAPPasswordModify.mainPasswordModify(args, false, null, null));
+ assertFalse(0 == LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args));
}
@@ -779,7 +778,7 @@
"-n", "newPassword"
};
- assertEquals(LDAPPasswordModify.mainPasswordModify(args, false, null, null), 32);
+ assertEquals(LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args), 32);
}
@@ -807,7 +806,7 @@
"-n", "newPassword"
};
- assertFalse(0 == LDAPPasswordModify.mainPasswordModify(args, false, null, null));
+ assertFalse(0 == LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args));
}
@@ -837,7 +836,7 @@
"-n", "newPassword"
};
- assertEquals(LDAPPasswordModify.mainPasswordModify(args, false, null, null), 49);
+ assertEquals(LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args), 49);
}
@@ -871,7 +870,7 @@
};
try {
- assertEquals(LDAPPasswordModify.mainPasswordModify(args, false, null, null), 0);
+ assertEquals(LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args), 0);
} finally {
applyPwdPolicyMods(dnStr, attr, "false");
}
@@ -908,7 +907,7 @@
"-n", "{SSHA}Fv4b7f4AnRMUiGqBi9QA1xJrTtRTqS3WpRi81g=="
};
- assertFalse(0 == LDAPPasswordModify.mainPasswordModify(args, false, null, null));
+ assertFalse(0 == LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args));
// don't restore password policy as this is already the default.
}
@@ -941,7 +940,7 @@
"-n", "{SSHA}Fv4b7f4AnRMUiGqBi9QA1xJrTtRTqS3WpRi81g=="
};
- assertFalse(0 == LDAPPasswordModify.mainPasswordModify(args, false, null, null));
+ assertFalse(0 == LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args));
}
@@ -1033,7 +1032,7 @@
};
try {
- assertFalse(0 == LDAPPasswordModify.mainPasswordModify(args, false, null, null));
+ assertFalse(0 == LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args));
} finally {
applyPwdPolicyMods(dnStr, attr, "true");
}
@@ -1071,7 +1070,7 @@
};
try {
- assertEquals(LDAPPasswordModify.mainPasswordModify(args, false, null, null), 53);
+ assertEquals(LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args), 53);
} finally {
applyPwdPolicyMods(dnStr, attr, "true");
}
@@ -1109,7 +1108,7 @@
};
try {
- assertFalse(0 == LDAPPasswordModify.mainPasswordModify(args, false, null, null));
+ assertFalse(0 == LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args));
} finally {
// Reset to default configuration
applyPwdPolicyMods(dnStr, attr, "false");
@@ -1148,7 +1147,7 @@
};
try {
- assertEquals(LDAPPasswordModify.mainPasswordModify(args, false, null, null), 13);
+ assertEquals(LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args), 13);
} finally {
// Reset to default configuration
applyPwdPolicyMods(dnStr, attr, "false");
@@ -1187,7 +1186,7 @@
};
try {
- assertEquals(LDAPPasswordModify.mainPasswordModify(args, false, null, null), 13);
+ assertEquals(LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args), 13);
} finally {
applyPwdPolicyMods(dnStr, attr, "false");
}
@@ -1227,7 +1226,7 @@
};
try {
- assertEquals(LDAPPasswordModify.mainPasswordModify(args, false, null, null), 13);
+ assertEquals(LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args), 13);
} finally {
// Reset to default configuration
applyPwdPolicyMods(dnStr, attr, "false");
@@ -1264,7 +1263,7 @@
};
try {
- assertFalse(0 == LDAPPasswordModify.mainPasswordModify(args, false, null, null));
+ assertFalse(0 == LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args));
} finally {
applyPwdPolicyMods(dnStr, attr, "0 seconds");
}
@@ -1301,7 +1300,7 @@
};
try {
- assertEquals(LDAPPasswordModify.mainPasswordModify(args, false, null, null), 53);
+ assertEquals(LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args), 53);
} finally {
applyPwdPolicyMods(dnStr, attr, "0 seconds");
}
@@ -1342,7 +1341,7 @@
"-n", "newPassword"
};
- assertFalse(0 == LDAPPasswordModify.mainPasswordModify(args, false, null, null));
+ assertFalse(0 == LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args));
} finally {
applyPwdPolicyMods(dnStr, attr1, "0 seconds");
applyPwdPolicyMods(dnStr, attr2, "false");
@@ -1386,7 +1385,7 @@
"-n", "newPassword"
};
- assertEquals(LDAPPasswordModify.mainPasswordModify(args, false, null, null), 0);
+ assertEquals(LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args), 0);
}
finally {
applyPwdPolicyMods(dnStr, attr1, "0 seconds");
@@ -1424,7 +1423,7 @@
"-w", "password"
};
try {
- assertFalse(0 == LDAPPasswordModify.mainPasswordModify(args, false, null, null));
+ assertFalse(0 == LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args));
} finally {
applyPwdPolicyMods(dnStr, attr, "cn=Random Password Generator,cn=Password Generators,cn=config");
}
@@ -1458,7 +1457,7 @@
"-c", "password"
};
try {
- assertFalse(0 == LDAPPasswordModify.mainPasswordModify(args, false, null, null));
+ assertFalse(0 == LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args));
}
finally {
applyPwdPolicyMods(dnStr, attr, "cn=Random Password Generator,cn=Password Generators,cn=config");
@@ -1496,7 +1495,7 @@
"-n", "short"
};
try {
- assertFalse(0 == LDAPPasswordModify.mainPasswordModify(args, false, null, null));
+ assertFalse(0 == LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args));
}
finally {
applyPwdPolicyMods(dnStr, attr);
@@ -1533,7 +1532,7 @@
"-n", "short"
};
try {
- assertFalse(0 == LDAPPasswordModify.mainPasswordModify(args, false, null, null));
+ assertFalse(0 == LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args));
}
finally {
applyPwdPolicyMods(dnStr, attr);
@@ -1586,7 +1585,7 @@
};
try {
- assertEquals(LDAPPasswordModify.mainPasswordModify(args, false, null, null), 0);
+ assertEquals(LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args), 0);
} finally {
applyPwdPolicyMods(dnStr, attr, "false");
}
@@ -1638,7 +1637,7 @@
};
try {
- assertEquals(LDAPPasswordModify.mainPasswordModify(args, false, null, System.err), 0);
+ assertEquals(LDAPPasswordModify.run(nullPrintStream(), System.err, args), 0);
} finally {
applyPwdPolicyMods(dnStr, attr, "false");
}
@@ -1688,7 +1687,7 @@
"-n", "newpassword"
};
- assertEquals(LDAPPasswordModify.mainPasswordModify(args, false, null, System.err), 0);
+ assertEquals(LDAPPasswordModify.run(nullPrintStream(), System.err, args), 0);
userEntry = DirectoryServer.getEntry(userDN);
assertNotNull(userEntry);
@@ -1744,7 +1743,7 @@
"-n", "newpassword"
};
- assertFalse(0 == LDAPPasswordModify.mainPasswordModify(args, false, null, System.err));
+ assertFalse(0 == LDAPPasswordModify.run(nullPrintStream(), System.err, args));
userEntry = DirectoryServer.getEntry(userDN);
assertNotNull(userEntry);
@@ -1792,7 +1791,7 @@
"-c", "password"
};
- assertEquals(LDAPPasswordModify.mainPasswordModify(args, false, null, System.err), 0);
+ assertEquals(LDAPPasswordModify.run(nullPrintStream(), System.err, args), 0);
userEntry = DirectoryServer.getEntry(userDN);
assertNotNull(userEntry);
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/extensions/PlainSASLMechanismHandlerTestCase.java b/opendj-server-legacy/src/test/java/org/opends/server/extensions/PlainSASLMechanismHandlerTestCase.java
index 98bc4ad..c7649f5 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/extensions/PlainSASLMechanismHandlerTestCase.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/extensions/PlainSASLMechanismHandlerTestCase.java
@@ -29,7 +29,7 @@
import org.opends.server.protocols.internal.Requests;
import org.opends.server.protocols.internal.SearchRequest;
import org.opends.server.schema.SchemaConstants;
-import org.opends.server.tools.LDAPSearch;
+import com.forgerock.opendj.ldap.tools.LDAPSearch;
import org.opends.server.types.AuthenticationInfo;
import org.forgerock.opendj.ldap.DN;
import org.opends.server.types.Entry;
@@ -38,6 +38,7 @@
import org.testng.annotations.Test;
import static org.opends.server.protocols.internal.InternalClientConnection.*;
+import static org.opends.server.types.NullOutputStream.nullPrintStream;
import static org.testng.Assert.*;
/**
@@ -379,7 +380,7 @@
SchemaConstants.NO_ATTRIBUTES
};
- assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
+ assertEquals(LDAPSearch.run(nullPrintStream(), System.err, args), 0);
}
@@ -490,7 +491,7 @@
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(LDAPSearch.run(nullPrintStream(), nullPrintStream(), args) == 0);
}
@@ -532,7 +533,7 @@
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(LDAPSearch.run(nullPrintStream(), nullPrintStream(), args) == 0);
}
@@ -574,7 +575,7 @@
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(LDAPSearch.run(nullPrintStream(), nullPrintStream(), args) == 0);
}
}
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/extensions/StartTLSExtendedOperationTestCase.java b/opendj-server-legacy/src/test/java/org/opends/server/extensions/StartTLSExtendedOperationTestCase.java
index 9b627a7..fa29cc8 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/extensions/StartTLSExtendedOperationTestCase.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/extensions/StartTLSExtendedOperationTestCase.java
@@ -12,7 +12,7 @@
* information: "Portions Copyright [year] [name of copyright owner]".
*
* Copyright 2006-2008 Sun Microsystems, Inc.
- * Portions Copyright 2014-2015 ForgeRock AS.
+ * Portions Copyright 2014-2016 ForgeRock AS.
*/
package org.opends.server.extensions;
@@ -20,10 +20,12 @@
import org.opends.server.TestCaseUtils;
import org.opends.server.core.DirectoryServer;
-import org.opends.server.tools.LDAPSearch;
+import com.forgerock.opendj.ldap.tools.LDAPSearch;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
+import static org.opends.server.TestCaseUtils.runLdapSearchTrustCertificateForSession;
+import static org.opends.server.types.NullOutputStream.nullPrintStream;
import static org.testng.Assert.*;
/**
@@ -69,7 +71,7 @@
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
+ assertEquals(runLdapSearchTrustCertificateForSession(args), 0);
}
@@ -93,7 +95,7 @@
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
+ assertEquals(LDAPSearch.run(nullPrintStream(), System.err, args), 0);
}
@@ -123,7 +125,7 @@
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
+ assertEquals(runLdapSearchTrustCertificateForSession(args), 0);
}
@@ -149,7 +151,7 @@
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
+ assertEquals(LDAPSearch.run(nullPrintStream(), System.err, args), 0);
}
@@ -190,17 +192,16 @@
"-K", keyStorePath,
"-W", "password",
"-P", trustStorePath,
- "-r",
+ "-o", "mech=EXTERNAL",
+ "-N", "client-cert",
"-b", "",
"-s", "base",
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
+ assertEquals(runLdapSearchTrustCertificateForSession(args), 0);
}
-
-
/**
* Tests the use of the StartTLS extended operation to communicate with the
* server in conjunction with SASL EXTERNAL authentication and using blind
@@ -236,13 +237,14 @@
"-K", keyStorePath,
"-W", "password",
"-X",
- "-r",
+ "-o", "mech=EXTERNAL",
+ "-N", "client-cert",
"-b", "",
"-s", "base",
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
+ assertEquals(LDAPSearch.run(nullPrintStream(), System.err, args), 0);
}
}
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/extensions/SubjectAttributeToUserAttributeCertificateMapperTestCase.java b/opendj-server-legacy/src/test/java/org/opends/server/extensions/SubjectAttributeToUserAttributeCertificateMapperTestCase.java
index 877c905..853ba32 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/extensions/SubjectAttributeToUserAttributeCertificateMapperTestCase.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/extensions/SubjectAttributeToUserAttributeCertificateMapperTestCase.java
@@ -19,7 +19,9 @@
import static org.forgerock.opendj.ldap.ModificationType.*;
import static org.forgerock.opendj.ldap.requests.Requests.*;
+import static org.opends.server.TestCaseUtils.runLdapSearchTrustCertificateForSession;
import static org.opends.server.protocols.internal.InternalClientConnection.*;
+import static org.opends.server.types.NullOutputStream.nullPrintStream;
import static org.testng.Assert.*;
import java.io.File;
@@ -32,7 +34,6 @@
import org.forgerock.opendj.server.config.meta.SubjectAttributeToUserAttributeCertificateMapperCfgDefn;
import org.opends.server.core.DirectoryServer;
import org.opends.server.core.ModifyOperation;
-import org.opends.server.tools.LDAPSearch;
import org.opends.server.types.DirectoryException;
import org.opends.server.types.Entry;
import org.opends.server.types.InitializationException;
@@ -223,13 +224,14 @@
"-K", getKeyStorePath("client.keystore"),
"-W", "password",
"-P", getTrustStorePath(),
- "-r",
+ "-o", "mech=EXTERNAL",
+ "-N", "client-cert",
"-b", "",
"-s", "base",
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
+ assertEquals(runLdapSearchTrustCertificateForSession(args), 0);
}
finally
{
@@ -277,13 +279,14 @@
"-K", getKeyStorePath("client-emailAddress.keystore"),
"-W", "password",
"-P", getTrustStorePath(),
- "-r",
+ "-o", "mech=EXTERNAL",
+ "-N", "client-cert",
"-b", "",
"-s", "base",
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
+ assertEquals(runLdapSearchTrustCertificateForSession(args), 0);
}
finally
{
@@ -331,13 +334,14 @@
"-K", getKeyStorePath("client-emailAddress.keystore"),
"-W", "password",
"-P", getTrustStorePath(),
- "-r",
+ "-o", "mech=EXTERNAL",
+ "-N", "client-cert",
"-b", "",
"-s", "base",
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
+ assertEquals(runLdapSearchTrustCertificateForSession(args), 0);
}
finally
{
@@ -393,13 +397,14 @@
"-K", getKeyStorePath("client.keystore"),
"-W", "password",
"-P", getTrustStorePath(),
- "-r",
+ "-o", "mech=EXTERNAL",
+ "-N", "client-cert",
"-b", "",
"-s", "base",
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
+ assertEquals(runLdapSearchTrustCertificateForSession(args), 0);
}
finally
{
@@ -448,13 +453,14 @@
"-K", getKeyStorePath("client.keystore"),
"-W", "password",
"-P", getTrustStorePath(),
- "-r",
+ "-o", "mech=EXTERNAL",
+ "-N", "client-cert",
"-b", "",
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, System.err) == 0);
+ assertFalse(runLdapSearchTrustCertificateForSession(args) == 0);
}
finally
{
@@ -500,13 +506,14 @@
"-K", getKeyStorePath("client.keystore"),
"-W", "password",
"-P", getTrustStorePath(),
- "-r",
+ "-o", "mech=EXTERNAL",
+ "-N", "client-cert",
"-b", "",
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(runLdapSearchTrustCertificateForSession(nullPrintStream(), nullPrintStream(), args) == 0);
}
finally
{
@@ -562,13 +569,14 @@
"-K", getKeyStorePath("client.keystore"),
"-W", "password",
"-P", getTrustStorePath(),
- "-r",
+ "-o", "mech=EXTERNAL",
+ "-N", "client-cert",
"-b", "",
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(runLdapSearchTrustCertificateForSession(nullPrintStream(), nullPrintStream(), args) == 0);
}
finally
{
@@ -616,13 +624,14 @@
"-K", getKeyStorePath("client.keystore"),
"-W", "password",
"-P", getTrustStorePath(),
- "-r",
+ "-o", "mech=EXTERNAL",
+ "-N", "client-cert",
"-b", "",
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(runLdapSearchTrustCertificateForSession(nullPrintStream(), nullPrintStream(), args) == 0);
}
finally
{
@@ -852,13 +861,14 @@
"-K", getKeyStorePath("client.keystore"),
"-W", "password",
"-P", getTrustStorePath(),
- "-r",
+ "-o", "mech=EXTERNAL",
+ "-N","client-cert",
"-b", "cn=config",
"-s", "sub",
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
+ assertEquals(runLdapSearchTrustCertificateForSession(args), 0);
}
finally
{
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/extensions/SubjectDNToUserAttributeCertificateMapperTestCase.java b/opendj-server-legacy/src/test/java/org/opends/server/extensions/SubjectDNToUserAttributeCertificateMapperTestCase.java
index 109484b..cfcc16e 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/extensions/SubjectDNToUserAttributeCertificateMapperTestCase.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/extensions/SubjectDNToUserAttributeCertificateMapperTestCase.java
@@ -18,7 +18,9 @@
import static org.forgerock.opendj.ldap.ModificationType.*;
import static org.forgerock.opendj.ldap.requests.Requests.*;
+import static org.opends.server.TestCaseUtils.runLdapSearchTrustCertificateForSession;
import static org.opends.server.protocols.internal.InternalClientConnection.*;
+import static org.opends.server.types.NullOutputStream.nullPrintStream;
import static org.testng.Assert.*;
import java.io.File;
@@ -31,7 +33,6 @@
import org.opends.server.TestCaseUtils;
import org.opends.server.core.DirectoryServer;
import org.opends.server.core.ModifyOperation;
-import org.opends.server.tools.LDAPSearch;
import org.opends.server.types.DirectoryException;
import org.opends.server.types.Entry;
import org.opends.server.types.InitializationException;
@@ -173,13 +174,14 @@
"-K", keyStorePath,
"-W", "password",
"-P", trustStorePath,
- "-r",
+ "-o", "mech=EXTERNAL",
+ "-N", "client-cert",
"-b", "",
"-s", "base",
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
+ assertEquals(runLdapSearchTrustCertificateForSession(args), 0);
}
finally
{
@@ -235,13 +237,14 @@
"-K", keyStorePath,
"-W", "password",
"-P", trustStorePath,
- "-r",
+ "-o", "mech=EXTERNAL",
+ "-N", "client-cert",
"-b", "",
"-s", "base",
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
+ assertEquals(runLdapSearchTrustCertificateForSession(args), 0);
}
finally
{
@@ -298,13 +301,14 @@
"-K", keyStorePath,
"-W", "password",
"-P", trustStorePath,
- "-r",
+ "-o", "mech=EXTERNAL",
+ "-N", "client-cert",
"-b", "",
"-s", "base",
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
+ assertEquals(runLdapSearchTrustCertificateForSession(args), 0);
}
finally
{
@@ -357,13 +361,14 @@
"-K", keyStorePath,
"-W", "password",
"-P", trustStorePath,
- "-r",
+ "-o", "mech=EXTERNAL",
+ "-N", "client-cert",
"-b", "",
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(runLdapSearchTrustCertificateForSession(args) == 0);
}
finally
{
@@ -429,13 +434,14 @@
"-K", keyStorePath,
"-W", "password",
"-P", trustStorePath,
- "-r",
+ "-o", "mech=EXTERNAL",
+ "-N", "client-cert",
"-b", "",
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(runLdapSearchTrustCertificateForSession(args) == 0);
}
finally
{
@@ -491,13 +497,14 @@
"-K", keyStorePath,
"-W", "password",
"-P", trustStorePath,
- "-r",
+ "-o", "mech=EXTERNAL",
+ "-N", "client-cert",
"-b", "",
"-s", "base",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(runLdapSearchTrustCertificateForSession(nullPrintStream(), nullPrintStream(), args) == 0);
}
finally
{
@@ -670,13 +677,14 @@
"-K", keyStorePath,
"-W", "password",
"-P", trustStorePath,
- "-r",
+ "-o", "mech=EXTERNAL",
+ "-N", "client-cert",
"-b", "cn=config",
"-s", "sub",
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
+ assertEquals(runLdapSearchTrustCertificateForSession(args), 0);
}
finally
{
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/extensions/TraditionalWorkQueueTestCase.java b/opendj-server-legacy/src/test/java/org/opends/server/extensions/TraditionalWorkQueueTestCase.java
index 63a4599..7b5ae31 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/extensions/TraditionalWorkQueueTestCase.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/extensions/TraditionalWorkQueueTestCase.java
@@ -29,7 +29,7 @@
import org.opends.server.protocols.internal.InternalSearchOperation;
import org.opends.server.protocols.internal.SearchRequest;
import org.opends.server.schema.SchemaConstants;
-import org.opends.server.tools.LDAPSearch;
+import com.forgerock.opendj.ldap.tools.LDAPSearch;
import org.opends.server.types.Attributes;
import org.forgerock.opendj.ldap.DN;
import org.opends.server.types.Modification;
@@ -39,6 +39,7 @@
import static org.forgerock.opendj.ldap.ModificationType.*;
import static org.opends.server.protocols.internal.InternalClientConnection.*;
import static org.opends.server.protocols.internal.Requests.*;
+import static org.opends.server.types.NullOutputStream.nullPrintStream;
import static org.opends.server.util.CollectionUtils.*;
import static org.testng.Assert.*;
@@ -112,7 +113,7 @@
for (int i=0; i < 7; i++)
{
- assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
+ assertEquals(LDAPSearch.run(nullPrintStream(), System.err, args), 0);
}
}
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/extensions/UserDefinedVirtualAttributeProviderTestCase.java b/opendj-server-legacy/src/test/java/org/opends/server/extensions/UserDefinedVirtualAttributeProviderTestCase.java
index c52378e..983bef9 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/extensions/UserDefinedVirtualAttributeProviderTestCase.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/extensions/UserDefinedVirtualAttributeProviderTestCase.java
@@ -31,7 +31,7 @@
import org.opends.server.protocols.internal.InternalSearchOperation;
import org.opends.server.protocols.internal.Requests;
import org.opends.server.protocols.internal.SearchRequest;
-import org.opends.server.tools.LDAPModify;
+import com.forgerock.opendj.ldap.tools.LDAPModify;
import org.opends.server.types.Attribute;
import org.opends.server.types.VirtualAttributeRule;
import org.testng.annotations.BeforeClass;
@@ -39,6 +39,7 @@
import static org.opends.server.protocols.internal.InternalClientConnection.*;
import static org.opends.server.protocols.internal.Requests.*;
+import static org.opends.server.types.NullOutputStream.nullPrintStream;
import static org.testng.Assert.*;
/**
@@ -663,7 +664,7 @@
String.valueOf(TestCaseUtils.getServerLdapPort()), "-D",
"cn=Directory Manager", "-w", "password", "-f", path1 };
- assertFalse(LDAPModify.mainModify(args1, false, null, null) == 0);
+ assertFalse(LDAPModify.run(nullPrintStream(), nullPrintStream(), args1) == 0);
String path2 =
TestCaseUtils.createTempFile("dn: " + ruleDN,
@@ -676,8 +677,8 @@
"-X", "-D", "cn=Directory Manager", "-w", "password",
"-f", path2 };
- assertEquals(LDAPModify.mainModify(args2, false, null, null), 0);
- assertEquals(LDAPModify.mainModify(args1, false, null, null), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), nullPrintStream(), args2), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), nullPrintStream(), args1), 0);
}
finally
{
@@ -780,7 +781,7 @@
String.valueOf(TestCaseUtils.getServerLdapPort()), "-D",
userDN, "-w", "password", "-f", path1 };
- assertFalse(LDAPModify.mainModify(args1, false, null, null) == 0);
+ assertFalse(LDAPModify.run(nullPrintStream(), nullPrintStream(), args1) == 0);
String path2 =
TestCaseUtils.createTempFile("dn: " + ruleDN,
@@ -793,8 +794,8 @@
"-X", "-D", "cn=Directory Manager", "-w", "password",
"-f", path2 };
- assertEquals(LDAPModify.mainModify(args2, false, null, null), 0);
- assertEquals(LDAPModify.mainModify(args1, false, null, null), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), nullPrintStream(), args2), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), nullPrintStream(), args1), 0);
}
finally
{
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/plugins/SevenBitCleanPluginTestCase.java b/opendj-server-legacy/src/test/java/org/opends/server/plugins/SevenBitCleanPluginTestCase.java
index ce84020..eada160 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/plugins/SevenBitCleanPluginTestCase.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/plugins/SevenBitCleanPluginTestCase.java
@@ -12,7 +12,7 @@
* information: "Portions Copyright [year] [name of copyright owner]".
*
* Copyright 2008 Sun Microsystems, Inc.
- * Portions Copyright 2014-2015 ForgeRock AS.
+ * Portions Copyright 2014-2016 ForgeRock AS.
*/
package org.opends.server.plugins;
@@ -23,7 +23,7 @@
import org.opends.server.TestCaseUtils;
import org.forgerock.opendj.ldap.ResultCode;
-import org.opends.server.tools.LDAPModify;
+import com.forgerock.opendj.ldap.tools.LDAPModify;
import static org.testng.Assert.*;
@@ -93,7 +93,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, System.out, System.err), 0);
+ assertEquals(LDAPModify.run(System.out, System.err, args), 0);
}
@@ -133,7 +133,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, System.out, System.err), 0);
+ assertEquals(LDAPModify.run(System.out, System.err, args), 0);
}
@@ -180,8 +180,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, System.out, System.err),
- 0);
+ assertEquals(LDAPModify.run(System.out, System.err, args), 0);
}
finally
{
@@ -236,8 +235,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, System.out, System.err),
- ResultCode.CONSTRAINT_VIOLATION.intValue());
+ assertEquals(LDAPModify.run(System.out, System.err, args), ResultCode.CONSTRAINT_VIOLATION.intValue());
}
finally
{
@@ -294,8 +292,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, System.out, System.err),
- 0);
+ assertEquals(LDAPModify.run(System.out, System.err, args), 0);
}
finally
{
@@ -349,7 +346,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, System.out, System.err), 0);
+ assertEquals(LDAPModify.run(System.out, System.err, args), 0);
}
@@ -401,8 +398,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, System.out, System.err),
- ResultCode.CONSTRAINT_VIOLATION.intValue());
+ assertEquals(LDAPModify.run(System.out, System.err, args), ResultCode.CONSTRAINT_VIOLATION.intValue());
}
finally
{
@@ -462,8 +458,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, System.out, System.err),
- 0);
+ assertEquals(LDAPModify.run(System.out, System.err, args), 0);
}
finally
{
@@ -523,8 +518,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, System.out, System.err),
- 0);
+ assertEquals(LDAPModify.run(System.out, System.err, args), 0);
}
finally
{
@@ -577,7 +571,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, System.out, System.err), 0);
+ assertEquals(LDAPModify.run(System.out, System.err, args), 0);
}
@@ -629,8 +623,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, System.out, System.err),
- ResultCode.CONSTRAINT_VIOLATION.intValue());
+ assertEquals(LDAPModify.run(System.out, System.err, args), ResultCode.CONSTRAINT_VIOLATION.intValue());
}
finally
{
@@ -690,8 +683,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, System.out, System.err),
- 0);
+ assertEquals(LDAPModify.run(System.out, System.err, args), 0);
}
finally
{
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/protocols/ldap/LDAPBinaryOptionTestCase.java b/opendj-server-legacy/src/test/java/org/opends/server/protocols/ldap/LDAPBinaryOptionTestCase.java
index 839377d..a5fa075 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/protocols/ldap/LDAPBinaryOptionTestCase.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/protocols/ldap/LDAPBinaryOptionTestCase.java
@@ -20,6 +20,7 @@
import static org.forgerock.opendj.ldap.SearchScope.*;
import static org.opends.server.protocols.internal.InternalClientConnection.*;
import static org.opends.server.protocols.internal.Requests.*;
+import static org.opends.server.types.NullOutputStream.nullPrintStream;
import static org.testng.Assert.*;
import java.io.BufferedReader;
@@ -28,6 +29,7 @@
import java.io.IOException;
import java.util.List;
+import org.forgerock.opendj.ldap.Base64;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.ResultCode;
import org.forgerock.opendj.ldap.SearchScope;
@@ -38,8 +40,8 @@
import org.opends.server.core.DirectoryServer;
import org.opends.server.protocols.internal.InternalSearchOperation;
import org.opends.server.protocols.internal.SearchRequest;
-import org.opends.server.tools.LDAPModify;
-import org.opends.server.tools.LDAPSearch;
+import com.forgerock.opendj.ldap.tools.LDAPModify;
+import com.forgerock.opendj.ldap.tools.LDAPSearch;
import org.opends.server.tools.RemoteConnection;
import org.opends.server.types.Attribute;
import org.opends.server.types.ExistingFileBehavior;
@@ -47,7 +49,6 @@
import org.opends.server.types.LDIFExportConfig;
import org.opends.server.types.LDIFImportConfig;
import org.opends.server.types.SearchResultEntry;
-import org.opends.server.util.Base64;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
@@ -121,10 +122,9 @@
"-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
"-D","cn=directory manager",
"-w","password",
- "-a",
"-f", filePath
};
- int err = LDAPModify.mainModify(args, false, null,null);
+ int err = LDAPModify.run(nullPrintStream(), nullPrintStream(), args);
assertEquals(err,0);
//ADD with ;binary option.
@@ -142,10 +142,9 @@
"-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
"-D","cn=directory manager",
"-w","password",
- "-a",
"-f", filePath
};
- err = LDAPModify.mainModify(args, false, null,null);
+ err = LDAPModify.run(nullPrintStream(), nullPrintStream(), args);
assertEquals(err,0);
}
@@ -173,10 +172,9 @@
"-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
"-D","cn=directory manager",
"-w","password",
- "-a",
"-f", filePath,
};
- int err = LDAPModify.mainModify(args, false, null,null);
+ int err = LDAPModify.run(nullPrintStream(), nullPrintStream(), args);
assertThat(err).isNotEqualTo(0);
}
@@ -243,7 +241,7 @@
.addAttribute("sn", "sn#1")
.addAttribute("sn;x-foo", "sn#2")
.addAttribute("sn;lang-fr", "sn#3")
- .addAttribute("userCertificate;binary", ByteString.wrap(Base64.decode(CERT)));
+ .addAttribute("userCertificate;binary", ByteString.wrap(Base64.decode(CERT).toByteArray()));
LDAPMessage message = conn.add(addRequest);
AddResponseProtocolOp addResponse = message.getAddResponseProtocolOp();
assertEquals(addResponse.getResultCode(),0);
@@ -302,7 +300,7 @@
"-b", "o=test",
"(uid=user.1)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
+ assertEquals(LDAPSearch.run(nullPrintStream(), System.err, args), 0);
exportBackend();
assertTrue(ldif.exists());
assertTrue(containsBinary());
@@ -380,10 +378,9 @@
"-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
"-D","cn=directory manager",
"-w","password",
- "-a",
"-f", filePath,
};
- int err = LDAPModify.mainModify(args, false, null,null);
+ int err = LDAPModify.run(nullPrintStream(), nullPrintStream(), args);
assertEquals(err,0);
filePath = TestCaseUtils.createTempFile(
@@ -399,7 +396,7 @@
"-w","password",
"-f", filePath,
};
- err = LDAPModify.mainModify(args, false, null,null);
+ err = LDAPModify.run(nullPrintStream(), nullPrintStream(), args);
assertEquals(err,0);
}
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/protocols/ldap/TestAddRequestProtocolOp.java b/opendj-server-legacy/src/test/java/org/opends/server/protocols/ldap/TestAddRequestProtocolOp.java
index 5d28dfa..b88bac5 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/protocols/ldap/TestAddRequestProtocolOp.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/protocols/ldap/TestAddRequestProtocolOp.java
@@ -12,7 +12,7 @@
* information: "Portions Copyright [year] [name of copyright owner]".
*
* Copyright 2006-2008 Sun Microsystems, Inc.
- * Portions Copyright 2013-2015 ForgeRock AS.
+ * Portions Copyright 2013-2016 ForgeRock AS.
*/
package org.opends.server.protocols.ldap;
@@ -27,11 +27,11 @@
import org.forgerock.opendj.io.ASN1;
import org.forgerock.opendj.io.ASN1Reader;
import org.forgerock.opendj.io.ASN1Writer;
+import org.forgerock.opendj.ldap.Base64;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.ByteStringBuilder;
import org.opends.server.types.LDAPException;
import org.opends.server.types.RawAttribute;
-import org.opends.server.util.Base64;
import org.testng.annotations.Test;
/**
@@ -363,7 +363,7 @@
BufferedReader reader =
new BufferedReader(new StringReader(buffer.toString()));
String line = reader.readLine();
- assertEquals(line, "dn:: "+Base64.encode(dnNeedsBase64));
+ assertEquals(line, "dn:: "+ Base64.encode(dnNeedsBase64));
for (int i = 0; i < numAttributes; i++)
{
for (int j = 0; j < numValues; j++)
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/replication/ChangeNumberControlPluginTestCase.java b/opendj-server-legacy/src/test/java/org/opends/server/replication/ChangeNumberControlPluginTestCase.java
index 83085ac..66cdf0c 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/replication/ChangeNumberControlPluginTestCase.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/replication/ChangeNumberControlPluginTestCase.java
@@ -16,19 +16,23 @@
*/
package org.opends.server.replication;
-import java.io.BufferedReader;
-import java.io.FileOutputStream;
-import java.io.FileReader;
+import org.forgerock.opendj.ldap.ByteString;
+import org.forgerock.opendj.ldap.Connection;
+import org.forgerock.opendj.ldap.LDAPConnectionFactory;
+import org.forgerock.opendj.ldap.controls.Control;
+import org.forgerock.opendj.ldap.requests.AddRequest;
+import org.forgerock.opendj.ldap.requests.DeleteRequest;
+import org.forgerock.opendj.ldap.requests.ModifyDNRequest;
+import org.forgerock.opendj.ldap.requests.ModifyRequest;
+import org.forgerock.opendj.ldap.requests.Requests;
+import org.forgerock.opendj.ldap.responses.Result;
+import org.forgerock.util.promise.ResultHandler;
import org.opends.server.TestCaseUtils;
-import org.opends.server.tools.LDAPModify;
import org.forgerock.opendj.ldap.DN;
-import org.opends.server.util.StaticUtils;
import org.testng.annotations.BeforeClass;
-import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
-import static org.opends.messages.ToolMessages.*;
import static org.opends.server.TestCaseUtils.*;
import static org.opends.server.util.ServerConstants.*;
import static org.testng.Assert.*;
@@ -37,10 +41,43 @@
public class ChangeNumberControlPluginTestCase extends ReplicationTestCase
{
- /**
- * The port of the replicationServer.
- */
- private int replServerPort;
+ private static final String HOSTNAME = "127.0.0.1";
+
+ private static final Control CSN_CONTROL = new Control()
+ {
+ @Override
+ public String getOID()
+ {
+ return OID_CSN_CONTROL;
+ }
+
+ @Override
+ public ByteString getValue()
+ {
+ return null;
+ }
+
+ @Override
+ public boolean hasValue()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean isCritical()
+ {
+ return false;
+ }
+ };
+
+ private static final ResultHandler<Result> ASSERTION_RESULT_HANDLER = new ResultHandler<Result>()
+ {
+ @Override
+ public void handleResult(final Result result)
+ {
+ assertTrue(result.containsControl(CSN_CONTROL.getOID()));
+ }
+ };
/**
* The replicationServer that will be used in this test.
@@ -58,8 +95,7 @@
super.setUp();
baseDn = DN.valueOf(TEST_ROOT_DN_STRING);
-
- replServerPort = TestCaseUtils.findFreePort();
+ final int replServerPort = TestCaseUtils.findFreePort();
// replication server
String replServerLdif =
@@ -86,79 +122,61 @@
configureReplication(replServerLdif, synchroServerLdif);
}
- @DataProvider(name = "operations")
- public Object[][] createLdapRequests() {
- return new Object[][] {
- new Object[] {
- "dn: cn=user1," + baseDn + "\n"
- + "changetype: add" + "\n"
- + "objectClass: person" + "\n"
- + "cn: user1" + "\n"
- + "sn: User Test 10"},
- new Object[] {
- "dn: cn=user1," + baseDn + "\n"
- + "changetype: modify" + "\n"
- + "add: description" + "\n"
- + "description: blah"},
- new Object[] {
- "dn: cn=user1," + baseDn + "\n"
- + "changetype: moddn" + "\n"
- + "newrdn: cn=user111" + "\n"
- + "deleteoldrdn: 1"},
- new Object[] {
- "dn: cn=user111," + baseDn + "\n"
- + "changetype: delete"}
- };
- }
-
- @Test(dataProvider="operations")
- public void ChangeNumberControlTest(String request) throws Exception {
-
- String path = TestCaseUtils.createTempFile(request);
-
- String[] args =
+ @Test
+ public void changeNumberControlAddRequestTest() throws Exception {
+ try (final LDAPConnectionFactory factory = new LDAPConnectionFactory(HOSTNAME, getServerLdapPort());
+ final Connection connection = factory.getConnection())
{
- "-h", "127.0.0.1",
- "-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
- "-D", "cn=Directory Manager",
- "-w", "password",
- "-J", OID_CSN_CONTROL + ":false",
- "--noPropertiesFile",
- "-f", path
- };
-
- String resultPath = TestCaseUtils.createTempFile();
-
- FileOutputStream fos = new FileOutputStream(resultPath);
-
- assertEquals(LDAPModify.mainModify(args, false, fos, System.err), 0);
- //fos.flush();
- fos.close();
-
- assertTrue(isCsnLinePresent(resultPath));
- }
-
- private boolean isCsnLinePresent(String file) throws Exception {
- FileReader fr = new FileReader(file);
- try
- {
- BufferedReader br = new BufferedReader(fr);
- String line = null;
- boolean found = false;
- while ((line = br.readLine()) != null)
- {
- if (line.contains(INFO_CHANGE_NUMBER_CONTROL_RESULT.get("%s", "%s")
- .toString().split("%s")[1]))
- {
- found = true;
- }
- }
- return found;
- }
- finally
- {
- StaticUtils.close(fr);
+ final AddRequest addRequest = Requests.newAddRequest("dn: cn=user1," + baseDn,
+ "changetype: add",
+ "objectClass: person",
+ "cn: user1",
+ "sn: User Test 10")
+ .addControl(CSN_CONTROL);
+ connection.addAsync(addRequest)
+ .thenOnResult(ASSERTION_RESULT_HANDLER);
}
}
+ @Test
+ public void changeNumberControlDeleteRequestTest() throws Exception
+ {
+ try (final LDAPConnectionFactory factory = new LDAPConnectionFactory(HOSTNAME, getServerLdapPort());
+ final Connection connection = factory.getConnection())
+ {
+ final DeleteRequest deleteRequest = Requests.newDeleteRequest("cn=user111," + baseDn)
+ .addControl(CSN_CONTROL);
+ connection.deleteAsync(deleteRequest)
+ .thenOnResult(ASSERTION_RESULT_HANDLER);
+ }
+ }
+
+ @Test
+ public void changeNumberControlModifyRequestTest() throws Exception
+ {
+ try (final LDAPConnectionFactory factory = new LDAPConnectionFactory(HOSTNAME, getServerLdapPort());
+ final Connection connection = factory.getConnection())
+ {
+ final ModifyRequest modifyRequest = Requests.newModifyRequest("dn: cn=user1," + baseDn,
+ "changetype: modify",
+ "add: description",
+ "description: blah")
+ .addControl(CSN_CONTROL);
+ connection.modifyAsync(modifyRequest).thenOnResult(ASSERTION_RESULT_HANDLER);
+ }
+ }
+
+ @Test
+ public void changeNumberControlModifyDNRequestTest() throws Exception
+ {
+ try (final LDAPConnectionFactory factory = new LDAPConnectionFactory(HOSTNAME, getServerLdapPort());
+ final Connection connection = factory.getConnection())
+ {
+ final ModifyDNRequest modifyDNRequest = Requests.newModifyDNRequest("cn=user.1" + baseDn, "cn=user.111")
+ .addControl(CSN_CONTROL)
+ .setDeleteOldRDN(true);
+ connection.modifyDNAsync(modifyDNRequest)
+ .thenOnResult(ASSERTION_RESULT_HANDLER);
+ }
+ }
}
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/replication/InitOnLineTest.java b/opendj-server-legacy/src/test/java/org/opends/server/replication/InitOnLineTest.java
index 3359378..d1a5c00 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/replication/InitOnLineTest.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/replication/InitOnLineTest.java
@@ -25,6 +25,7 @@
import org.assertj.core.api.Assertions;
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.i18n.slf4j.LocalizedLogger;
+import org.forgerock.opendj.ldap.Base64;
import org.forgerock.opendj.ldap.DN;
import org.forgerock.opendj.ldap.ResultCode;
import org.forgerock.opendj.ldap.SearchScope;
@@ -49,7 +50,6 @@
import org.opends.server.replication.service.ReplicationBroker;
import org.opends.server.types.DirectoryException;
import org.opends.server.types.Entry;
-import org.opends.server.util.Base64;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
@@ -351,8 +351,7 @@
+ "cn: "+useri+"_cn"+"\n"
+ "sn: "+useri+"_sn"+"\n"
+ "uid: "+useri+"_uid"+"\n"
- + "description:: "+ Base64.encode(
- new String(bigAttributeValue).getBytes())+"\n"
+ + "description:: "+ Base64.encode(new String(bigAttributeValue).getBytes()) +"\n"
+ "entryUUID: 21111111-1111-1111-1111-"+useri+
filler.substring(0, 12-useri.length())+"\n"
+ "\n";
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/HistoricalTest.java b/opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/HistoricalTest.java
index f83379c..28671bc 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/HistoricalTest.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/HistoricalTest.java
@@ -22,6 +22,7 @@
import static org.forgerock.opendj.ldap.SearchScope.*;
import static org.forgerock.opendj.ldap.schema.CoreSchema.*;
import static org.opends.server.TestCaseUtils.*;
+import static org.opends.server.types.NullOutputStream.nullPrintStream;
import static org.opends.server.util.CollectionUtils.*;
import static org.testng.Assert.*;
@@ -43,7 +44,7 @@
import org.opends.server.replication.protocol.LDAPUpdateMsg;
import org.opends.server.replication.protocol.ModifyMsg;
import org.opends.server.replication.service.ReplicationBroker;
-import org.opends.server.tools.LDAPModify;
+import com.forgerock.opendj.ldap.tools.LDAPModify;
import org.opends.server.types.Attribute;
import org.opends.server.types.Attributes;
import org.opends.server.types.DirectoryException;
@@ -614,6 +615,6 @@
private void ldapmodify(String[] args)
{
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
}
}
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/ReplicationRepairControlTest.java b/opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/ReplicationRepairControlTest.java
index 8931eeb..c338df8 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/ReplicationRepairControlTest.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/replication/plugin/ReplicationRepairControlTest.java
@@ -12,14 +12,16 @@
* information: "Portions Copyright [year] [name of copyright owner]".
*
* Copyright 2008-2010 Sun Microsystems, Inc.
- * Portions Copyright 2015 ForgeRock AS.
+ * Portions Copyright 2015-2016 ForgeRock AS.
*/
package org.opends.server.replication.plugin;
import org.opends.server.TestCaseUtils;
import org.opends.server.replication.ReplicationTestCase;
-import org.opends.server.tools.LDAPModify;
+import com.forgerock.opendj.ldap.tools.LDAPModify;
import org.testng.annotations.Test;
+
+import static org.opends.server.types.NullOutputStream.nullPrintStream;
import static org.testng.Assert.*;
import static org.opends.server.TestCaseUtils.*;
@@ -53,11 +55,10 @@
"-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
"-D", "cn=Directory Manager",
"-w", "password",
- "-a",
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, null, null), 53);
+ assertEquals(LDAPModify.run(nullPrintStream(), nullPrintStream(), args), 53);
// Test that we can't add an entry with the ds-sync-hist attribute
// without specifying the replication repair control.
@@ -81,12 +82,11 @@
"-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
"-D", "cn=Directory Manager",
"-w", "password",
- "-a",
"-f", path1
};
- assertEquals(LDAPModify.mainModify(args1, false, null, null), 53);
+ assertEquals(LDAPModify.run(nullPrintStream(), nullPrintStream(), args1), 53);
// Now Test specifying the replication repair control makes
// possible to add an entry with the entryuuid and ds-sync-hist attributes
@@ -113,10 +113,9 @@
"-D", "cn=Directory Manager",
"-w", "password",
"-J", "1.3.6.1.4.1.26027.1.5.2",
- "-a",
"-f", path2
};
- assertEquals(LDAPModify.mainModify(args2, false, null, null), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), nullPrintStream(), args2), 0);
}
}
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/replication/server/MonitorTest.java b/opendj-server-legacy/src/test/java/org/opends/server/replication/server/MonitorTest.java
index 80dc3e9..0ee006a 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/replication/server/MonitorTest.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/replication/server/MonitorTest.java
@@ -20,6 +20,7 @@
import static org.testng.Assert.*;
import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
import java.net.SocketException;
import java.util.Arrays;
import java.util.SortedSet;
@@ -39,7 +40,7 @@
import org.opends.server.replication.server.changelog.file.ECLEnabledDomainPredicate;
import org.opends.server.replication.service.DSRSShutdownSync;
import org.opends.server.replication.service.ReplicationBroker;
-import org.opends.server.tools.LDAPSearch;
+import com.forgerock.opendj.ldap.tools.LDAPSearch;
import org.opends.server.types.Entry;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
@@ -429,8 +430,7 @@
oStream.reset();
eStream.reset();
- int retVal =
- LDAPSearch.mainSearch(args3, false, oStream, eStream);
+ int retVal = LDAPSearch.run(new PrintStream(oStream), new PrintStream(eStream), args3);
String entries = oStream.toString();
debugInfo("Entries:" + entries);
assertEquals(retVal, 0, "Returned error: " + eStream);
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/schema/CollationMatchingRuleTest.java b/opendj-server-legacy/src/test/java/org/opends/server/schema/CollationMatchingRuleTest.java
index 38548d9..da04750 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/schema/CollationMatchingRuleTest.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/schema/CollationMatchingRuleTest.java
@@ -27,7 +27,7 @@
import org.opends.server.controls.VLVRequestControl;
import org.opends.server.protocols.internal.InternalSearchOperation;
import org.opends.server.protocols.internal.SearchRequest;
-import org.opends.server.tools.LDAPModify;
+import com.forgerock.opendj.ldap.tools.LDAPModify;
import org.opends.server.types.Control;
import org.opends.server.types.Entry;
import org.opends.server.types.LDAPException;
@@ -41,6 +41,7 @@
import static org.forgerock.opendj.ldap.SearchScope.*;
import static org.opends.server.protocols.internal.InternalClientConnection.*;
import static org.opends.server.protocols.internal.Requests.*;
+import static org.opends.server.types.NullOutputStream.nullPrintStream;
import static org.testng.Assert.*;
/** Integration tests for collation matching rules. */
@@ -89,10 +90,9 @@
"-p", String.valueOf(TestCaseUtils.getServerLdapPort()),
"-D","cn=directory manager",
"-w","password",
- "-a",
"-f", filePath,
};
- int err = LDAPModify.mainModify(args, false, null,null);
+ int err = LDAPModify.run(nullPrintStream(), nullPrintStream(), args);
assertEquals(err,0);
}
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/tasks/AllowedTaskTestCase.java b/opendj-server-legacy/src/test/java/org/opends/server/tasks/AllowedTaskTestCase.java
index cc5d725..d52651a 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/tasks/AllowedTaskTestCase.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/tasks/AllowedTaskTestCase.java
@@ -21,7 +21,7 @@
import org.opends.server.TestCaseUtils;
import org.opends.server.protocols.ldap.LDAPResultCode;
-import org.opends.server.tools.LDAPModify;
+import com.forgerock.opendj.ldap.tools.LDAPModify;
import org.forgerock.opendj.ldap.DN;
import static org.testng.Assert.*;
@@ -76,8 +76,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, System.out, System.err),
- LDAPResultCode.UNWILLING_TO_PERFORM);
+ assertEquals(LDAPModify.run(System.out, System.err, args), LDAPResultCode.UNWILLING_TO_PERFORM);
// Update the set of allowed tasks to include the dummy task.
@@ -105,8 +104,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, System.out, System.err),
- LDAPResultCode.SUCCESS);
+ assertEquals(LDAPModify.run(System.out, System.err, args), LDAPResultCode.SUCCESS);
waitTaskCompletedSuccessfully(DN.valueOf(
"ds-task-id=testAllowedTask 2,cn=Scheduled Tasks,cn=Tasks"));
@@ -138,8 +136,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, System.out, System.err),
- LDAPResultCode.UNWILLING_TO_PERFORM);
+ assertEquals(LDAPModify.run(System.out, System.err, args), LDAPResultCode.UNWILLING_TO_PERFORM);
}
}
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/tasks/LockdownModeTaskTestCase.java b/opendj-server-legacy/src/test/java/org/opends/server/tasks/LockdownModeTaskTestCase.java
index d165445..18c087a 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/tasks/LockdownModeTaskTestCase.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/tasks/LockdownModeTaskTestCase.java
@@ -24,10 +24,11 @@
import org.opends.server.TestCaseUtils;
import org.opends.server.core.DirectoryServer;
-import org.opends.server.tools.LDAPSearch;
-import org.opends.server.tools.LDAPModify;
+import com.forgerock.opendj.ldap.tools.LDAPSearch;
+import com.forgerock.opendj.ldap.tools.LDAPModify;
import org.forgerock.opendj.ldap.DN;
+import static org.opends.server.types.NullOutputStream.nullPrintStream;
import static org.testng.Assert.*;
/** Tests the enter and leave lockdown mode tasks. */
@@ -98,7 +99,7 @@
"--noPropertiesFile",
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
+ assertEquals(LDAPSearch.run(nullPrintStream(), System.err, args), 0);
// Create a file that holds the LDIF for putting the server in lockdown
@@ -126,8 +127,7 @@
"--noPropertiesFile",
"-f", taskFile
};
- assertFalse(LDAPModify.mainModify(args, false, null, System.err) == 0);
-
+ assertFalse(LDAPModify.run(nullPrintStream(), System.err, args) == 0);
// If the local address isn't a loopback address, then verify that we can't
// put the server in lockdown mode using it.
@@ -140,10 +140,10 @@
"-Z", "-X",
"-D", "cn=Directory Manager",
"-w", "password",
- "--noPropertiesFile",
+ "--noPropertiesFile",
"-f", taskFile
};
- assertFalse(LDAPModify.mainModify(args, false, null, System.err) == 0);
+ assertFalse(LDAPModify.run(nullPrintStream(), System.err, args) == 0);
}
@@ -159,7 +159,7 @@
"--noPropertiesFile",
"-f", taskFile
};
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
waitTaskCompletedSuccessfully(taskDN);
assertTrue(DirectoryServer.lockdownMode());
@@ -179,7 +179,7 @@
"--noPropertiesFile",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(LDAPSearch.run(nullPrintStream(), nullPrintStream(), args) == 0);
}
@@ -195,7 +195,7 @@
"--noPropertiesFile",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(LDAPSearch.run(nullPrintStream(), nullPrintStream(), args) == 0);
// Make sure that we can no longer retrieve the server's root DSE over an
@@ -212,7 +212,7 @@
"--noPropertiesFile",
"(objectClass=*)"
};
- assertFalse(LDAPSearch.mainSearch(args, false, null, null) == 0);
+ assertFalse(LDAPSearch.run(nullPrintStream(), nullPrintStream(), args) == 0);
// Make sure that we can retrieve the server's root DSE over a
@@ -228,7 +228,7 @@
"--noPropertiesFile",
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, null, null), 0);
+ assertEquals(LDAPSearch.run(nullPrintStream(), nullPrintStream(), args), 0);
// Use another task to take the server out of lockdown mode and make sure it
@@ -254,7 +254,7 @@
"--noPropertiesFile",
"-f", taskFile
};
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
waitTaskCompletedSuccessfully(taskDN);
assertFalse(DirectoryServer.lockdownMode());
@@ -270,7 +270,7 @@
"--noPropertiesFile",
"(objectClass=*)"
};
- assertEquals(LDAPSearch.mainSearch(args, false, null, System.err), 0);
+ assertEquals(LDAPSearch.run(nullPrintStream(), System.err, args), 0);
}
}
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/tools/ArgumentParserToolsTestCase.java b/opendj-server-legacy/src/test/java/org/opends/server/tools/ArgumentParserToolsTestCase.java
index 1b169e0..5d9dd7f 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/tools/ArgumentParserToolsTestCase.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/tools/ArgumentParserToolsTestCase.java
@@ -130,54 +130,6 @@
}
@Test(dataProvider = "invalidArgs")
- public void testLDAPCompare(final String[] args)
- {
- assertToolFailsWithUsage(LDAPCompare.mainCompare(args, false, outStream, errStream));
- }
-
- @Test(dataProvider = "invalidArg")
- public void testLDAPDelete(final String[] args)
- {
- assertToolFailsWithUsage(LDAPDelete.mainDelete(args, false, outStream, errStream));
- }
-
- @Test(dataProvider = "invalidArg")
- public void testLDAPModify(final String[] args)
- {
- assertToolFailsWithUsage(LDAPModify.mainModify(args, false, outStream, errStream));
- }
-
- @Test(dataProvider = "invalidArg")
- public void testLDAPPasswordModify(final String[] args)
- {
- assertToolFailsWithUsage(LDAPPasswordModify.mainPasswordModify(args, false, outStream, errStream));
- }
-
- @Test(dataProvider = "invalidArgs")
- public void testLDAPSearch(final String[] args)
- {
- assertToolFailsWithUsage(LDAPSearch.mainSearch(args, false, outStream, errStream));
- }
-
- @Test(dataProvider = "invalidArgs")
- public void testLDIFDiff(final String[] args)
- {
- assertToolFailsWithUsage(LDIFDiff.mainDiff(args, false, outStream, errStream));
- }
-
- @Test(dataProvider = "invalidArgs")
- public void testLDIFModify(final String[] args)
- {
- assertToolFailsWithUsage(LDIFModify.ldifModifyMain(args, false, outStream, errStream));
- }
-
- @Test(dataProvider = "invalidArg")
- public void testLDIFSearch(final String[] args)
- {
- assertToolFailsWithUsage(LDIFSearch.mainSearch(args, false, outStream, errStream));
- }
-
- @Test(dataProvider = "invalidArgs")
public void testListBackends(final String[] args)
{
assertToolFailsWithUsage(ListBackends.listBackends(args, false, outStream, errStream));
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/types/EntrySchemaCheckingTestCase.java b/opendj-server-legacy/src/test/java/org/opends/server/types/EntrySchemaCheckingTestCase.java
index 9b52831..a064814 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/types/EntrySchemaCheckingTestCase.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/types/EntrySchemaCheckingTestCase.java
@@ -17,6 +17,7 @@
package org.opends.server.types;
import static org.opends.server.types.AcceptRejectWarn.*;
+import static org.opends.server.types.NullOutputStream.nullPrintStream;
import static org.testng.Assert.*;
import java.util.LinkedList;
@@ -27,7 +28,7 @@
import org.forgerock.opendj.ldap.schema.CoreSchema;
import org.opends.server.TestCaseUtils;
import org.opends.server.core.DirectoryServer;
-import org.opends.server.tools.LDAPModify;
+import com.forgerock.opendj.ldap.tools.LDAPModify;
import org.testng.annotations.Test;
/**
@@ -275,7 +276,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
Entry e = TestCaseUtils.makeEntry(
"dn: cn=test,o=test",
@@ -319,7 +320,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
Entry e = TestCaseUtils.makeEntry(
"dn: cn=test,o=test",
@@ -363,7 +364,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
Entry e = TestCaseUtils.makeEntry(
"dn: cn=test,o=test",
@@ -495,7 +496,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
Entry e = TestCaseUtils.makeEntry(
"dn: cn=test,o=test",
@@ -550,7 +551,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
Entry e = TestCaseUtils.makeEntry(
"dn: cn=test,o=test",
@@ -599,7 +600,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
Entry e = TestCaseUtils.makeEntry(
"dn: cn=test,o=test",
@@ -650,7 +651,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
Entry e = TestCaseUtils.makeEntry(
"dn: cn=test,o=test",
@@ -699,7 +700,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
Entry e = TestCaseUtils.makeEntry(
"dn: cn=test,o=test",
@@ -749,7 +750,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
Entry e = TestCaseUtils.makeEntry(
"dn: cn=test,o=test",
@@ -801,7 +802,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
Entry e = TestCaseUtils.makeEntry(
"dn: cn=test,o=test",
@@ -852,7 +853,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
Entry e = TestCaseUtils.makeEntry(
"dn: cn=test,o=test",
@@ -901,7 +902,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
Entry e = TestCaseUtils.makeEntry(
"dn: cn=test,o=test",
@@ -951,7 +952,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
Entry e = TestCaseUtils.makeEntry(
"dn: description=foo,o=test",
@@ -1001,7 +1002,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
Entry e = TestCaseUtils.makeEntry(
"dn: cn=test+description=foo,o=test",
@@ -1052,7 +1053,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
Entry e = TestCaseUtils.makeEntry(
"dn: description=foo,o=test",
@@ -1106,7 +1107,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
Entry e = TestCaseUtils.makeEntry(
"dn: cn=test+description=foo,o=test",
@@ -1160,7 +1161,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
Entry e = TestCaseUtils.makeEntry(
"dn: cn=test,o=test",
@@ -1211,7 +1212,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
Entry e = TestCaseUtils.makeEntry(
"dn: cn=test,o=test",
@@ -1264,7 +1265,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
Entry e = TestCaseUtils.makeEntry(
"dn: cn=test+description=foo,o=test",
@@ -1317,7 +1318,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
Entry e = TestCaseUtils.makeEntry(
"dn: description=foo,o=test",
@@ -1383,7 +1384,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
Entry e = TestCaseUtils.makeEntry(
@@ -1411,7 +1412,7 @@
"-f", path
};
- assertEquals(LDAPModify.mainModify(args, false, null, System.err), 0);
+ assertEquals(LDAPModify.run(nullPrintStream(), System.err, args), 0);
LocalizableMessageBuilder invalidReason = new LocalizableMessageBuilder();
assertTrue(e.conformsToSchema(null, false, true, true, invalidReason),
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/types/PrivilegeTestCase.java b/opendj-server-legacy/src/test/java/org/opends/server/types/PrivilegeTestCase.java
index 7294ca7..10e5f5d 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/types/PrivilegeTestCase.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/types/PrivilegeTestCase.java
@@ -60,9 +60,9 @@
import org.opends.server.protocols.internal.InternalSearchOperation;
import org.opends.server.protocols.internal.Requests;
import org.opends.server.protocols.internal.SearchRequest;
-import org.opends.server.tools.LDAPModify;
-import org.opends.server.tools.LDAPPasswordModify;
-import org.opends.server.tools.LDAPSearch;
+import com.forgerock.opendj.ldap.tools.LDAPModify;
+import com.forgerock.opendj.ldap.tools.LDAPPasswordModify;
+import com.forgerock.opendj.ldap.tools.LDAPSearch;
import org.opends.server.tools.RemoteConnection;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
@@ -75,6 +75,7 @@
import static org.opends.server.TestCaseUtils.*;
import static org.opends.server.protocols.internal.InternalClientConnection.*;
import static org.opends.server.protocols.internal.Requests.*;
+import static org.opends.server.types.NullOutputStream.nullPrintStream;
import static org.opends.server.types.Privilege.*;
import static org.opends.server.util.CollectionUtils.*;
import static org.testng.Assert.*;
@@ -732,7 +733,7 @@
"-f", path
};
- int resultCode = LDAPModify.mainModify(args, false, null, null);
+ int resultCode = LDAPModify.run(nullPrintStream(), nullPrintStream(), args);
if (hasPrivilege)
{
assertEquals(resultCode, 0);
@@ -798,7 +799,7 @@
};
int resultCode =
- LDAPPasswordModify.mainPasswordModify(args, false, null, null);
+ LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args);
if (hasPrivilege)
{
assertEquals(resultCode, 0);
@@ -813,8 +814,7 @@
"-a", "dn:cn=PWReset Target,o=test",
"-n", "password"
};
- assertEquals(LDAPPasswordModify.mainPasswordModify(args, false, null,
- null), 0);
+ assertEquals(LDAPPasswordModify.run(nullPrintStream(), nullPrintStream(), args), 0);
}
else
{
@@ -2193,12 +2193,12 @@
private int runSearch(String[] args)
{
- return LDAPSearch.mainSearch(args, false, null, null);
+ return LDAPSearch.run(nullPrintStream(), nullPrintStream(), args);
}
private int runSearchWithSystemErr(String[] args)
{
- return LDAPSearch.mainSearch(args, false, null, System.err);
+ return LDAPSearch.run(nullPrintStream(), System.err, args);
}
/**
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/types/SearchFilterTests.java b/opendj-server-legacy/src/test/java/org/opends/server/types/SearchFilterTests.java
index 846fba7..1a8de2e 100644
--- a/opendj-server-legacy/src/test/java/org/opends/server/types/SearchFilterTests.java
+++ b/opendj-server-legacy/src/test/java/org/opends/server/types/SearchFilterTests.java
@@ -23,12 +23,12 @@
import java.util.LinkedHashSet;
import java.util.List;
+import org.forgerock.opendj.ldap.Base64;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.schema.AttributeType;
import org.opends.server.DirectoryServerTestCase;
import org.opends.server.TestCaseUtils;
import org.opends.server.core.DirectoryServer;
-import org.opends.server.util.Base64;
import org.opends.server.util.StaticUtils;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
@@ -1031,7 +1031,7 @@
"userCertificate;binary:: "+BASE64_CERT_VALUE
);
StringBuilder builder = new StringBuilder();
- RawFilter.valueToFilterString(builder,ByteString.wrap(Base64.decode(BASE64_CERT_VALUE)));
+ RawFilter.valueToFilterString(builder, ByteString.wrap(Base64.decode(BASE64_CERT_VALUE).toByteArray()));
final String CERTIFICATE_ENCODED = builder.toString();
return new Object[][]{
diff --git a/opendj-server-legacy/src/test/java/org/opends/server/util/TestBase64.java b/opendj-server-legacy/src/test/java/org/opends/server/util/TestBase64.java
deleted file mode 100644
index 775df7e..0000000
--- a/opendj-server-legacy/src/test/java/org/opends/server/util/TestBase64.java
+++ /dev/null
@@ -1,202 +0,0 @@
-/*
- * The contents of this file are subject to the terms of the Common Development and
- * Distribution License (the License). You may not use this file except in compliance with the
- * License.
- *
- * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
- * specific language governing permission and limitations under the License.
- *
- * When distributing Covered Software, include this CDDL Header Notice in each file and include
- * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
- * Header, with the fields enclosed by brackets [] replaced by your own identifying
- * information: "Portions Copyright [year] [name of copyright owner]".
- *
- * Copyright 2006-2008 Sun Microsystems, Inc.
- * Portions Copyright 2014-2015 ForgeRock AS.
- */
-package org.opends.server.util;
-
-import java.text.ParseException;
-import java.util.Arrays;
-
-import org.testng.Assert;
-import org.testng.annotations.DataProvider;
-import org.testng.annotations.Test;
-
-/**
- * This class defines a set of tests for the
- * {@link org.opends.server.util.Base64} class.
- */
-public final class TestBase64 extends UtilTestCase {
- /** Look up table for converting hex chars to byte values. */
- private static final byte[] hexToByte = { -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1,
- -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
- -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1 - 1,
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 };
-
- /**
- * Base 64 valid test data provider.
- *
- * @return Returns an array of decoded and valid encoded base64 data.
- */
- @DataProvider(name = "validData")
- public Object[][] createValidData() {
- return new Object[][] {
- { "", "" },
- { "00", "AA==" },
- { "01", "AQ==" },
- { "02", "Ag==" },
- { "03", "Aw==" },
- { "04", "BA==" },
- { "05", "BQ==" },
- { "06", "Bg==" },
- { "07", "Bw==" },
- { "0000", "AAA=" },
- { "000000", "AAAA" },
- { "00000000", "AAAAAA==" },
- {
- "000102030405060708090a0b0c0d0e0f"
- + "101112131415161718191a1b1c1d1e1f"
- + "202122232425262728292a2b2c2d2e2f"
- + "303132333435363738393a3b3c3d3e3f"
- + "404142434445464748494a4b4c4d4e4f"
- + "505152535455565758595a5b5c5d5e5f"
- + "606162636465666768696a6b6c6d6e6f"
- + "707172737475767778797a7b7c7d7e7f"
- + "808182838485868788898a8b8c8d8e8f"
- + "909192939495969798999a9b9c9d9e9f"
- + "a0a1a2a3a4a5a6a7a8a9aaabacadaeaf"
- + "b0b1b2b3b4b5b6b7b8b9babbbcbdbebf"
- + "c0c1c2c3c4c5c6c7c8c9cacbcccdcecf"
- + "d0d1d2d3d4d5d6d7d8d9dadbdcdddedf"
- + "e0e1e2e3e4e5e6e7e8e9eaebecedeeef"
- + "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
- "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4v"
- + "MDEyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5f"
- + "YGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn+AgYKDhIWGh4iJiouMjY6P"
- + "kJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq+wsbKztLW2t7i5uru8vb6/"
- + "wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v"
- + "8PHy8/T19vf4+fr7/P3+/w==" }, };
- }
-
- /**
- * Base 64 invalid test data provider.
- *
- * @return Returns an array of invalid encoded base64 data.
- */
- @DataProvider(name = "invalidData")
- public Object[][] createInvalidData() {
- // FIXME: fix cases ==== and ==x=
-
- return new Object[][] { { "=" }, { "==" }, { "===" }, { "A" },
- { "AA" }, { "AAA" }, { "AA`=" }, { "AA~=" }, { "AA!=" },
- { "AA@=" }, { "AA#=" }, { "AA$=" }, { "AA%=" }, { "AA^=" },
- { "AA*=" }, { "AA(=" }, { "AA)=" }, { "AA_=" }, { "AA-=" },
- { "AA{=" }, { "AA}=" }, { "AA|=" }, { "AA[=" }, { "AA]=" },
- { "AA\\=" }, { "AA;=" }, { "AA'=" }, { "AA\"=" }, { "AA:=" },
- { "AA,=" }, { "AA.=" }, { "AA<=" }, { "AA>=" }, { "AA?=" },
- { "AA;=" } };
- }
-
- /**
- * Tests the encode method.
- *
- * @param hexData
- * The decoded hex data.
- * @param encodedData
- * The encoded data.
- * @throws Exception
- * If the test failed unexpectedly.
- */
- @Test(dataProvider = "validData")
- public void testEncode(String hexData, String encodedData)
- throws Exception {
- byte[] data = getBytes(hexData);
- String base64 = Base64.encode(data);
- Assert.assertEquals(base64, encodedData);
- }
-
- /**
- * Tests the decode method against valid data.
- *
- * @param hexData
- * The decoded hex data.
- * @param encodedData
- * The encoded data.
- * @throws Exception
- * If the test failed unexpectedly.
- */
- @Test(dataProvider = "validData")
- public void testDecodeValidData(String hexData, String encodedData)
- throws Exception {
- byte[] data = getBytes(hexData);
- byte[] decodedData = Base64.decode(encodedData);
- Assert.assertEquals(decodedData, data);
- }
-
- /**
- * Tests the decode method against invalid data.
- *
- * @param encodedData
- * The invalid encoded data.
- * @throws Exception
- * If the test failed unexpectedly.
- */
- @Test(dataProvider = "invalidData", expectedExceptions = { ParseException.class })
- public void testDecodeInvalidData(String encodedData) throws Exception {
- Assert.fail("Expected exception but got result: "
- + Arrays.toString(Base64.decode(encodedData)));
- }
-
- /**
- * Decode a hex string to a byte-array.
- *
- * @param hexData
- * The string of hex.
- * @return Returns the decoded byte array.
- */
- private byte[] getBytes(String hexData) {
- int sz = hexData.length();
-
- if (sz % 2 != 0) {
- throw new IllegalArgumentException(
- "Hex string does not contain an even number of hex digits");
- }
-
- byte[] bytes = new byte[sz / 2];
-
- for (int i = 0, j = 0; i < sz; i += 2, j++) {
- int c = hexData.codePointAt(i);
- if ((c & 0x7f) != c) {
- throw new IllegalArgumentException(
- "Hex string contains non-hex digits");
- }
-
- byte b1 = hexToByte[c];
- if (b1 < 0) {
- throw new IllegalArgumentException(
- "Hex string contains non-hex digits");
- }
-
- c = hexData.codePointAt(i + 1);
- if ((c & 0x7f) != c) {
- throw new IllegalArgumentException(
- "Hex string contains non-hex digits");
- }
-
- byte b2 = hexToByte[c];
- if (b2 < 0) {
- throw new IllegalArgumentException(
- "Hex string contains non-hex digits");
- }
-
- bytes[j] = (byte) ((b1 << 4) | b2);
- }
-
- return bytes;
- }
-}
--
Gitblit v1.10.0