You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ambari.apache.org by lp...@apache.org on 2017/10/13 15:54:29 UTC
[01/33] ambari git commit: AMBARI-22224. host and hostname built-in
variables are not populated when performing Kerberos-related operations
(rlevas) [Forced Update!]
Repository: ambari
Updated Branches:
refs/heads/feature-branch-AMBARI-21307 b7f03cac8 -> d623a21fe (forced update)
AMBARI-22224. host and hostname built-in variables are not populated when performing Kerberos-related operations (rlevas)
Project: http://git-wip-us.apache.org/repos/asf/ambari/repo
Commit: http://git-wip-us.apache.org/repos/asf/ambari/commit/0f76c7f9
Tree: http://git-wip-us.apache.org/repos/asf/ambari/tree/0f76c7f9
Diff: http://git-wip-us.apache.org/repos/asf/ambari/diff/0f76c7f9
Branch: refs/heads/feature-branch-AMBARI-21307
Commit: 0f76c7f9d642bced5c89e0a25986c12c89213912
Parents: d88d3cc
Author: Robert Levas <rl...@hortonworks.com>
Authored: Thu Oct 12 15:49:57 2017 -0400
Committer: Robert Levas <rl...@hortonworks.com>
Committed: Thu Oct 12 15:49:57 2017 -0400
----------------------------------------------------------------------
.../ambari/server/controller/KerberosHelperImpl.java | 2 +-
.../kerberos/AbstractPrepareKerberosServerAction.java | 14 ++++++++++++++
.../upgrades/PreconfigureKerberosAction.java | 13 +++++++++++++
.../AbstractPrepareKerberosServerActionTest.java | 5 +++++
4 files changed, 33 insertions(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/ambari/blob/0f76c7f9/ambari-server/src/main/java/org/apache/ambari/server/controller/KerberosHelperImpl.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/controller/KerberosHelperImpl.java b/ambari-server/src/main/java/org/apache/ambari/server/controller/KerberosHelperImpl.java
index f8fe31a..4f14614 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/controller/KerberosHelperImpl.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/controller/KerberosHelperImpl.java
@@ -1644,7 +1644,7 @@ public class KerberosHelperImpl implements KerberosHelper {
// Calculate the current host-specific configurations. These will be used to replace
// variables within the Kerberos descriptor data
Map<String, Map<String, String>> configurations = calculateConfigurations(cluster,
- hostname.equals(ambariServerHostname) ? null : hostname,
+ hostname,
kerberosDescriptor,
false,
false);
http://git-wip-us.apache.org/repos/asf/ambari/blob/0f76c7f9/ambari-server/src/main/java/org/apache/ambari/server/serveraction/kerberos/AbstractPrepareKerberosServerAction.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/serveraction/kerberos/AbstractPrepareKerberosServerAction.java b/ambari-server/src/main/java/org/apache/ambari/server/serveraction/kerberos/AbstractPrepareKerberosServerAction.java
index 3db844a..7948a60 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/serveraction/kerberos/AbstractPrepareKerberosServerAction.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/serveraction/kerberos/AbstractPrepareKerberosServerAction.java
@@ -40,6 +40,7 @@ import org.apache.ambari.server.state.kerberos.KerberosDescriptor;
import org.apache.ambari.server.state.kerberos.KerberosIdentityDescriptor;
import org.apache.ambari.server.state.kerberos.KerberosServiceDescriptor;
import org.apache.ambari.server.utils.StageUtils;
+import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -141,6 +142,19 @@ public abstract class AbstractPrepareKerberosServerAction extends KerberosServer
if (serviceDescriptor != null) {
List<KerberosIdentityDescriptor> serviceIdentities = serviceDescriptor.getIdentities(true, filterContext);
+ if (!StringUtils.isEmpty(hostName)) {
+ // Update the configurations with the relevant hostname
+ Map<String, String> generalProperties = currentConfigurations.get("");
+ if (generalProperties == null) {
+ generalProperties = new HashMap<>();
+ currentConfigurations.put("", generalProperties);
+ }
+
+ // Add the current hostname under "host" and "hostname"
+ generalProperties.put("host", hostName);
+ generalProperties.put("hostname", hostName);
+ }
+
// Add service-level principals (and keytabs)
kerberosHelper.addIdentities(kerberosIdentityDataFileWriter, serviceIdentities,
identityFilter, hostName, serviceName, componentName, kerberosConfigurations, currentConfigurations, excludeHeadless);
http://git-wip-us.apache.org/repos/asf/ambari/blob/0f76c7f9/ambari-server/src/main/java/org/apache/ambari/server/serveraction/upgrades/PreconfigureKerberosAction.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/serveraction/upgrades/PreconfigureKerberosAction.java b/ambari-server/src/main/java/org/apache/ambari/server/serveraction/upgrades/PreconfigureKerberosAction.java
index d18f333..5af7c6b 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/serveraction/upgrades/PreconfigureKerberosAction.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/serveraction/upgrades/PreconfigureKerberosAction.java
@@ -305,6 +305,19 @@ public class PreconfigureKerberosAction extends AbstractUpgradeServerAction {
KerberosServiceDescriptor serviceDescriptor = kerberosDescriptor.getService(serviceName);
+ if (!StringUtils.isEmpty(hostName)) {
+ // Update the configurations with the relevant hostname
+ Map<String, String> generalProperties = currentConfigurations.get("");
+ if (generalProperties == null) {
+ generalProperties = new HashMap<>();
+ currentConfigurations.put("", generalProperties);
+ }
+
+ // Add the current hostname under "host" and "hostname"
+ generalProperties.put("host", hostName);
+ generalProperties.put("hostname", hostName);
+ }
+
if (serviceDescriptor != null) {
List<KerberosIdentityDescriptor> serviceIdentities = serviceDescriptor.getIdentities(true, filterContext);
http://git-wip-us.apache.org/repos/asf/ambari/blob/0f76c7f9/ambari-server/src/test/java/org/apache/ambari/server/serveraction/kerberos/AbstractPrepareKerberosServerActionTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/serveraction/kerberos/AbstractPrepareKerberosServerActionTest.java b/ambari-server/src/test/java/org/apache/ambari/server/serveraction/kerberos/AbstractPrepareKerberosServerActionTest.java
index 8ff5ad2..5522132 100644
--- a/ambari-server/src/test/java/org/apache/ambari/server/serveraction/kerberos/AbstractPrepareKerberosServerActionTest.java
+++ b/ambari-server/src/test/java/org/apache/ambari/server/serveraction/kerberos/AbstractPrepareKerberosServerActionTest.java
@@ -45,6 +45,7 @@ import org.apache.ambari.server.state.kerberos.KerberosComponentDescriptor;
import org.apache.ambari.server.state.kerberos.KerberosDescriptor;
import org.apache.ambari.server.state.kerberos.KerberosServiceDescriptor;
import org.easymock.EasyMock;
+import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
@@ -152,6 +153,10 @@ public class AbstractPrepareKerberosServerActionTest {
false, propertiesToIgnore, false);
verify(kerberosHelper);
+
+ // Ensure the host and hostname values were set in the configuration context
+ Assert.assertEquals("host1", configurations.get("").get("host"));
+ Assert.assertEquals("host1", configurations.get("").get("hostname"));
}
}
[29/33] ambari git commit: AMBARI-21307 Added unit test for the
LdapFacade
Posted by lp...@apache.org.
AMBARI-21307 Added unit test for the LdapFacade
Project: http://git-wip-us.apache.org/repos/asf/ambari/repo
Commit: http://git-wip-us.apache.org/repos/asf/ambari/commit/2f059df3
Tree: http://git-wip-us.apache.org/repos/asf/ambari/tree/2f059df3
Diff: http://git-wip-us.apache.org/repos/asf/ambari/diff/2f059df3
Branch: refs/heads/feature-branch-AMBARI-21307
Commit: 2f059df32d74fbc32385838ff459eac481069647
Parents: 060b85c
Author: lpuskas <lp...@apache.org>
Authored: Thu Oct 12 16:53:31 2017 +0200
Committer: lpuskas <lp...@apache.org>
Committed: Fri Oct 13 17:20:53 2017 +0200
----------------------------------------------------------------------
.../services/AmbariConfigurationService.java | 2 +-
.../ldap/domain/AmbariLdapConfiguration.java | 22 ++
.../server/ldap/service/AmbariLdapFacade.java | 10 +-
.../ldap/service/AmbariLdapFacadeTest.java | 215 +++++++++++++++++++
4 files changed, 245 insertions(+), 4 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/ambari/blob/2f059df3/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationService.java b/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationService.java
index 492509f..38ae766 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationService.java
@@ -150,7 +150,7 @@ public class AmbariConfigurationService extends BaseService {
@PUT
@Path("{configurationId}")
@Produces(MediaType.TEXT_PLAIN)
- @ApiOperation(value = "Updates ambari configuration resources - Not implemented yet",
+ @ApiOperation(value = "Updates ambari configuration resources ",
nickname = "AmbariConfigurationService#updateAmbariConfiguration")
@ApiImplicitParams({
@ApiImplicitParam(dataType = AMBARI_CONFIGURATION_REQUEST_TYPE, paramType = PARAM_TYPE_BODY),
http://git-wip-us.apache.org/repos/asf/ambari/blob/2f059df3/ambari-server/src/main/java/org/apache/ambari/server/ldap/domain/AmbariLdapConfiguration.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/domain/AmbariLdapConfiguration.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/domain/AmbariLdapConfiguration.java
index d071ebe..8b26cd3 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/domain/AmbariLdapConfiguration.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/domain/AmbariLdapConfiguration.java
@@ -19,6 +19,8 @@ import java.util.Map;
import javax.inject.Inject;
+import org.apache.commons.lang3.builder.EqualsBuilder;
+import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -174,4 +176,24 @@ public class AmbariLdapConfiguration {
public String toString() {
return configurationMap.toString();
}
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+
+ if (o == null || getClass() != o.getClass()) return false;
+
+ AmbariLdapConfiguration that = (AmbariLdapConfiguration) o;
+
+ return new EqualsBuilder()
+ .append(configurationMap, that.configurationMap)
+ .isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder(17, 37)
+ .append(configurationMap)
+ .toHashCode();
+ }
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/2f059df3/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
index c75b0c4..bbfbc8e 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
@@ -33,7 +33,7 @@ public class AmbariLdapFacade implements LdapFacade {
/**
* Additional parameters expected to be provided along with the configuration
*/
- private enum Parameters {
+ protected enum Parameters {
TEST_USER_NAME("ambari.ldap.test.user.name"),
TEST_USER_PASSWORD("ambari.ldap.test.user.password");
@@ -43,7 +43,7 @@ public class AmbariLdapFacade implements LdapFacade {
this.parameterKey = parameterKey;
}
- private String getParameterKey() {
+ public String getParameterKey() {
return parameterKey;
}
@@ -62,6 +62,7 @@ public class AmbariLdapFacade implements LdapFacade {
@Override
public void checkConnection(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
try {
+
ldapConfigurationService.checkConnection(ambariLdapConfiguration);
LOGGER.info("Validating LDAP connection related configuration: SUCCESS");
@@ -80,12 +81,15 @@ public class AmbariLdapFacade implements LdapFacade {
LOGGER.info("Detecting LDAP configuration attributes ...");
try {
-
+ LOGGER.info("Detecting user attributes ....");
// decorate the configuration with detected user attributes
ambariLdapConfiguration = ldapAttributeDetectionService.detectLdapUserAttributes(ambariLdapConfiguration);
+ LOGGER.info("Detecting group attributes ....");
// decorate the configuration with detected group attributes
ambariLdapConfiguration = ldapAttributeDetectionService.detectLdapGroupAttributes(ambariLdapConfiguration);
+
+ LOGGER.info("Attribute detection finished.");
return ambariLdapConfiguration;
} catch (Exception e) {
http://git-wip-us.apache.org/repos/asf/ambari/blob/2f059df3/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/AmbariLdapFacadeTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/AmbariLdapFacadeTest.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/AmbariLdapFacadeTest.java
new file mode 100644
index 0000000..8552f86
--- /dev/null
+++ b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/AmbariLdapFacadeTest.java
@@ -0,0 +1,215 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service;
+
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.ambari.server.ldap.domain.AmbariLdapConfigKeys;
+import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.domain.AmbariLdapConfigurationFactory;
+import org.apache.ambari.server.ldap.domain.TestAmbariAmbariLdapConfigurationFactory;
+import org.easymock.Capture;
+import org.easymock.EasyMock;
+import org.easymock.EasyMockRule;
+import org.easymock.EasyMockSupport;
+import org.easymock.Mock;
+import org.easymock.MockType;
+import org.easymock.TestSubject;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+
+/**
+ * Unit test suite for the LdapFacade operations.
+ */
+public class AmbariLdapFacadeTest extends EasyMockSupport {
+
+ @Rule
+ public EasyMockRule mocks = new EasyMockRule(this);
+
+ @Mock(type = MockType.STRICT)
+ public LdapConfigurationService ldapConfigurationServiceMock;
+
+ @Mock(type = MockType.STRICT)
+ public LdapAttributeDetectionService ldapAttributeDetectionServiceMock;
+
+ private AmbariLdapConfigurationFactory ambariLdapConfigurationFactory;
+
+
+ @TestSubject
+ private LdapFacade ldapFacade = new AmbariLdapFacade();
+
+ private AmbariLdapConfiguration ambariLdapConfiguration;
+
+
+ private Capture<AmbariLdapConfiguration> ambariLdapConfigurationCapture;
+
+ @Before
+ public void before() {
+ ambariLdapConfigurationFactory = new TestAmbariAmbariLdapConfigurationFactory();
+ ambariLdapConfiguration = ambariLdapConfigurationFactory.createLdapConfiguration(Maps.newHashMap());
+ ambariLdapConfigurationCapture = Capture.newInstance();
+
+
+ resetAll();
+ }
+
+ /**
+ * Tests whether the facade method call delegates to the proper service call.
+ * The thest is success if the same instance is passed to the service.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void testShouldConfigurationCheckDelegateToTheRightServiceCall() throws Exception {
+ // GIVEN
+ // the mocks are set up
+ ldapConfigurationServiceMock.checkConnection(EasyMock.capture(ambariLdapConfigurationCapture));
+ replayAll();
+ // WHEN
+ // the facade method is called
+ ldapFacade.checkConnection(ambariLdapConfiguration);
+
+ // THEN
+ // the captured configuration instance is the same the facade method got called with
+ Assert.assertEquals("The configuration instance souldn't change before passing it to the service",
+ ambariLdapConfiguration, ambariLdapConfigurationCapture.getValue());
+ }
+
+ @Test(expected = AmbariLdapException.class)
+ public void testShouldConfigurationCheckFailureResultInAmbariLdapException() throws Exception {
+ // GIVEN
+ ldapConfigurationServiceMock.checkConnection(EasyMock.anyObject(AmbariLdapConfiguration.class));
+ EasyMock.expectLastCall().andThrow(new AmbariLdapException("Testing ..."));
+ replayAll();
+
+ // WHEN
+ ldapFacade.checkConnection(ambariLdapConfiguration);
+
+ // THEN
+ // exception is thrown
+
+ }
+
+ @Test
+ public void testShouldLdapAttributesCheckDelegateToTheRightServiceCalls() throws Exception {
+ // GIVEN
+
+ Map<String, Object> parameters = Maps.newHashMap();
+ parameters.put(AmbariLdapFacade.Parameters.TEST_USER_NAME.getParameterKey(), "testUser");
+ parameters.put(AmbariLdapFacade.Parameters.TEST_USER_PASSWORD.getParameterKey(), "testPassword");
+
+
+ Capture<String> testUserCapture = Capture.newInstance();
+ Capture<String> testPasswordCapture = Capture.newInstance();
+ Capture<String> userDnCapture = Capture.newInstance();
+
+ EasyMock.expect(ldapConfigurationServiceMock.checkUserAttributes(EasyMock.capture(testUserCapture), EasyMock.capture(testPasswordCapture),
+ EasyMock.capture(ambariLdapConfigurationCapture))).andReturn("userDn");
+
+ EasyMock.expect(ldapConfigurationServiceMock.checkGroupAttributes(EasyMock.capture(userDnCapture),
+ EasyMock.capture(ambariLdapConfigurationCapture))).andReturn(Sets.newHashSet("userGroup"));
+
+ replayAll();
+
+ // WHEN
+ Set<String> testUserGroups = ldapFacade.checkLdapAttributes(parameters, ambariLdapConfiguration);
+
+ // THEN
+ Assert.assertEquals("testUser", testUserCapture.getValue());
+ Assert.assertEquals("testPassword", testPasswordCapture.getValue());
+ Assert.assertEquals("userDn", userDnCapture.getValue());
+
+ Assert.assertTrue(testUserGroups.contains("userGroup"));
+
+ }
+
+ @Test(expected = AmbariLdapException.class)
+ public void testShouldAttributeCheckFailuresResultInAmbariLdapException() throws Exception {
+ // GIVEN
+ Map<String, Object> parameters = Maps.newHashMap();
+ parameters.put(AmbariLdapFacade.Parameters.TEST_USER_NAME.getParameterKey(), "testUser");
+ parameters.put(AmbariLdapFacade.Parameters.TEST_USER_PASSWORD.getParameterKey(), "testPassword");
+
+ EasyMock.expect(ldapConfigurationServiceMock.checkUserAttributes(EasyMock.anyString(), EasyMock.anyString(),
+ EasyMock.anyObject(AmbariLdapConfiguration.class))).andThrow(new AmbariLdapException("Testing ..."));
+
+ replayAll();
+
+ // WHEN
+ Set<String> testUserGroups = ldapFacade.checkLdapAttributes(parameters, ambariLdapConfiguration);
+ // THEN
+ // Exception is thrown
+ }
+
+ @Test
+ public void testShouldLdapAttributeDetectionDelegateToTheRightServiceCalls() throws Exception {
+
+ // configuration map with user attributes detected
+ Map<String, Object> userConfigMap = Maps.newHashMap();
+ userConfigMap.put(AmbariLdapConfigKeys.USER_NAME_ATTRIBUTE.key(), "uid");
+ AmbariLdapConfiguration userAttrDecoratedConfig = ambariLdapConfigurationFactory.createLdapConfiguration(userConfigMap);
+
+ // configuration map with user+group attributes detected
+ Map<String, Object> groupConfigMap = Maps.newHashMap(userConfigMap);
+ groupConfigMap.put(AmbariLdapConfigKeys.GROUP_NAME_ATTRIBUTE.key(), "dn");
+ AmbariLdapConfiguration groupAttrDecoratedConfig = ambariLdapConfigurationFactory.createLdapConfiguration(groupConfigMap);
+
+ Capture<AmbariLdapConfiguration> userAttrDetectionConfigCapture = Capture.newInstance();
+ Capture<AmbariLdapConfiguration> groupAttrDetectionConfigCapture = Capture.newInstance();
+
+ // GIVEN
+ EasyMock.expect(ldapAttributeDetectionServiceMock.detectLdapUserAttributes(EasyMock.capture(userAttrDetectionConfigCapture)))
+ .andReturn(userAttrDecoratedConfig);
+
+ EasyMock.expect(ldapAttributeDetectionServiceMock.detectLdapGroupAttributes(EasyMock.capture(groupAttrDetectionConfigCapture)))
+ .andReturn(groupAttrDecoratedConfig);
+
+ replayAll();
+
+ // WHEN
+ AmbariLdapConfiguration detected = ldapFacade.detectAttributes(ambariLdapConfiguration);
+
+ // THEN
+ Assert.assertEquals("User attribute detection called with the wrong configuration", ambariLdapConfiguration,
+ userAttrDetectionConfigCapture.getValue());
+
+ Assert.assertEquals("Group attribute detection called with the wrong configuration", userAttrDecoratedConfig,
+ groupAttrDetectionConfigCapture.getValue());
+
+ Assert.assertEquals("Attribute detection returned an invalid configuration", groupAttrDecoratedConfig, detected);
+
+ }
+
+ @Test(expected = AmbariLdapException.class)
+ public void testShouldAttributeDetectionFailuresResultInAmbariLdapException() throws Exception {
+ // GIVEN
+ EasyMock.expect(ldapAttributeDetectionServiceMock.detectLdapUserAttributes(EasyMock.anyObject(AmbariLdapConfiguration.class)))
+ .andThrow(new AmbariLdapException("Testing ..."));
+
+ replayAll();
+
+ // WHEN
+ ldapFacade.detectAttributes(ambariLdapConfiguration);
+
+ // THEN
+ // Exception is thrown
+ }
+}
\ No newline at end of file
[10/33] ambari git commit: AMBARI-21545 Stack Advisor support for
LDAP configuration (benyoka)
Posted by lp...@apache.org.
AMBARI-21545 Stack Advisor support for LDAP configuration (benyoka)
Project: http://git-wip-us.apache.org/repos/asf/ambari/repo
Commit: http://git-wip-us.apache.org/repos/asf/ambari/commit/e87ca3ce
Tree: http://git-wip-us.apache.org/repos/asf/ambari/tree/e87ca3ce
Diff: http://git-wip-us.apache.org/repos/asf/ambari/diff/e87ca3ce
Branch: refs/heads/feature-branch-AMBARI-21307
Commit: e87ca3cec5768e887b12e9fe3e500317664e8c36
Parents: 2818046
Author: Balazs Bence Sari <be...@apache.org>
Authored: Tue Aug 8 20:17:14 2017 +0200
Committer: lpuskas <lp...@apache.org>
Committed: Fri Oct 13 17:20:49 2017 +0200
----------------------------------------------------------------------
.../services/AmbariConfigurationService.java | 4 +-
.../stackadvisor/StackAdvisorRequest.java | 12 ++
.../commands/StackAdvisorCommand.java | 54 +++++
.../commands/StackAdvisorCommandTest.java | 212 +++++++++++++++++++
.../StackAdvisorResourceProviderTest.java | 97 ++++-----
5 files changed, 324 insertions(+), 55 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/ambari/blob/e87ca3ce/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationService.java b/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationService.java
index 0632361..927e518 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationService.java
@@ -56,9 +56,9 @@ import io.swagger.annotations.ApiResponses;
* "data": [
* {
* "authentication.ldap.primaryUrl": "localhost:33389"
- "authentication.ldap.secondaryUrl": "localhost:333"
+ * "authentication.ldap.secondaryUrl": "localhost:333"
* "authentication.ldap.baseDn": "dc=ambari,dc=apache,dc=org"
- * // ......
+ * // ......
* ]
* }
* </pre>
http://git-wip-us.apache.org/repos/asf/ambari/blob/e87ca3ce/ambari-server/src/main/java/org/apache/ambari/server/api/services/stackadvisor/StackAdvisorRequest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/api/services/stackadvisor/StackAdvisorRequest.java b/ambari-server/src/main/java/org/apache/ambari/server/api/services/stackadvisor/StackAdvisorRequest.java
index 3a2b488..cd26c56 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/api/services/stackadvisor/StackAdvisorRequest.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/api/services/stackadvisor/StackAdvisorRequest.java
@@ -31,6 +31,8 @@ import org.apache.ambari.server.api.services.stackadvisor.recommendations.Recomm
import org.apache.ambari.server.state.ChangedConfigInfo;
import org.apache.commons.lang.StringUtils;
+import com.google.common.base.Preconditions;
+
/**
* Stack advisor request.
*/
@@ -48,6 +50,7 @@ public class StackAdvisorRequest {
private List<ChangedConfigInfo> changedConfigurations = new LinkedList<>();
private Set<RecommendationResponse.ConfigGroup> configGroups;
private Map<String, String> userContext = new HashMap<>();
+ private Map<String, Object> ldapConfig = new HashMap<>();
public String getStackName() {
return stackName;
@@ -93,6 +96,8 @@ public class StackAdvisorRequest {
return configurations;
}
+ public Map<String, Object> getLdapConfig() { return ldapConfig; }
+
public List<ChangedConfigInfo> getChangedConfigurations() {
return changedConfigurations;
}
@@ -189,6 +194,13 @@ public class StackAdvisorRequest {
return this;
}
+ public StackAdvisorRequestBuilder withLdapConfig(Map<String, Object> ldapConfig) {
+ Preconditions.checkNotNull(ldapConfig);
+ this.instance.ldapConfig = ldapConfig;
+ return this;
+ }
+
+
public StackAdvisorRequest build() {
return this.instance;
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/e87ca3ce/ambari-server/src/main/java/org/apache/ambari/server/api/services/stackadvisor/commands/StackAdvisorCommand.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/api/services/stackadvisor/commands/StackAdvisorCommand.java b/ambari-server/src/main/java/org/apache/ambari/server/api/services/stackadvisor/commands/StackAdvisorCommand.java
index 356754d..2dc45de 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/api/services/stackadvisor/commands/StackAdvisorCommand.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/api/services/stackadvisor/commands/StackAdvisorCommand.java
@@ -84,6 +84,7 @@ public abstract class StackAdvisorCommand<T extends StackAdvisorResponse> extend
+ ",services/configurations/dependencies/StackConfigurationDependency/dependency_name"
+ ",services/configurations/dependencies/StackConfigurationDependency/dependency_type,services/configurations/StackConfigurations/type"
+ "&services/StackServices/service_name.in(%s)";
+ private static final String GET_LDAP_CONFIG_URI = "/api/v1/configurations?AmbariConfiguration/type=ldap&fields=AmbariConfiguration/*";
private static final String SERVICES_PROPERTY = "services";
private static final String SERVICES_COMPONENTS_PROPERTY = "components";
private static final String CONFIG_GROUPS_PROPERTY = "config-groups";
@@ -95,6 +96,7 @@ public abstract class StackAdvisorCommand<T extends StackAdvisorResponse> extend
private static final String CHANGED_CONFIGURATIONS_PROPERTY = "changed-configurations";
private static final String USER_CONTEXT_PROPERTY = "user-context";
private static final String AMBARI_SERVER_CONFIGURATIONS_PROPERTY = "ambari-server-properties";
+ protected static final String LDAP_CONFIGURATION_PROPERTY = "ldap-configuration";
private File recommendationsDir;
private String recommendationsArtifactsLifetime;
@@ -160,6 +162,7 @@ public abstract class StackAdvisorCommand<T extends StackAdvisorResponse> extend
populateConfigurations(root, request);
populateConfigGroups(root, request);
populateAmbariServerInfo(root);
+ populateLdapConfiguration(root);
data.servicesJSON = mapper.writeValueAsString(root);
} catch (Exception e) {
// should not happen
@@ -171,6 +174,52 @@ public abstract class StackAdvisorCommand<T extends StackAdvisorResponse> extend
return data;
}
+ /**
+ * Retrieves the LDAP configuration if exists and adds it to services.json
+ * @param root The JSON document that will become service.json when passed to the stack advisor engine
+ * @throws StackAdvisorException
+ * @throws IOException
+ */
+ protected void populateLdapConfiguration(ObjectNode root) throws StackAdvisorException, IOException {
+ Response response = handleRequest(null, null, new LocalUriInfo(GET_LDAP_CONFIG_URI), Request.Type.GET,
+ createConfigResource());
+
+ if (response.getStatus() != Status.OK.getStatusCode()) {
+ String message = String.format(
+ "Error occured during retrieving ldap configuration, status=%s, response=%s",
+ response.getStatus(), (String) response.getEntity());
+ LOG.warn(message);
+ throw new StackAdvisorException(message);
+ }
+
+ String ldapConfigJSON = (String) response.getEntity();
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("LDAP configuration: {}", ldapConfigJSON);
+ }
+
+ JsonNode ldapConfigRoot = mapper.readTree(ldapConfigJSON);
+ ArrayNode ldapConfigs = ((ArrayNode)ldapConfigRoot.get("items"));
+ int numConfigs = ldapConfigs.size();
+ // Zero or one config may exist
+ switch (numConfigs) {
+ case 0:
+ LOG.debug("No LDAP config is stored in the DB");
+ break;
+ case 1:
+ ArrayNode ldapConfigData = (ArrayNode)ldapConfigs.get(0).get("AmbariConfiguration").get("data");
+ if (ldapConfigData.size() == 0) {
+ throw new StackAdvisorException("No configuration data for LDAP configuration.");
+ }
+ if (ldapConfigData.size() > 1) {
+ throw new StackAdvisorException("Ambigous configuration data for LDAP configuration.");
+ }
+ root.put(LDAP_CONFIGURATION_PROPERTY, ldapConfigData.get(0));
+ break;
+ default:
+ throw new StackAdvisorException(String.format("Multiple (%s) LDAP configs are found in the DB.", numConfigs));
+ }
+ }
+
protected void populateAmbariServerInfo(ObjectNode root) throws StackAdvisorException {
Map<String, String> serverProperties = metaInfo.getAmbariServerProperties();
@@ -437,6 +486,11 @@ public abstract class StackAdvisorCommand<T extends StackAdvisorResponse> extend
return createResource(Resource.Type.Host, mapIds);
}
+ protected ResourceInstance createConfigResource() {
+ return createResource(Resource.Type.AmbariConfiguration, new HashMap<>());
+ }
+
+
private ResourceInstance createStackVersionResource(String stackName, String stackVersion) {
Map<Resource.Type, String> mapIds = new HashMap<>();
mapIds.put(Resource.Type.Stack, stackName);
http://git-wip-us.apache.org/repos/asf/ambari/blob/e87ca3ce/ambari-server/src/test/java/org/apache/ambari/server/api/services/stackadvisor/commands/StackAdvisorCommandTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/api/services/stackadvisor/commands/StackAdvisorCommandTest.java b/ambari-server/src/test/java/org/apache/ambari/server/api/services/stackadvisor/commands/StackAdvisorCommandTest.java
index eaa4716..959db15 100644
--- a/ambari-server/src/test/java/org/apache/ambari/server/api/services/stackadvisor/commands/StackAdvisorCommandTest.java
+++ b/ambari-server/src/test/java/org/apache/ambari/server/api/services/stackadvisor/commands/StackAdvisorCommandTest.java
@@ -18,6 +18,7 @@
package org.apache.ambari.server.api.services.stackadvisor.commands;
+import static org.apache.ambari.server.api.services.stackadvisor.commands.StackAdvisorCommand.LDAP_CONFIGURATION_PROPERTY;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
@@ -33,12 +34,21 @@ import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
+import java.util.HashMap;
import java.util.Iterator;
+import java.util.List;
import java.util.Map;
import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.apache.ambari.server.api.resources.ResourceInstance;
import org.apache.ambari.server.api.services.AmbariMetaInfo;
+import org.apache.ambari.server.api.services.Request;
+import org.apache.ambari.server.api.services.ResultStatus;
import org.apache.ambari.server.api.services.stackadvisor.StackAdvisorException;
import org.apache.ambari.server.api.services.stackadvisor.StackAdvisorRequest;
import org.apache.ambari.server.api.services.stackadvisor.StackAdvisorRequest.StackAdvisorRequestBuilder;
@@ -50,6 +60,7 @@ import org.apache.ambari.server.state.ServiceInfo;
import org.apache.commons.io.FileUtils;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.annotate.JsonProperty;
+import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ArrayNode;
import org.codehaus.jackson.node.ObjectNode;
import org.junit.After;
@@ -59,6 +70,8 @@ import org.junit.rules.TemporaryFolder;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
+import com.google.common.collect.Lists;
+
/**
* StackAdvisorCommand unit tests.
*/
@@ -265,6 +278,197 @@ public class StackAdvisorCommandTest {
assertEquals(0, stackVersions.size());
}
+ @Test
+ public void testPopulateLdapConfig() throws Exception {
+ File recommendationsDir = temp.newFolder("recommendationDir");
+ String recommendationsArtifactsLifetime = "1w";
+ int requestId = 0;
+ StackAdvisorRunner saRunner = mock(StackAdvisorRunner.class);
+ AmbariMetaInfo metaInfo = mock(AmbariMetaInfo.class);
+ doReturn(Collections.emptyList()).when(metaInfo).getStackParentVersions(anyString(), anyString());
+ TestStackAdvisorCommand command = spy(new TestStackAdvisorCommand(recommendationsDir, recommendationsArtifactsLifetime,
+ ServiceInfo.ServiceAdvisorType.PYTHON, requestId, saRunner, metaInfo));
+
+ StackAdvisorRequest request = StackAdvisorRequestBuilder.forStack("stackName", "stackVersion").build();
+
+ Map<String, Object> ldapConfigData = map(
+ "authentication.ldap.primaryUrl", "localhost:33389",
+ "authentication.ldap.secondaryUrl", "localhost:333",
+ "authentication.ldap.baseDn", "c=ambari,dc=apache,dc=org"
+ );
+
+ Map<String, Object> storedLdapConfigResult = map(
+ "items",
+ list(
+ map(
+ "AmbariConfiguration",
+ map(
+ "data", list(ldapConfigData)
+ )
+ )
+ )
+ );
+
+ Response response =
+ Response.status(ResultStatus.STATUS.OK.getStatus()).entity(jsonString(storedLdapConfigResult)).build();
+
+ doReturn(response).when(command).handleRequest(any(), any(), any(), any(), any(), any());
+
+ JsonNode servicesRootNode = json("{}");
+ command.populateLdapConfiguration((ObjectNode)servicesRootNode);
+
+ JsonNode expectedLdapConfig = json(
+ map(LDAP_CONFIGURATION_PROPERTY, ldapConfigData)
+ );
+
+ assertEquals(expectedLdapConfig, servicesRootNode);
+ }
+
+ @Test
+ public void testPopulateLdapConfig_NoConfigs() throws Exception {
+ File recommendationsDir = temp.newFolder("recommendationDir");
+ String recommendationsArtifactsLifetime = "1w";
+ int requestId = 0;
+ StackAdvisorRunner saRunner = mock(StackAdvisorRunner.class);
+ AmbariMetaInfo metaInfo = mock(AmbariMetaInfo.class);
+ doReturn(Collections.emptyList()).when(metaInfo).getStackParentVersions(anyString(), anyString());
+ TestStackAdvisorCommand command = spy(new TestStackAdvisorCommand(recommendationsDir, recommendationsArtifactsLifetime,
+ ServiceInfo.ServiceAdvisorType.PYTHON, requestId, saRunner, metaInfo));
+
+ StackAdvisorRequest request = StackAdvisorRequestBuilder.forStack("stackName", "stackVersion").build();
+
+ Map<String, Object> storedLdapConfigResult = map(
+ "items", list()
+ );
+
+ Response response =
+ Response.status(ResultStatus.STATUS.OK.getStatus()).entity(jsonString(storedLdapConfigResult)).build();
+
+ doReturn(response).when(command).handleRequest(any(), any(), any(), any(), any(), any());
+
+ JsonNode servicesRootNode = json("{}");
+ command.populateLdapConfiguration((ObjectNode)servicesRootNode);
+
+ JsonNode expectedLdapConfig = json("{}");
+
+ assertEquals(expectedLdapConfig, servicesRootNode);
+ }
+
+ /**
+ * An ambigous ldap config that has two items in its data[] array should result in exception
+ */
+ @Test(expected = StackAdvisorException.class)
+ public void testPopulateLdapConfig_multipleConfigs() throws Exception {
+ File recommendationsDir = temp.newFolder("recommendationDir");
+ String recommendationsArtifactsLifetime = "1w";
+ int requestId = 0;
+ StackAdvisorRunner saRunner = mock(StackAdvisorRunner.class);
+ AmbariMetaInfo metaInfo = mock(AmbariMetaInfo.class);
+ doReturn(Collections.emptyList()).when(metaInfo).getStackParentVersions(anyString(), anyString());
+ TestStackAdvisorCommand command = spy(new TestStackAdvisorCommand(recommendationsDir, recommendationsArtifactsLifetime,
+ ServiceInfo.ServiceAdvisorType.PYTHON, requestId, saRunner, metaInfo));
+
+ StackAdvisorRequest request = StackAdvisorRequestBuilder.forStack("stackName", "stackVersion").build();
+
+ Map<String, Object> ldapConfigData = map(
+ "authentication.ldap.primaryUrl", "localhost:33389",
+ "authentication.ldap.secondaryUrl", "localhost:333",
+ "authentication.ldap.baseDn", "c=ambari,dc=apache,dc=org"
+ );
+
+ Map<String, Object> storedLdapConfigResult = map(
+ "items",
+ list(
+ map(
+ "AmbariConfiguration",
+ map(
+ "data",
+ list(ldapConfigData, ldapConfigData)
+ )
+ )
+ )
+ );
+
+ Response response =
+ Response.status(ResultStatus.STATUS.OK.getStatus()).entity(jsonString(storedLdapConfigResult)).build();
+
+ doReturn(response).when(command).handleRequest(any(), any(), any(), any(), any(), any());
+
+ JsonNode servicesRootNode = json("{}");
+ command.populateLdapConfiguration((ObjectNode)servicesRootNode);
+ }
+
+ /**
+ * An if multiple ambari configurations are stored with 'ldap-config' type, an
+ * exception should be thrown
+ */
+ @Test(expected = StackAdvisorException.class)
+ public void testPopulateLdapConfig_multipleResults() throws Exception {
+ File recommendationsDir = temp.newFolder("recommendationDir");
+ String recommendationsArtifactsLifetime = "1w";
+ int requestId = 0;
+ StackAdvisorRunner saRunner = mock(StackAdvisorRunner.class);
+ AmbariMetaInfo metaInfo = mock(AmbariMetaInfo.class);
+ doReturn(Collections.emptyList()).when(metaInfo).getStackParentVersions(anyString(), anyString());
+ TestStackAdvisorCommand command = spy(new TestStackAdvisorCommand(recommendationsDir, recommendationsArtifactsLifetime,
+ ServiceInfo.ServiceAdvisorType.PYTHON, requestId, saRunner, metaInfo));
+
+ StackAdvisorRequest request = StackAdvisorRequestBuilder.forStack("stackName", "stackVersion")
+ .build();
+
+ Map<String, Object> ldapConfig = map(
+ "AmbariConfiguration",
+ map(
+ "data",
+ list(
+ map(
+ "authentication.ldap.primaryUrl", "localhost:33389",
+ "authentication.ldap.secondaryUrl", "localhost:333",
+ "authentication.ldap.baseDn", "c=ambari,dc=apache,dc=org"
+ )
+ )
+ )
+ );
+
+ Map<String, Object> storedLdapConfigResult = map(
+ "items",
+ list(ldapConfig, ldapConfig)
+ );
+
+ Response response =
+ Response.status(ResultStatus.STATUS.OK.getStatus()).entity(jsonString(storedLdapConfigResult)).build();
+
+ doReturn(response).when(command).handleRequest(any(), any(), any(), any(), any(), any());
+
+ JsonNode servicesRootNode = json("{}");
+ command.populateLdapConfiguration((ObjectNode)servicesRootNode);
+ }
+
+ private static String jsonString(Object obj) throws IOException {
+ return new ObjectMapper().writeValueAsString(obj);
+ }
+
+ private static JsonNode json(Object obj) throws IOException {
+ return new ObjectMapper().convertValue(obj, JsonNode.class);
+ }
+
+ private static JsonNode json(String jsonString) throws IOException {
+ return new ObjectMapper().readTree(jsonString);
+ }
+
+ private static List<Object> list(Object... items) {
+ return Lists.newArrayList(items);
+ }
+
+ private static Map<String, Object> map(Object... keysAndValues) {
+ Map<String, Object> map = new HashMap<>();
+ Iterator<Object> iterator = Arrays.asList(keysAndValues).iterator();
+ while (iterator.hasNext()) {
+ map.put(iterator.next().toString(), iterator.next());
+ }
+ return map;
+ }
+
class TestStackAdvisorCommand extends StackAdvisorCommand<TestResource> {
public TestStackAdvisorCommand(File recommendationsDir, String recommendationsArtifactsLifetime, ServiceInfo.ServiceAdvisorType serviceAdvisorType,
int requestId, StackAdvisorRunner saRunner, AmbariMetaInfo metaInfo) {
@@ -290,6 +494,14 @@ public class StackAdvisorCommandTest {
protected TestResource updateResponse(StackAdvisorRequest request, TestResource response) {
return response;
}
+
+ // Overridden to ensure visiblity in tests
+ @Override
+ public javax.ws.rs.core.Response handleRequest(HttpHeaders headers, String body,
+ UriInfo uriInfo, Request.Type requestType,
+ MediaType mediaType, ResourceInstance resource) {
+ return super.handleRequest(headers, body, uriInfo, requestType, mediaType, resource);
+ }
}
public static class TestResource extends StackAdvisorResponse {
http://git-wip-us.apache.org/repos/asf/ambari/blob/e87ca3ce/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/StackAdvisorResourceProviderTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/StackAdvisorResourceProviderTest.java b/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/StackAdvisorResourceProviderTest.java
index ab60948..05232ea 100644
--- a/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/StackAdvisorResourceProviderTest.java
+++ b/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/StackAdvisorResourceProviderTest.java
@@ -27,43 +27,35 @@ import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
-import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
+import java.util.Iterator;
import java.util.LinkedHashSet;
-import java.util.List;
import java.util.Map;
import java.util.Set;
+import javax.annotation.Nonnull;
+
import org.apache.ambari.server.controller.AmbariManagementController;
import org.apache.ambari.server.controller.spi.Request;
import org.apache.ambari.server.controller.spi.Resource;
import org.junit.Assert;
+import org.junit.Before;
import org.junit.Test;
+import com.google.common.collect.Lists;
+
public class StackAdvisorResourceProviderTest {
+ private RecommendationResourceProvider provider;
+
@Test
public void testCalculateConfigurations() throws Exception {
-
- Map<Resource.Type, String> keyPropertyIds = Collections.emptyMap();
- Set<String> propertyIds = Collections.emptySet();
- AmbariManagementController ambariManagementController = mock(AmbariManagementController.class);
- RecommendationResourceProvider provider = new RecommendationResourceProvider(propertyIds,
- keyPropertyIds, ambariManagementController);
-
- Request request = mock(Request.class);
- Set<Map<String, Object>> propertiesSet = new HashSet<>();
- Map<String, Object> propertiesMap = new HashMap<>();
- propertiesMap.put(CONFIGURATIONS_PROPERTY_ID + "site/properties/string_prop", "string");
- List<Object> array = new ArrayList<>();
- array.add("array1");
- array.add("array2");
- propertiesMap.put(CONFIGURATIONS_PROPERTY_ID + "site/properties/array_prop", array);
- propertiesSet.add(propertiesMap);
-
- doReturn(propertiesSet).when(request).getProperties();
+ Request request = createMockRequest(
+ CONFIGURATIONS_PROPERTY_ID + "site/properties/string_prop", "string",
+ CONFIGURATIONS_PROPERTY_ID + "site/properties/array_prop", Lists.newArrayList("array1", "array2"));
Map<String, Map<String, Map<String, String>>> calculatedConfigurations = provider.calculateConfigurations(request);
@@ -79,27 +71,37 @@ public class StackAdvisorResourceProviderTest {
assertEquals("[array1, array2]", properties.get("array_prop"));
}
- @Test
- public void testReadUserContext() throws Exception {
-
+ @Nonnull
+ private RecommendationResourceProvider createRecommendationResourceProvider() {
Map<Resource.Type, String> keyPropertyIds = Collections.emptyMap();
Set<String> propertyIds = Collections.emptySet();
AmbariManagementController ambariManagementController = mock(AmbariManagementController.class);
- RecommendationResourceProvider provider = new RecommendationResourceProvider(propertyIds,
- keyPropertyIds, ambariManagementController);
+ return new RecommendationResourceProvider(propertyIds,
+ keyPropertyIds, ambariManagementController);
+ }
+ @Nonnull
+ private Request createMockRequest(Object... propertyKeysAndValues) {
Request request = mock(Request.class);
Set<Map<String, Object>> propertiesSet = new HashSet<>();
Map<String, Object> propertiesMap = new HashMap<>();
- propertiesMap.put(CONFIGURATIONS_PROPERTY_ID + "site/properties/string_prop", "string");
- List<Object> array = new ArrayList<>();
- array.add("array1");
- array.add("array2");
- propertiesMap.put(USER_CONTEXT_OPERATION_PROPERTY, "op1");
- propertiesMap.put(USER_CONTEXT_OPERATION_DETAILS_PROPERTY, "op_det");
+ Iterator<Object> it = Arrays.asList(propertyKeysAndValues).iterator();
+ while(it.hasNext()) {
+ String key = (String)it.next();
+ Object value = it.next();
+ propertiesMap.put(key, value);
+ }
propertiesSet.add(propertiesMap);
-
doReturn(propertiesSet).when(request).getProperties();
+ return request;
+ }
+
+ @Test
+ public void testReadUserContext() throws Exception {
+ Request request = createMockRequest(
+ CONFIGURATIONS_PROPERTY_ID + "site/properties/string_prop", "string",
+ USER_CONTEXT_OPERATION_PROPERTY, "op1",
+ USER_CONTEXT_OPERATION_DETAILS_PROPERTY, "op_det");
Map<String, String> userContext = provider.readUserContext(request);
@@ -111,24 +113,9 @@ public class StackAdvisorResourceProviderTest {
@Test
public void testCalculateConfigurationsWithNullPropertyValues() throws Exception {
-
- Map<Resource.Type, String> keyPropertyIds = Collections.emptyMap();
- Set<String> propertyIds = Collections.emptySet();
- AmbariManagementController ambariManagementController = mock(AmbariManagementController.class);
- RecommendationResourceProvider provider = new RecommendationResourceProvider(propertyIds,
- keyPropertyIds, ambariManagementController);
-
- Request request = mock(Request.class);
- Set<Map<String, Object>> propertiesSet = new HashSet<>();
- Map<String, Object> propertiesMap = new HashMap<>();
- propertiesMap.put(CONFIGURATIONS_PROPERTY_ID + "site/properties/string_prop", null); //null value means no value specified for the property
- List<Object> array = new ArrayList<>();
- array.add("array1");
- array.add("array2");
- propertiesMap.put(CONFIGURATIONS_PROPERTY_ID + "site/properties/array_prop", array);
- propertiesSet.add(propertiesMap);
-
- doReturn(propertiesSet).when(request).getProperties();
+ Request request = createMockRequest(
+ CONFIGURATIONS_PROPERTY_ID + "site/properties/string_prop", null,
+ CONFIGURATIONS_PROPERTY_ID + "site/properties/array_prop", Lists.newArrayList("array1", "array2"));
Map<String, Map<String, Map<String, String>>> calculatedConfigurations = provider.calculateConfigurations(request);
@@ -142,19 +129,18 @@ public class StackAdvisorResourceProviderTest {
assertEquals("[array1, array2]", properties.get("array_prop"));
-
// config properties with null values should be ignored
assertFalse(properties.containsKey("string_prop"));
-
}
+
@Test
public void testStackAdvisorWithEmptyHosts() {
Map<Resource.Type, String> keyPropertyIds = Collections.emptyMap();
Set<String> propertyIds = Collections.emptySet();
AmbariManagementController ambariManagementController = mock(AmbariManagementController.class);
RecommendationResourceProvider provider = new RecommendationResourceProvider(propertyIds,
- keyPropertyIds, ambariManagementController);
+ keyPropertyIds, ambariManagementController);
Request request = mock(Request.class);
Set<Map<String, Object>> propertiesSet = new HashSet<>();
@@ -170,4 +156,9 @@ public class StackAdvisorResourceProviderTest {
} catch (Exception e) {
}
}
+
+ @Before
+ public void init() {
+ provider = createRecommendationResourceProvider();
+ }
}
[26/33] ambari git commit: AMBARI-21307 added javadocs,
organized and cleaned the code
Posted by lp...@apache.org.
AMBARI-21307 added javadocs, organized and cleaned the code
Project: http://git-wip-us.apache.org/repos/asf/ambari/repo
Commit: http://git-wip-us.apache.org/repos/asf/ambari/commit/a15c4e5f
Tree: http://git-wip-us.apache.org/repos/asf/ambari/tree/a15c4e5f
Diff: http://git-wip-us.apache.org/repos/asf/ambari/diff/a15c4e5f
Branch: refs/heads/feature-branch-AMBARI-21307
Commit: a15c4e5fa8fea4c2c8f3962e191d84a1e7a1bfcd
Parents: dd99009
Author: lpuskas <lp...@apache.org>
Authored: Wed Sep 13 15:27:39 2017 +0200
Committer: lpuskas <lp...@apache.org>
Committed: Fri Oct 13 17:20:52 2017 +0200
----------------------------------------------------------------------
.../server/ldap/LdapConfigurationFactory.java | 13 +
.../server/ldap/LdapConfigurationService.java | 60 -----
.../apache/ambari/server/ldap/LdapModule.java | 6 +-
.../server/ldap/service/AmbariLdapFacade.java | 9 +-
.../server/ldap/service/AttributeDetector.java | 3 +-
.../ldap/service/LdapConfigurationService.java | 60 +++++
.../ambari/server/ldap/service/LdapFacade.java | 10 +-
.../ads/DefaultAttributeDetectionService.java | 238 -------------------
.../DefaultLdapAttributeDetectionService.java | 238 +++++++++++++++++++
.../ads/DefaultLdapConfigurationService.java | 17 +-
.../detectors/UserGroupMemberAttrDetector.java | 1 -
.../DefaultAttributeDetectionServiceTest.java | 108 ---------
...efaultLdapAttributeDetectionServiceTest.java | 108 +++++++++
.../DefaultLdapConfigurationServiceTest.java | 2 +-
14 files changed, 453 insertions(+), 420 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/ambari/blob/a15c4e5f/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationFactory.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationFactory.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationFactory.java
index 57cdf6e..67ac092 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationFactory.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationFactory.java
@@ -16,6 +16,19 @@ package org.apache.ambari.server.ldap;
import java.util.Map;
+/**
+ * Factory interface for AmbariLdapConfiguration instances.
+ * It's registered as a factory in the GUICE context ( so no implementations required)
+ *
+ * To be extended with other factory methods upon needs.
+ */
public interface LdapConfigurationFactory {
+
+ /**
+ * Creates an AmbariLdapConfiguration instance with the provided map of configuration settings.
+ *
+ * @param configuration a map where keys are the configuration properties and values are the configuration values
+ * @return an AmbariLdapConfiguration instance
+ */
AmbariLdapConfiguration createLdapConfiguration(Map<String, Object> configuration);
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/ambari/blob/a15c4e5f/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationService.java
deleted file mode 100644
index 69a641f..0000000
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationService.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.ambari.server.ldap;
-
-import java.util.Set;
-
-import org.apache.ambari.server.AmbariException;
-import org.apache.ambari.server.ldap.service.AmbariLdapException;
-import org.apache.directory.ldap.client.api.LdapConnection;
-
-/**
- * Collection of operations for validating ldap configuration.
- * It's intended to decouple implementations using different libraries.
- */
-public interface LdapConfigurationService {
-
- /**
- * Tests the connection based on the provided configuration.
- *
- * @param ldapConnection connection instance
- * @param configuration the ambari ldap configuration instance
- * @throws AmbariLdapException if the connection is not possible
- */
- void checkConnection(LdapConnection ldapConnection, AmbariLdapConfiguration configuration) throws AmbariLdapException;
-
-
- /**
- * Implements LDAP user related configuration settings validation logic.
- * Implementers communicate with the LDAP server (search, bind) to validate attributes in the provided configuration
- * instance
- *
- * @param ldapConnection connection instance used to connect to the LDAP server
- * @param testUserName the test username
- * @param testPassword the test password
- * @param configuration the available ldap configuration
- * @return The DN of the found user entry
- * @throws AmbariException if the connection couldn't be estabilisheds
- */
- String checkUserAttributes(LdapConnection ldapConnection, String testUserName, String testPassword, AmbariLdapConfiguration configuration) throws AmbariLdapException;
-
- /**
- * Checks whether the group related LDAP attributes in the configuration are correct.
- *
- * @throws AmbariException if the attributes are not valid
- */
- Set<String> checkGroupAttributes(LdapConnection ldapConnection, String userDn, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException;
-
-}
http://git-wip-us.apache.org/repos/asf/ambari/blob/a15c4e5f/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
index 5d6a698..0be69d4 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
@@ -18,9 +18,10 @@ package org.apache.ambari.server.ldap;
import org.apache.ambari.server.ldap.service.AmbariLdapConfigurationProvider;
import org.apache.ambari.server.ldap.service.AmbariLdapFacade;
import org.apache.ambari.server.ldap.service.LdapAttributeDetectionService;
+import org.apache.ambari.server.ldap.service.LdapConfigurationService;
import org.apache.ambari.server.ldap.service.LdapConnectionService;
import org.apache.ambari.server.ldap.service.LdapFacade;
-import org.apache.ambari.server.ldap.service.ads.DefaultAttributeDetectionService;
+import org.apache.ambari.server.ldap.service.ads.DefaultLdapAttributeDetectionService;
import org.apache.ambari.server.ldap.service.ads.DefaultLdapConfigurationService;
import org.apache.ambari.server.ldap.service.ads.DefaultLdapConnectionService;
@@ -37,8 +38,9 @@ public class LdapModule extends AbstractModule {
bind(LdapFacade.class).to(AmbariLdapFacade.class);
bind(LdapConfigurationService.class).to(DefaultLdapConfigurationService.class);
bind(LdapConnectionService.class).to(DefaultLdapConnectionService.class);
- bind(LdapAttributeDetectionService.class).to(DefaultAttributeDetectionService.class);
+ bind(LdapAttributeDetectionService.class).to(DefaultLdapAttributeDetectionService.class);
+ // this binding requires the JPA module!
bind(AmbariLdapConfiguration.class).toProvider(AmbariLdapConfigurationProvider.class);
install(new FactoryModuleBuilder().build(LdapConfigurationFactory.class));
http://git-wip-us.apache.org/repos/asf/ambari/blob/a15c4e5f/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
index 719bb7b..689a072 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
@@ -22,7 +22,6 @@ import javax.inject.Inject;
import javax.inject.Singleton;
import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
-import org.apache.ambari.server.ldap.LdapConfigurationService;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -32,9 +31,12 @@ public class AmbariLdapFacade implements LdapFacade {
private static final Logger LOGGER = LoggerFactory.getLogger(AmbariLdapFacade.class);
+ /**
+ * Additional parameters expected to be provided along with the configuration
+ */
private enum Parameters {
- TEST_USER_NAME("ldap.test.user.name"),
- TEST_USER_PASSWORD("ldap.test.user.password");
+ TEST_USER_NAME("ambari.ldap.test.user.name"),
+ TEST_USER_PASSWORD("ambari.ldap.test.user.password");
private String parameterKey;
@@ -68,6 +70,7 @@ public class AmbariLdapFacade implements LdapFacade {
LOGGER.info("Validating LDAP connection related configuration based on: {}", ambariLdapConfiguration);
connection = ldapConnectionService.getBoundLdapConnection(ambariLdapConfiguration);
+
ldapConfigurationService.checkConnection(connection, ambariLdapConfiguration);
LOGGER.info("Validating LDAP connection related configuration: SUCCESS");
http://git-wip-us.apache.org/repos/asf/ambari/blob/a15c4e5f/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AttributeDetector.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AttributeDetector.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AttributeDetector.java
index 3e20a6a..1b28148 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AttributeDetector.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AttributeDetector.java
@@ -16,7 +16,8 @@ package org.apache.ambari.server.ldap.service;
/**
* Operations for detecting LDAP related settings.
- * Attributes and values are detected based on a sample set of results returned from a search
+ * The basis for the attribute or value detection is a set of entries returned by a search operation.
+ * Individual attribute detector implementations are responsible for detecting a specific set of attributes or values
*/
public interface AttributeDetector<T> {
http://git-wip-us.apache.org/repos/asf/ambari/blob/a15c4e5f/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConfigurationService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConfigurationService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConfigurationService.java
new file mode 100644
index 0000000..06566cc
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConfigurationService.java
@@ -0,0 +1,60 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service;
+
+import java.util.Set;
+
+import org.apache.ambari.server.AmbariException;
+import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
+import org.apache.directory.ldap.client.api.LdapConnection;
+
+/**
+ * Collection of operations for validating ldap configuration.
+ * It's intended to decouple implementations using different libraries.
+ */
+public interface LdapConfigurationService {
+
+ /**
+ * Tests the connection based on the provided configuration.
+ *
+ * @param ldapConnection connection instance
+ * @param configuration the ambari ldap configuration instance
+ * @throws AmbariLdapException if the connection is not possible
+ */
+ void checkConnection(LdapConnection ldapConnection, AmbariLdapConfiguration configuration) throws AmbariLdapException;
+
+
+ /**
+ * Implements LDAP user related configuration settings validation logic.
+ * Implementers communicate with the LDAP server (search, bind) to validate attributes in the provided configuration
+ * instance
+ *
+ * @param ldapConnection connection instance used to connect to the LDAP server
+ * @param testUserName the test username
+ * @param testPassword the test password
+ * @param configuration the available ldap configuration
+ * @return The DN of the found user entry
+ * @throws AmbariException if the connection couldn't be estabilisheds
+ */
+ String checkUserAttributes(LdapConnection ldapConnection, String testUserName, String testPassword, AmbariLdapConfiguration configuration) throws AmbariLdapException;
+
+ /**
+ * Checks whether the group related LDAP attributes in the configuration are correct.
+ *
+ * @throws AmbariException if the attributes are not valid
+ */
+ Set<String> checkGroupAttributes(LdapConnection ldapConnection, String userDn, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException;
+
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/a15c4e5f/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java
index 6060d7f..3ae913c 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java
@@ -22,6 +22,9 @@ import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
/**
* The contract defining all the operations required by the application when communicating with an arbitrary LDAP server.
* This interface is intended to decouple LDAP specific details from the application.
+ *
+ * Any operation that requires interaction with an LDAP server from within Ambari should go through this interface.
+ * (LDAP)
*/
public interface LdapFacade {
@@ -35,9 +38,12 @@ public interface LdapFacade {
/**
- * Runs the user and group attribute detection algorithms
+ * Runs the user and group attribute detection algorithms.
+ * The method is not intended to be used as a coniguration factory, the returned instance may not be suitable for use.
*
- * @param ambariLdapConfiguration
+ * @param ambariLdapConfiguration partially filled configuration instance to be extended with detected properties
+ * @return a configuration instance, with properties filled with potentially correct values
+ * @throws AmbariLdapException
*/
AmbariLdapConfiguration detectAttributes(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException;
http://git-wip-us.apache.org/repos/asf/ambari/blob/a15c4e5f/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionService.java
deleted file mode 100644
index e5254b5..0000000
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionService.java
+++ /dev/null
@@ -1,238 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.ambari.server.ldap.service.ads;
-
-import javax.inject.Inject;
-import javax.inject.Singleton;
-
-import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
-import org.apache.ambari.server.ldap.service.AmbariLdapException;
-import org.apache.ambari.server.ldap.service.LdapAttributeDetectionService;
-import org.apache.ambari.server.ldap.service.ads.detectors.GroupMemberAttrDetector;
-import org.apache.ambari.server.ldap.service.ads.detectors.GroupNameAttrDetector;
-import org.apache.ambari.server.ldap.service.ads.detectors.GroupObjectClassDetector;
-import org.apache.ambari.server.ldap.service.ads.detectors.UserGroupMemberAttrDetector;
-import org.apache.ambari.server.ldap.service.ads.detectors.UserNameAttrDetector;
-import org.apache.ambari.server.ldap.service.ads.detectors.UserObjectClassDetector;
-import org.apache.directory.api.ldap.model.cursor.SearchCursor;
-import org.apache.directory.api.ldap.model.entry.Entry;
-import org.apache.directory.api.ldap.model.message.Response;
-import org.apache.directory.api.ldap.model.message.SearchRequest;
-import org.apache.directory.api.ldap.model.message.SearchRequestImpl;
-import org.apache.directory.api.ldap.model.message.SearchResultEntry;
-import org.apache.directory.api.ldap.model.message.SearchScope;
-import org.apache.directory.api.ldap.model.name.Dn;
-import org.apache.directory.api.util.Strings;
-import org.apache.directory.ldap.client.api.LdapConnection;
-import org.apache.directory.ldap.client.api.search.FilterBuilder;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-@Singleton
-public class DefaultAttributeDetectionService implements LdapAttributeDetectionService<LdapConnection> {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(DefaultAttributeDetectionService.class);
- private static final int SAMPLE_RESULT_SIZE = 50;
-
-
- @Inject
- private UserNameAttrDetector userNameAttrDetector;
-
- @Inject
- private UserObjectClassDetector userObjectClassDetector;
-
- @Inject
- private UserGroupMemberAttrDetector userGroupMemberAttrDetector;
-
- @Inject
- private GroupNameAttrDetector groupNameAttrDetector;
-
- @Inject
- private GroupObjectClassDetector groupObjectClassDetector;
-
- @Inject
- private GroupMemberAttrDetector groupMemberAttrDetector;
-
- @Inject
- public DefaultAttributeDetectionService() {
- }
-
- @Override
- public AmbariLdapConfiguration detectLdapUserAttributes(LdapConnection connection, AmbariLdapConfiguration ambariLdapConfiguration) {
- LOGGER.info("Detecting LDAP user attributes ...");
-
- // perform a search using the user search base
- if (Strings.isEmpty(ambariLdapConfiguration.userSearchBase())) {
- LOGGER.warn("No user search base provided");
- return ambariLdapConfiguration;
- }
-
- SearchCursor searchCursor = null;
-
- try {
-
- SearchRequest searchRequest = assembleUserSearchRequest(ambariLdapConfiguration);
-
- // do the search
- searchCursor = connection.search(searchRequest);
-
- int processedUserCnt = 0;
-
- while (searchCursor.next()) {
-
- if (processedUserCnt >= SAMPLE_RESULT_SIZE) {
- LOGGER.debug("The maximum count of results for attribute detection has exceeded. Quit user attribute detection.");
- break;
- }
-
- Response response = searchCursor.get();
- // process the SearchResultEntry
-
- if (response instanceof SearchResultEntry) {
- Entry resultEntry = ((SearchResultEntry) response).getEntry();
- LOGGER.info("Processing sample entry with dn: [{}]", resultEntry.getDn());
-
- userNameAttrDetector.collect(resultEntry);
- userObjectClassDetector.collect(resultEntry);
- userGroupMemberAttrDetector.collect(resultEntry);
-
- processedUserCnt++;
- }
- }
-
- ambariLdapConfiguration.setValueFor(AmbariLdapConfiguration.AmbariLdapConfig.USER_NAME_ATTRIBUTE, userNameAttrDetector.detect());
- ambariLdapConfiguration.setValueFor(AmbariLdapConfiguration.AmbariLdapConfig.USER_OBJECT_CLASS, userObjectClassDetector.detect());
- ambariLdapConfiguration.setValueFor(AmbariLdapConfiguration.AmbariLdapConfig.USER_GROUP_MEMBER_ATTRIBUTE, userGroupMemberAttrDetector.detect());
-
- LOGGER.info("Decorated ambari ldap config : [{}]", ambariLdapConfiguration);
-
- } catch (Exception e) {
-
- LOGGER.error("Ldap operation failed", e);
- } finally {
- // housekeeping
- if (null != searchCursor) {
- searchCursor.close();
- }
- }
-
- return ambariLdapConfiguration;
- }
-
-
- @Override
- public AmbariLdapConfiguration detectLdapGroupAttributes(LdapConnection connection, AmbariLdapConfiguration ambariLdapConfiguration) {
- LOGGER.info("Detecting LDAP group attributes ...");
-
- // perform a search using the user search base
- if (Strings.isEmpty(ambariLdapConfiguration.groupSearchBase())) {
- LOGGER.warn("No group search base provided");
- return ambariLdapConfiguration;
- }
-
- SearchCursor searchCursor = null;
-
- try {
- // todo should the bind operation be done in the facade?
- connection.bind(ambariLdapConfiguration.bindDn(), ambariLdapConfiguration.bindPassword());
-
- SearchRequest searchRequest = assembleGroupSearchRequest(ambariLdapConfiguration);
-
- // do the search
- searchCursor = connection.search(searchRequest);
-
- int processedGroupCnt = 0;
-
- while (searchCursor.next()) {
-
- if (processedGroupCnt >= SAMPLE_RESULT_SIZE) {
- LOGGER.debug("The maximum number of results for attribute detection has exceeded. Quit detection.");
- break;
- }
-
- Response response = searchCursor.get();
- // process the SearchResultEntry
-
- if (response instanceof SearchResultEntry) {
- Entry resultEntry = ((SearchResultEntry) response).getEntry();
- LOGGER.info("Processing sample entry with dn: [{}]", resultEntry.getDn());
-
- groupNameAttrDetector.collect(resultEntry);
- groupObjectClassDetector.collect(resultEntry);
- groupMemberAttrDetector.collect(resultEntry);
-
- processedGroupCnt++;
- }
- }
-
- ambariLdapConfiguration.setValueFor(AmbariLdapConfiguration.AmbariLdapConfig.GROUP_NAME_ATTRIBUTE, groupNameAttrDetector.detect());
- ambariLdapConfiguration.setValueFor(AmbariLdapConfiguration.AmbariLdapConfig.GROUP_OBJECT_CLASS, groupObjectClassDetector.detect());
- ambariLdapConfiguration.setValueFor(AmbariLdapConfiguration.AmbariLdapConfig.GROUP_MEMBER_ATTRIBUTE, groupMemberAttrDetector.detect());
-
- LOGGER.info("Decorated ambari ldap config : [{}]", ambariLdapConfiguration);
-
- } catch (Exception e) {
-
- LOGGER.error("Ldap operation failed", e);
- } finally {
- // housekeeping
- if (null != searchCursor) {
- searchCursor.close();
- }
- }
-
- return ambariLdapConfiguration;
- }
-
- private SearchRequest assembleUserSearchRequest(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
- try {
-
- SearchRequest req = new SearchRequestImpl();
- req.setScope(SearchScope.SUBTREE);
- req.addAttributes("*");
- req.setTimeLimit(0);
- req.setBase(new Dn(ambariLdapConfiguration.userSearchBase()));
- // the filter must be set!
- req.setFilter(FilterBuilder.present(ambariLdapConfiguration.dnAttribute()).toString());
-
- return req;
-
- } catch (Exception e) {
- LOGGER.error("Could not assemble ldap search request", e);
- throw new AmbariLdapException(e);
- }
- }
-
- private SearchRequest assembleGroupSearchRequest(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
- try {
-
- SearchRequest req = new SearchRequestImpl();
- req.setScope(SearchScope.SUBTREE);
- req.addAttributes("*");
- req.setTimeLimit(0);
- req.setBase(new Dn(ambariLdapConfiguration.groupSearchBase()));
- // the filter must be set!
- req.setFilter(FilterBuilder.present(ambariLdapConfiguration.dnAttribute()).toString());
-
- return req;
-
- } catch (Exception e) {
- LOGGER.error("Could not assemble ldap search request", e);
- throw new AmbariLdapException(e);
- }
- }
-
-
-}
http://git-wip-us.apache.org/repos/asf/ambari/blob/a15c4e5f/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionService.java
new file mode 100644
index 0000000..b499b65
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionService.java
@@ -0,0 +1,238 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service.ads;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.service.AmbariLdapException;
+import org.apache.ambari.server.ldap.service.LdapAttributeDetectionService;
+import org.apache.ambari.server.ldap.service.ads.detectors.GroupMemberAttrDetector;
+import org.apache.ambari.server.ldap.service.ads.detectors.GroupNameAttrDetector;
+import org.apache.ambari.server.ldap.service.ads.detectors.GroupObjectClassDetector;
+import org.apache.ambari.server.ldap.service.ads.detectors.UserGroupMemberAttrDetector;
+import org.apache.ambari.server.ldap.service.ads.detectors.UserNameAttrDetector;
+import org.apache.ambari.server.ldap.service.ads.detectors.UserObjectClassDetector;
+import org.apache.directory.api.ldap.model.cursor.SearchCursor;
+import org.apache.directory.api.ldap.model.entry.Entry;
+import org.apache.directory.api.ldap.model.message.Response;
+import org.apache.directory.api.ldap.model.message.SearchRequest;
+import org.apache.directory.api.ldap.model.message.SearchRequestImpl;
+import org.apache.directory.api.ldap.model.message.SearchResultEntry;
+import org.apache.directory.api.ldap.model.message.SearchScope;
+import org.apache.directory.api.ldap.model.name.Dn;
+import org.apache.directory.api.util.Strings;
+import org.apache.directory.ldap.client.api.LdapConnection;
+import org.apache.directory.ldap.client.api.search.FilterBuilder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Singleton
+public class DefaultLdapAttributeDetectionService implements LdapAttributeDetectionService<LdapConnection> {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(DefaultLdapAttributeDetectionService.class);
+ private static final int SAMPLE_RESULT_SIZE = 50;
+
+
+ @Inject
+ private UserNameAttrDetector userNameAttrDetector;
+
+ @Inject
+ private UserObjectClassDetector userObjectClassDetector;
+
+ @Inject
+ private UserGroupMemberAttrDetector userGroupMemberAttrDetector;
+
+ @Inject
+ private GroupNameAttrDetector groupNameAttrDetector;
+
+ @Inject
+ private GroupObjectClassDetector groupObjectClassDetector;
+
+ @Inject
+ private GroupMemberAttrDetector groupMemberAttrDetector;
+
+ @Inject
+ public DefaultLdapAttributeDetectionService() {
+ }
+
+ @Override
+ public AmbariLdapConfiguration detectLdapUserAttributes(LdapConnection connection, AmbariLdapConfiguration ambariLdapConfiguration) {
+ LOGGER.info("Detecting LDAP user attributes ...");
+
+ // perform a search using the user search base
+ if (Strings.isEmpty(ambariLdapConfiguration.userSearchBase())) {
+ LOGGER.warn("No user search base provided");
+ return ambariLdapConfiguration;
+ }
+
+ SearchCursor searchCursor = null;
+
+ try {
+
+ SearchRequest searchRequest = assembleUserSearchRequest(ambariLdapConfiguration);
+
+ // do the search
+ searchCursor = connection.search(searchRequest);
+
+ int processedUserCnt = 0;
+
+ while (searchCursor.next()) {
+
+ if (processedUserCnt >= SAMPLE_RESULT_SIZE) {
+ LOGGER.debug("The maximum count of results for attribute detection has exceeded. Quit user attribute detection.");
+ break;
+ }
+
+ Response response = searchCursor.get();
+ // process the SearchResultEntry
+
+ if (response instanceof SearchResultEntry) {
+ Entry resultEntry = ((SearchResultEntry) response).getEntry();
+ LOGGER.info("Processing sample entry with dn: [{}]", resultEntry.getDn());
+
+ userNameAttrDetector.collect(resultEntry);
+ userObjectClassDetector.collect(resultEntry);
+ userGroupMemberAttrDetector.collect(resultEntry);
+
+ processedUserCnt++;
+ }
+ }
+
+ ambariLdapConfiguration.setValueFor(AmbariLdapConfiguration.AmbariLdapConfig.USER_NAME_ATTRIBUTE, userNameAttrDetector.detect());
+ ambariLdapConfiguration.setValueFor(AmbariLdapConfiguration.AmbariLdapConfig.USER_OBJECT_CLASS, userObjectClassDetector.detect());
+ ambariLdapConfiguration.setValueFor(AmbariLdapConfiguration.AmbariLdapConfig.USER_GROUP_MEMBER_ATTRIBUTE, userGroupMemberAttrDetector.detect());
+
+ LOGGER.info("Decorated ambari ldap config : [{}]", ambariLdapConfiguration);
+
+ } catch (Exception e) {
+
+ LOGGER.error("Ldap operation failed", e);
+ } finally {
+ // housekeeping
+ if (null != searchCursor) {
+ searchCursor.close();
+ }
+ }
+
+ return ambariLdapConfiguration;
+ }
+
+
+ @Override
+ public AmbariLdapConfiguration detectLdapGroupAttributes(LdapConnection connection, AmbariLdapConfiguration ambariLdapConfiguration) {
+ LOGGER.info("Detecting LDAP group attributes ...");
+
+ // perform a search using the user search base
+ if (Strings.isEmpty(ambariLdapConfiguration.groupSearchBase())) {
+ LOGGER.warn("No group search base provided");
+ return ambariLdapConfiguration;
+ }
+
+ SearchCursor searchCursor = null;
+
+ try {
+ // todo should the bind operation be done in the facade?
+ connection.bind(ambariLdapConfiguration.bindDn(), ambariLdapConfiguration.bindPassword());
+
+ SearchRequest searchRequest = assembleGroupSearchRequest(ambariLdapConfiguration);
+
+ // do the search
+ searchCursor = connection.search(searchRequest);
+
+ int processedGroupCnt = 0;
+
+ while (searchCursor.next()) {
+
+ if (processedGroupCnt >= SAMPLE_RESULT_SIZE) {
+ LOGGER.debug("The maximum number of results for attribute detection has exceeded. Quit detection.");
+ break;
+ }
+
+ Response response = searchCursor.get();
+ // process the SearchResultEntry
+
+ if (response instanceof SearchResultEntry) {
+ Entry resultEntry = ((SearchResultEntry) response).getEntry();
+ LOGGER.info("Processing sample entry with dn: [{}]", resultEntry.getDn());
+
+ groupNameAttrDetector.collect(resultEntry);
+ groupObjectClassDetector.collect(resultEntry);
+ groupMemberAttrDetector.collect(resultEntry);
+
+ processedGroupCnt++;
+ }
+ }
+
+ ambariLdapConfiguration.setValueFor(AmbariLdapConfiguration.AmbariLdapConfig.GROUP_NAME_ATTRIBUTE, groupNameAttrDetector.detect());
+ ambariLdapConfiguration.setValueFor(AmbariLdapConfiguration.AmbariLdapConfig.GROUP_OBJECT_CLASS, groupObjectClassDetector.detect());
+ ambariLdapConfiguration.setValueFor(AmbariLdapConfiguration.AmbariLdapConfig.GROUP_MEMBER_ATTRIBUTE, groupMemberAttrDetector.detect());
+
+ LOGGER.info("Decorated ambari ldap config : [{}]", ambariLdapConfiguration);
+
+ } catch (Exception e) {
+
+ LOGGER.error("Ldap operation failed", e);
+ } finally {
+ // housekeeping
+ if (null != searchCursor) {
+ searchCursor.close();
+ }
+ }
+
+ return ambariLdapConfiguration;
+ }
+
+ private SearchRequest assembleUserSearchRequest(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
+ try {
+
+ SearchRequest req = new SearchRequestImpl();
+ req.setScope(SearchScope.SUBTREE);
+ req.addAttributes("*");
+ req.setTimeLimit(0);
+ req.setBase(new Dn(ambariLdapConfiguration.userSearchBase()));
+ // the filter must be set!
+ req.setFilter(FilterBuilder.present(ambariLdapConfiguration.dnAttribute()).toString());
+
+ return req;
+
+ } catch (Exception e) {
+ LOGGER.error("Could not assemble ldap search request", e);
+ throw new AmbariLdapException(e);
+ }
+ }
+
+ private SearchRequest assembleGroupSearchRequest(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
+ try {
+
+ SearchRequest req = new SearchRequestImpl();
+ req.setScope(SearchScope.SUBTREE);
+ req.addAttributes("*");
+ req.setTimeLimit(0);
+ req.setBase(new Dn(ambariLdapConfiguration.groupSearchBase()));
+ // the filter must be set!
+ req.setFilter(FilterBuilder.present(ambariLdapConfiguration.dnAttribute()).toString());
+
+ return req;
+
+ } catch (Exception e) {
+ LOGGER.error("Could not assemble ldap search request", e);
+ throw new AmbariLdapException(e);
+ }
+ }
+
+
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/a15c4e5f/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
index c90b5ac..0a309cd 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
@@ -21,8 +21,8 @@ import javax.inject.Inject;
import javax.inject.Singleton;
import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
-import org.apache.ambari.server.ldap.LdapConfigurationService;
import org.apache.ambari.server.ldap.service.AmbariLdapException;
+import org.apache.ambari.server.ldap.service.LdapConfigurationService;
import org.apache.directory.api.ldap.codec.decorators.SearchResultEntryDecorator;
import org.apache.directory.api.ldap.model.constants.SchemaConstants;
import org.apache.directory.api.ldap.model.cursor.EntryCursor;
@@ -63,7 +63,6 @@ public class DefaultLdapConfigurationService implements LdapConfigurationService
}
-
/**
* Checks the user attributes provided in the configuration instance by issuing a search for a (known) test user in the LDAP.
* Attributes are considered correct if there is at least one entry found.
@@ -73,7 +72,7 @@ public class DefaultLdapConfigurationService implements LdapConfigurationService
* @param ldapConnection connection instance used to connect to the LDAP server
* @param testUserName the test username
* @param testPassword the test password
- * @param ambariLdapConfiguration configuration instance holding ldap configuration details
+ * @param ambariLdapConfiguration the available LDAP configuration to be validated
* @return the DN of the test user
* @throws AmbariLdapException if an error occurs
*/
@@ -122,7 +121,16 @@ public class DefaultLdapConfigurationService implements LdapConfigurationService
return userDn;
}
-
+ /**
+ * Checks whether the provided group related settings are correct.
+ * The algorithm implemented in this method per
+ *
+ * @param ldapConnection a connecion instance bound to an LDAP server
+ * @param userDn a user DN to check
+ * @param ambariLdapConfiguration the available LDAP configuration to be validated
+ * @return
+ * @throws AmbariLdapException
+ */
@Override
public Set<String> checkGroupAttributes(LdapConnection ldapConnection, String userDn, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
SearchCursor searchCursor = null;
@@ -144,6 +152,7 @@ public class DefaultLdapConfigurationService implements LdapConfigurationService
searchRequest.setFilter(filter);
searchRequest.setBase(new Dn(ambariLdapConfiguration.groupSearchBase()));
searchRequest.setScope(SearchScope.SUBTREE);
+ // attributes to be returned
searchRequest.addAttributes(ambariLdapConfiguration.groupMemberAttribute(), ambariLdapConfiguration.groupNameAttribute());
// perform the search
http://git-wip-us.apache.org/repos/asf/ambari/blob/a15c4e5f/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserGroupMemberAttrDetector.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserGroupMemberAttrDetector.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserGroupMemberAttrDetector.java
index 913c2b6..a7f03dd 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserGroupMemberAttrDetector.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserGroupMemberAttrDetector.java
@@ -19,7 +19,6 @@ import javax.inject.Inject;
import org.apache.directory.api.ldap.model.entry.Entry;
public class UserGroupMemberAttrDetector extends OccurranceAndWeightBasedDetector {
- private static String[] userGroupMemAttrValues = {"memberOf", "ismemberOf"};
private enum UserGroupMemberAttr {
http://git-wip-us.apache.org/repos/asf/ambari/blob/a15c4e5f/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionServiceTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionServiceTest.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionServiceTest.java
deleted file mode 100644
index 9b03b86..0000000
--- a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionServiceTest.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.ambari.server.ldap.service.ads;
-
-
-import java.util.Map;
-
-import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
-import org.apache.ambari.server.ldap.service.LdapConnectionService;
-import org.apache.directory.api.ldap.model.constants.SchemaConstants;
-import org.apache.directory.ldap.client.api.LdapConnection;
-import org.easymock.EasyMockRule;
-import org.easymock.TestSubject;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.Maps;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-
-public class DefaultAttributeDetectionServiceTest {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(DefaultAttributeDetectionServiceTest.class);
-
- @Rule
- public EasyMockRule mocks = new EasyMockRule(this);
-
- private AmbariLdapConfiguration testLdapConfiguration;
- private LdapConnection connection;
-
- @TestSubject
- private DefaultAttributeDetectionService attributeDetectionService = new DefaultAttributeDetectionService();
-
- @Before
- public void before() {
-
- Map<String, Object> initialProps = Maps.newHashMap();
- initialProps.put(AmbariLdapConfiguration.AmbariLdapConfig.BIND_DN.key(), "");
- testLdapConfiguration = new AmbariLdapConfiguration(initialProps);
- }
-
- @Test
- public void testShouldUserNameAttributeBeDetectedWhenSearchReturnsValidUsers() throws Exception {
- // GIVEN
-// a set of entries returned from the LDAP search
-
- // WHEN
- AmbariLdapConfiguration ambariLdapConfiguration = attributeDetectionService.detectLdapUserAttributes(connection, testLdapConfiguration);
-
- // THEN
- Assert.assertNotNull(ambariLdapConfiguration);
- Assert.assertEquals("The username attribute is not the expected", "uid", ambariLdapConfiguration.userNameAttribute());
-
- }
-
-
- @Test
- public void functionalTest() throws Exception {
- // GIVEN
- AmbariLdapConfiguration ambariLdapConfiguration = new AmbariLdapConfiguration(getTestPropertiesMap());
- LdapConnectionService connectionService = new DefaultLdapConnectionService();
- LdapConnection ldapConnection = connectionService.createLdapConnection(ambariLdapConfiguration);
-
- // WHEN
- AmbariLdapConfiguration config = attributeDetectionService.detectLdapUserAttributes(ldapConnection, ambariLdapConfiguration);
- config = attributeDetectionService.detectLdapGroupAttributes(ldapConnection, ambariLdapConfiguration);
-
- Gson gson = new GsonBuilder().create();
- LOGGER.info(gson.toJson(config));
-
- // THEN
- ldapConnection.close();
-
- }
-
- private Map<String, Object> getTestPropertiesMap() {
- Map<String, Object> ldapPropsMap = Maps.newHashMap();
-
- ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.ANONYMOUS_BIND.key(), "true");
- ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.SERVER_HOST.key(), "ldap.forumsys.com");
- ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.SERVER_PORT.key(), "389");
- ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.BIND_DN.key(), "cn=read-only-admin,dc=example,dc=com");
- ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.BIND_PASSWORD.key(), "password");
- ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.DN_ATTRIBUTE.key(), SchemaConstants.CN_AT);
-
- ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.USER_SEARCH_BASE.key(), "dc=example,dc=com");
- ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.GROUP_SEARCH_BASE.key(), "dc=example,dc=com");
-
- return ldapPropsMap;
-
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/ambari/blob/a15c4e5f/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionServiceTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionServiceTest.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionServiceTest.java
new file mode 100644
index 0000000..3d335bf
--- /dev/null
+++ b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionServiceTest.java
@@ -0,0 +1,108 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service.ads;
+
+
+import java.util.Map;
+
+import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.service.LdapConnectionService;
+import org.apache.directory.api.ldap.model.constants.SchemaConstants;
+import org.apache.directory.ldap.client.api.LdapConnection;
+import org.easymock.EasyMockRule;
+import org.easymock.TestSubject;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.collect.Maps;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+public class DefaultLdapAttributeDetectionServiceTest {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(DefaultLdapAttributeDetectionServiceTest.class);
+
+ @Rule
+ public EasyMockRule mocks = new EasyMockRule(this);
+
+ private AmbariLdapConfiguration testLdapConfiguration;
+ private LdapConnection connection;
+
+ @TestSubject
+ private DefaultLdapAttributeDetectionService attributeDetectionService = new DefaultLdapAttributeDetectionService();
+
+ @Before
+ public void before() {
+
+ Map<String, Object> initialProps = Maps.newHashMap();
+ initialProps.put(AmbariLdapConfiguration.AmbariLdapConfig.BIND_DN.key(), "");
+ testLdapConfiguration = new AmbariLdapConfiguration(initialProps);
+ }
+
+ @Test
+ public void testShouldUserNameAttributeBeDetectedWhenSearchReturnsValidUsers() throws Exception {
+ // GIVEN
+// a set of entries returned from the LDAP search
+
+ // WHEN
+ AmbariLdapConfiguration ambariLdapConfiguration = attributeDetectionService.detectLdapUserAttributes(connection, testLdapConfiguration);
+
+ // THEN
+ Assert.assertNotNull(ambariLdapConfiguration);
+ Assert.assertEquals("The username attribute is not the expected", "uid", ambariLdapConfiguration.userNameAttribute());
+
+ }
+
+
+ @Test
+ public void functionalTest() throws Exception {
+ // GIVEN
+ AmbariLdapConfiguration ambariLdapConfiguration = new AmbariLdapConfiguration(getTestPropertiesMap());
+ LdapConnectionService connectionService = new DefaultLdapConnectionService();
+ LdapConnection ldapConnection = connectionService.createLdapConnection(ambariLdapConfiguration);
+
+ // WHEN
+ AmbariLdapConfiguration config = attributeDetectionService.detectLdapUserAttributes(ldapConnection, ambariLdapConfiguration);
+ config = attributeDetectionService.detectLdapGroupAttributes(ldapConnection, ambariLdapConfiguration);
+
+ Gson gson = new GsonBuilder().create();
+ LOGGER.info(gson.toJson(config));
+
+ // THEN
+ ldapConnection.close();
+
+ }
+
+ private Map<String, Object> getTestPropertiesMap() {
+ Map<String, Object> ldapPropsMap = Maps.newHashMap();
+
+ ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.ANONYMOUS_BIND.key(), "true");
+ ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.SERVER_HOST.key(), "ldap.forumsys.com");
+ ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.SERVER_PORT.key(), "389");
+ ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.BIND_DN.key(), "cn=read-only-admin,dc=example,dc=com");
+ ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.BIND_PASSWORD.key(), "password");
+ ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.DN_ATTRIBUTE.key(), SchemaConstants.CN_AT);
+
+ ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.USER_SEARCH_BASE.key(), "dc=example,dc=com");
+ ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.GROUP_SEARCH_BASE.key(), "dc=example,dc=com");
+
+ return ldapPropsMap;
+
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/ambari/blob/a15c4e5f/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java
index 1e69012..1ba6110 100644
--- a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java
+++ b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java
@@ -19,7 +19,7 @@ import static org.junit.Assert.assertNotNull;
import java.util.Map;
import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
-import org.apache.ambari.server.ldap.LdapConfigurationService;
+import org.apache.ambari.server.ldap.service.LdapConfigurationService;
import org.apache.ambari.server.ldap.service.LdapConnectionService;
import org.apache.directory.api.ldap.model.constants.SchemaConstants;
import org.apache.directory.api.ldap.model.cursor.EntryCursor;
[14/33] ambari git commit: AMBARI-21307 Add all known LDAP properties
to AmbariConfigurationEnum (benyoka)
Posted by lp...@apache.org.
AMBARI-21307 Add all known LDAP properties to AmbariConfigurationEnum (benyoka)
Project: http://git-wip-us.apache.org/repos/asf/ambari/repo
Commit: http://git-wip-us.apache.org/repos/asf/ambari/commit/12be8291
Tree: http://git-wip-us.apache.org/repos/asf/ambari/tree/12be8291
Diff: http://git-wip-us.apache.org/repos/asf/ambari/diff/12be8291
Branch: refs/heads/feature-branch-AMBARI-21307
Commit: 12be829194706b75404bb1ffd37e1c6d74740672
Parents: a5397e2
Author: Balazs Bence Sari <be...@apache.org>
Authored: Mon Sep 4 12:45:07 2017 +0200
Committer: lpuskas <lp...@apache.org>
Committed: Fri Oct 13 17:20:50 2017 +0200
----------------------------------------------------------------------
.../ambari/server/ldap/AmbariLdapConfiguration.java | 15 ++++++++++++++-
1 file changed, 14 insertions(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/ambari/blob/12be8291/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
index b1cbced..e913e77 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
@@ -40,22 +40,35 @@ public class AmbariLdapConfiguration {
USE_SSL("ambari.ldap.usessl"),
LDAP_SERVER_HOST("ambari.ldap.server.host"),
LDAP_SERVER_PORT("ambari.ldap.server.port"),
+ LDAP_TRUSTSTORE("ambari.ldap.truststore"),
LDAP_TRUSTSTORE_TYPE("ambari.ldap.truststore.type"),
LDAP_TRUSTSTORE_PATH("ambari.ldap.truststore.path"),
+ LDAP_TRUSTSTORE_PASSWORD("ambari.ldap.truststore.password"),
BASE_DN("ambari.ldap.bind.dn"),
+ REFERRAL("ambari.ldap.referral"),
+ PAGINATION_ENABLED("ambari.ldap.pagination.enabled"),
BIND_ANONIMOUSLY("ambari.ldap.bindanonymously"),
MANAGER_DN("ambari.ldap.managerdn"),
MANAGER_PASSWORD("ambari.ldap.managerpassword"),
USER_OBJECT_CLASS("ambari.ldap.user.object.class"),
USER_NAME_ATTRIBUTE("ambari.ldap.user.name.attribute"),
+ USER_NAME_FORCE_LOWERCASE("ambari.ldap.username.force.lowercase"),
USER_SEARCH_BASE("ambari.ldap.user.search.base"),
+ SYNC_USER_MEMBER_REPLACE_PATTERN("ambari.ldap.sync.user.member.replacepattern"),
+ SYNC_USER_MEMBER_FILTER("ambari.ldap.sync.user.member_filter"),
+ ADMIN_GROUP_MAPPING_RULES ("ambari.ldap.admin.group.mappingrules"),
GROUP_OBJECT_CLASS("ambari.ldap.group.object.class"),
GROUP_NAME_ATTRIBUTE("ambari.ldap.group.name.attribute"),
GROUP_MEMBER_ATTRIBUTE("ambari.ldap.group.member.attribute"),
GROUP_SEARCH_BASE("ambari.ldap.group.search.base"),
- DN_ATTRIBUTE("authentication.ldap.dnAttribute");
+ SYNC_GROUP_MEMBER_REPLACE_PATTERN("ambari.ldap.sync.group.member.replacepattern"),
+ SYNC_GROUP_MEMBER_FILTER("ambari.ldap.sync.group.member_filter"),
+ DN_ATTRIBUTE("authentication.ldap.dnAttribute"),
+
+ TEST_USER_NAME("ambari.ldap.test.user.name"),
+ TEST_USER_PASSWORD("ambari.ldap.test.user.password");
private String propertyName;
[15/33] ambari git commit: AMBARI-21307 AddedLDAP configuration
provider for loading and maintaining the LDAP configuration in the
application
Posted by lp...@apache.org.
AMBARI-21307 AddedLDAP configuration provider for loading and maintaining the LDAP configuration in the application
Project: http://git-wip-us.apache.org/repos/asf/ambari/repo
Commit: http://git-wip-us.apache.org/repos/asf/ambari/commit/a5397e2b
Tree: http://git-wip-us.apache.org/repos/asf/ambari/tree/a5397e2b
Diff: http://git-wip-us.apache.org/repos/asf/ambari/diff/a5397e2b
Branch: refs/heads/feature-branch-AMBARI-21307
Commit: a5397e2b91515bc75242112b13bdfd11715b2b24
Parents: 176356b
Author: lpuskas <lp...@apache.org>
Authored: Tue Aug 29 14:55:09 2017 +0200
Committer: lpuskas <lp...@apache.org>
Committed: Fri Oct 13 17:20:50 2017 +0200
----------------------------------------------------------------------
.../services/ldap/LdapConfigurationService.java | 1 +
.../AmbariConfigurationResourceProvider.java | 35 +++++-
.../ambari/server/events/AmbariEvent.java | 11 +-
.../events/AmbariLdapConfigChangedEvent.java | 37 ++++++
.../server/ldap/LdapConfigurationFactory.java | 2 +-
.../apache/ambari/server/ldap/LdapModule.java | 3 +
.../AmbariLdapConfigurationProvider.java | 114 +++++++++++++++++++
.../server/ldap/service/AmbariLdapFacade.java | 7 +-
.../server/orm/dao/AmbariConfigurationDAO.java | 48 ++++++++
.../orm/entities/AmbariConfigurationEntity.java | 4 +-
.../DefaultLdapConfigurationServiceTest.java | 10 +-
11 files changed, 260 insertions(+), 12 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/ambari/blob/a5397e2b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationService.java b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationService.java
index fc6bd41..1b8427b 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationService.java
@@ -82,6 +82,7 @@ public class LdapConfigurationService extends AmbariConfigurationService {
@Produces(MediaType.APPLICATION_JSON)
public Response validateConfiguration(LdapConfigurationRequest ldapConfigurationRequest) {
+ // check if the user is authorized to perform the operation
authorize();
Set<String> groups = Sets.newHashSet();
http://git-wip-us.apache.org/repos/asf/ambari/blob/a5397e2b/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AmbariConfigurationResourceProvider.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AmbariConfigurationResourceProvider.java b/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AmbariConfigurationResourceProvider.java
index 2302d8b..4f4cc70 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AmbariConfigurationResourceProvider.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AmbariConfigurationResourceProvider.java
@@ -35,6 +35,9 @@ import org.apache.ambari.server.controller.spi.ResourceAlreadyExistsException;
import org.apache.ambari.server.controller.spi.SystemException;
import org.apache.ambari.server.controller.spi.UnsupportedPropertyException;
import org.apache.ambari.server.controller.utilities.PredicateHelper;
+import org.apache.ambari.server.events.AmbariEvent;
+import org.apache.ambari.server.events.AmbariLdapConfigChangedEvent;
+import org.apache.ambari.server.events.publishers.AmbariEventPublisher;
import org.apache.ambari.server.orm.dao.AmbariConfigurationDAO;
import org.apache.ambari.server.orm.entities.AmbariConfigurationEntity;
import org.apache.ambari.server.orm.entities.ConfigurationBaseEntity;
@@ -113,6 +116,10 @@ public class AmbariConfigurationResourceProvider extends AbstractAuthorizedResou
@Inject
private AmbariConfigurationDAO ambariConfigurationDAO;
+ @Inject
+ private AmbariEventPublisher publisher;
+
+
private Gson gson;
@AssistedInject
@@ -142,7 +149,18 @@ public class AmbariConfigurationResourceProvider extends AbstractAuthorizedResou
}
LOGGER.info("Persisting new ambari configuration: {} ", ambariConfigurationEntity);
- ambariConfigurationDAO.create(ambariConfigurationEntity);
+
+ try {
+ ambariConfigurationDAO.create(ambariConfigurationEntity);
+ } catch (Exception e) {
+ LOGGER.error("Failed to create resource", e);
+ throw new ResourceAlreadyExistsException(e.getMessage());
+ }
+
+ // todo filter by configuration type
+ // notify subscribers about the configuration changes
+ publisher.publish(new AmbariLdapConfigChangedEvent(AmbariEvent.AmbariEventType.LDAP_CONFIG_CHANGED,
+ ambariConfigurationEntity.getId()));
return getRequestStatus(null);
}
@@ -183,6 +201,10 @@ public class AmbariConfigurationResourceProvider extends AbstractAuthorizedResou
}
+ // notify subscribers about the configuration changes
+ publisher.publish(new AmbariLdapConfigChangedEvent(AmbariEvent.AmbariEventType.LDAP_CONFIG_CHANGED, idFromRequest));
+
+
return getRequestStatus(null);
}
@@ -209,11 +231,15 @@ public class AmbariConfigurationResourceProvider extends AbstractAuthorizedResou
persistedEntity.getConfigurationBaseEntity().setConfigurationAttributes(entityFromRequest.getConfigurationBaseEntity().getConfigurationAttributes());
- ambariConfigurationDAO.create(persistedEntity);
+ ambariConfigurationDAO.update(persistedEntity);
} catch (AmbariException e) {
throw new NoSuchParentResourceException(e.getMessage());
}
+ publisher.publish(new AmbariLdapConfigChangedEvent(AmbariEvent.AmbariEventType.LDAP_CONFIG_CHANGED,
+ persistedEntity.getId()));
+
+
return getRequestStatus(null);
}
@@ -251,6 +277,11 @@ public class AmbariConfigurationResourceProvider extends AbstractAuthorizedResou
throw new AmbariException("There must be only one resource specified in the request");
}
+ // the configuration type must be set
+ if (getValueFromResourceProperties(ResourcePropertyId.TYPE, resourcePropertiesSet.iterator().next()) == null) {
+ throw new AmbariException("The configuration type must be set");
+ }
+
for (ResourcePropertyId resourcePropertyId : ResourcePropertyId.values()) {
Object requestValue = getValueFromResourceProperties(resourcePropertyId, resourcePropertiesSet.iterator().next());
http://git-wip-us.apache.org/repos/asf/ambari/blob/a5397e2b/ambari-server/src/main/java/org/apache/ambari/server/events/AmbariEvent.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/events/AmbariEvent.java b/ambari-server/src/main/java/org/apache/ambari/server/events/AmbariEvent.java
index 9a5ee79..0f9ff52 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/events/AmbariEvent.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/events/AmbariEvent.java
@@ -140,7 +140,13 @@ public abstract class AmbariEvent {
/**
* Local user has been created.
*/
- USER_CREATED;
+ USER_CREATED,
+
+ /**
+ * LDAP config changed event;
+ */
+ LDAP_CONFIG_CHANGED;
+
}
/**
@@ -151,8 +157,7 @@ public abstract class AmbariEvent {
/**
* Constructor.
*
- * @param eventType
- * the type of event (not {@code null}).
+ * @param eventType the type of event (not {@code null}).
*/
public AmbariEvent(AmbariEventType eventType) {
m_eventType = eventType;
http://git-wip-us.apache.org/repos/asf/ambari/blob/a5397e2b/ambari-server/src/main/java/org/apache/ambari/server/events/AmbariLdapConfigChangedEvent.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/events/AmbariLdapConfigChangedEvent.java b/ambari-server/src/main/java/org/apache/ambari/server/events/AmbariLdapConfigChangedEvent.java
new file mode 100644
index 0000000..48799d7
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/events/AmbariLdapConfigChangedEvent.java
@@ -0,0 +1,37 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.events;
+
+/**
+ * Event signaling the creation or changing of an LDAP configuration entry.
+ */
+public class AmbariLdapConfigChangedEvent extends AmbariEvent {
+
+ private Long configurationId;
+
+ /**
+ * Constructor.
+ *
+ * @param eventType the type of event (not {@code null}).
+ */
+ public AmbariLdapConfigChangedEvent(AmbariEventType eventType, Long configurationId) {
+ super(eventType);
+ this.configurationId = configurationId;
+ }
+
+ public Long getConfigurationId() {
+ return configurationId;
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/a5397e2b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationFactory.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationFactory.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationFactory.java
index bcd6e39..57cdf6e 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationFactory.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationFactory.java
@@ -18,4 +18,4 @@ import java.util.Map;
public interface LdapConfigurationFactory {
AmbariLdapConfiguration createLdapConfiguration(Map<String, Object> configuration);
-}
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/ambari/blob/a5397e2b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
index 3ae4587..81f2a44 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
@@ -15,6 +15,7 @@
package org.apache.ambari.server.ldap;
+import org.apache.ambari.server.ldap.service.AmbariLdapConfigurationProvider;
import org.apache.ambari.server.ldap.service.AmbariLdapFacade;
import org.apache.ambari.server.ldap.service.LdapConnectionService;
import org.apache.ambari.server.ldap.service.LdapFacade;
@@ -35,6 +36,8 @@ public class LdapModule extends AbstractModule {
bind(LdapConfigurationService.class).to(DefaultLdapConfigurationService.class);
bind(LdapConnectionService.class).to(DefaultLdapConnectionService.class);
+ bind(AmbariLdapConfiguration.class).toProvider(AmbariLdapConfigurationProvider.class);
+
install(new FactoryModuleBuilder().build(LdapConfigurationFactory.class));
}
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/a5397e2b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapConfigurationProvider.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapConfigurationProvider.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapConfigurationProvider.java
new file mode 100644
index 0000000..7f3e8a9
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapConfigurationProvider.java
@@ -0,0 +1,114 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service;
+
+import java.util.Map;
+import java.util.Set;
+
+import javax.inject.Inject;
+import javax.inject.Provider;
+import javax.inject.Singleton;
+
+import org.apache.ambari.server.events.AmbariLdapConfigChangedEvent;
+import org.apache.ambari.server.events.publishers.AmbariEventPublisher;
+import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
+import org.apache.ambari.server.orm.dao.AmbariConfigurationDAO;
+import org.apache.ambari.server.orm.entities.AmbariConfigurationEntity;
+import org.apache.ambari.server.security.authorization.AmbariLdapAuthenticationProvider;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.eventbus.Subscribe;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+/**
+ * Provider implementation for LDAP configurations. It needs to be registered in the related GUICE module as a provider
+ * It's responsible for managing LDAP configurations in the application.
+ * Whenever requested, this provider returns an AmbariLdapConfiguration which is always in sync with the persisted LDAP
+ * configuration resource.
+ *
+ * The provider receives notifications on CRUD operations related to the persisted resource and reloads the cached
+ * configuration instance accordingly.
+ */
+@Singleton
+public class AmbariLdapConfigurationProvider implements Provider<AmbariLdapConfiguration> {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(AmbariLdapAuthenticationProvider.class);
+ private AmbariLdapConfiguration instance;
+
+ @Inject
+ private AmbariEventPublisher publisher;
+
+ @Inject
+ private Provider<AmbariConfigurationDAO> ambariConfigurationDAOProvider;
+
+ private Gson gson = new GsonBuilder().create();
+
+ @Inject
+ public AmbariLdapConfigurationProvider() {
+ }
+
+ @Inject
+ void register() {
+ publisher.register(this);
+ }
+
+ @Override
+ public AmbariLdapConfiguration get() {
+ return instance != null ? instance : loadInstance(null);
+ }
+
+ /**
+ * Loads the AmbariLdapConfiguration from the database.
+ *
+ * @param configurationId the configuration id
+ * @return the AmbariLdapConfiguration instance
+ */
+ private AmbariLdapConfiguration loadInstance(Long configurationId) {
+ AmbariConfigurationEntity configEntity = null;
+
+ LOGGER.info("Loading LDAP configuration ...");
+ if (null != configurationId) {
+
+ LOGGER.debug("Reloading configuration based on the provied id: {}", configurationId);
+ configEntity = ambariConfigurationDAOProvider.get().findByPK(configurationId);
+
+ } else {
+
+ LOGGER.debug("Initial loading of the ldap configuration ...");
+ configEntity = ambariConfigurationDAOProvider.get().getLdapConfiguration();
+
+ }
+
+ if (configEntity != null) {
+ Set propertyMaps = gson.fromJson(configEntity.getConfigurationBaseEntity().getConfigurationData(), Set.class);
+ instance = new AmbariLdapConfiguration((Map<String, Object>) propertyMaps.iterator().next());
+ }
+
+ LOGGER.info("Loaded LDAP configuration instance: [ {} ]", instance);
+
+ return instance;
+ }
+
+ @Subscribe
+ public void ambariLdapConfigChanged(AmbariLdapConfigChangedEvent event) {
+ LOGGER.info("LDAP config changed event received: {}", event);
+ loadInstance(event.getConfigurationId());
+ LOGGER.info("Refreshed LDAP config instance.");
+ }
+
+
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/a5397e2b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
index 683ed43..90a5ba7 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
@@ -19,6 +19,7 @@ import java.util.Map;
import java.util.Set;
import javax.inject.Inject;
+import javax.inject.Provider;
import javax.inject.Singleton;
import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
@@ -54,6 +55,10 @@ public class AmbariLdapFacade implements LdapFacade {
@Inject
private LdapConnectionService ldapConnectionService;
+ //todo remove this, added for testing purposes only
+ @Inject
+ private Provider<AmbariLdapConfiguration> ambariLdapConfigurationProvider;
+
@Inject
public AmbariLdapFacade() {
}
@@ -75,7 +80,7 @@ public class AmbariLdapFacade implements LdapFacade {
@Override
public void detectAttributes(AmbariLdapConfiguration ambariLdapConfiguration) {
LOGGER.info("Detecting LDAP configuration attributes ...");
- throw new UnsupportedOperationException("Not yet implemented");
+ LOGGER.info("LDAP config: {}", ambariLdapConfigurationProvider.get());
}
@Override
http://git-wip-us.apache.org/repos/asf/ambari/blob/a5397e2b/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/AmbariConfigurationDAO.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/AmbariConfigurationDAO.java b/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/AmbariConfigurationDAO.java
index 5710a7f..83293ef 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/AmbariConfigurationDAO.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/AmbariConfigurationDAO.java
@@ -16,8 +16,13 @@ package org.apache.ambari.server.orm.dao;
import javax.inject.Inject;
import javax.inject.Singleton;
+import javax.persistence.EntityExistsException;
+import javax.persistence.EntityNotFoundException;
+import javax.persistence.TypedQuery;
import org.apache.ambari.server.orm.entities.AmbariConfigurationEntity;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import com.google.inject.persist.Transactional;
@@ -29,6 +34,8 @@ import com.google.inject.persist.Transactional;
@Singleton
public class AmbariConfigurationDAO extends CrudDAO<AmbariConfigurationEntity, Long> {
+ private static final Logger LOGGER = LoggerFactory.getLogger(AmbariConfigurationDAO.class);
+
@Inject
public AmbariConfigurationDAO() {
super(AmbariConfigurationEntity.class);
@@ -36,6 +43,47 @@ public class AmbariConfigurationDAO extends CrudDAO<AmbariConfigurationEntity, L
@Transactional
public void create(AmbariConfigurationEntity entity) {
+ // make sure only one LDAP config entry exists
+ if ("ldap-configuration".equals(entity.getConfigurationBaseEntity().getType())) {
+ AmbariConfigurationEntity ldapConfigEntity = getLdapConfiguration();
+ if (ldapConfigEntity != null) {
+ LOGGER.error("Only one LDAP configuration entry can exist!");
+ throw new EntityExistsException("LDAP configuration entity already exists!");
+ }
+ }
super.create(entity);
}
+
+
+ @Transactional
+ public void update(AmbariConfigurationEntity entity) {
+ if (entity.getId() == null || findByPK(entity.getId()) == null) {
+ String msg = String.format("The entity with id [ %s ] is not found", entity.getId());
+ LOGGER.debug(msg);
+ throw new EntityNotFoundException(msg);
+ }
+
+ // updating the existing entity
+ super.merge(entity);
+ entityManagerProvider.get().flush();
+ }
+
+ /**
+ * Returns the LDAP configuration from the database.
+ *
+ * @return the configuration entity
+ */
+ @Transactional
+ public AmbariConfigurationEntity getLdapConfiguration() {
+ LOGGER.info("Looking up the LDAP configuration ....");
+ AmbariConfigurationEntity ldapConfigEntity = null;
+
+ TypedQuery<AmbariConfigurationEntity> query = entityManagerProvider.get().createNamedQuery(
+ "AmbariConfigurationEntity.findByType", AmbariConfigurationEntity.class);
+ query.setParameter("typeName", "ldap-configuration");
+
+ ldapConfigEntity = daoUtils.selectSingle(query);
+ LOGGER.info("Returned entity: {} ", ldapConfigEntity);
+ return ldapConfigEntity;
+ }
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/a5397e2b/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/AmbariConfigurationEntity.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/AmbariConfigurationEntity.java b/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/AmbariConfigurationEntity.java
index 34fa221..c9f4695 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/AmbariConfigurationEntity.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/AmbariConfigurationEntity.java
@@ -29,8 +29,8 @@ import javax.persistence.Table;
@Table(name = "ambari_configuration")
@NamedQueries({
@NamedQuery(
- name = "AmbariConfigurationEntity.findAll",
- query = "select ace from AmbariConfigurationEntity ace")
+ name = "AmbariConfigurationEntity.findByType",
+ query = "select ace from AmbariConfigurationEntity ace where ace.configurationBaseEntity.type = :typeName")
})
public class AmbariConfigurationEntity {
http://git-wip-us.apache.org/repos/asf/ambari/blob/a5397e2b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java
index 2b7448e..b5978a5 100644
--- a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java
+++ b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java
@@ -28,6 +28,7 @@ import org.apache.directory.api.ldap.model.message.SearchScope;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.LdapConnectionConfig;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;
+import org.apache.directory.ldap.client.api.search.FilterBuilder;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -46,15 +47,18 @@ public class DefaultLdapConfigurationServiceTest {
// WHEN
LdapConnectionConfig config = new LdapConnectionConfig();
- config.setLdapHost("localhost");
+ config.setLdapHost("172.22.112.167");
config.setLdapPort(389);
LdapConnection connection = new LdapNetworkConnection(config);
// THEN
- connection.anonymousBind();
+ connection.bind("CN=Robert Levas,CN=Users,DC=HWQE,DC=HORTONWORKS,DC=COM", "Hadoop1234");
+ String filter = FilterBuilder.and(
+ FilterBuilder.equal(SchemaConstants.OBJECT_CLASS_AT, "person"),
+ FilterBuilder.equal("name", "User1 Levas")).toString();
- EntryCursor cursor = connection.search("dc=dev,dc=local", "(objectclass=*)", SearchScope.ONELEVEL);
+ EntryCursor cursor = connection.search("OU=levas,DC=hwqe,DC=hortonworks,DC=com", filter, SearchScope.SUBTREE);
for (Entry entry : cursor) {
assertNotNull(entry);
[06/33] ambari git commit: AMBARI-21307 Implemented PUT operation,
added unit tests
Posted by lp...@apache.org.
AMBARI-21307 Implemented PUT operation, added unit tests
Project: http://git-wip-us.apache.org/repos/asf/ambari/repo
Commit: http://git-wip-us.apache.org/repos/asf/ambari/commit/1e8cde47
Tree: http://git-wip-us.apache.org/repos/asf/ambari/tree/1e8cde47
Diff: http://git-wip-us.apache.org/repos/asf/ambari/diff/1e8cde47
Branch: refs/heads/feature-branch-AMBARI-21307
Commit: 1e8cde47d6c05b4b1310414f1dda92a4789e5730
Parents: 53b4627
Author: lpuskas <lp...@apache.org>
Authored: Thu Jul 13 16:20:58 2017 +0200
Committer: lpuskas <lp...@apache.org>
Committed: Fri Oct 13 17:20:48 2017 +0200
----------------------------------------------------------------------
.../services/AmbariConfigurationService.java | 89 ++++---
.../server/controller/ControllerModule.java | 2 +
.../controller/ResourceProviderFactory.java | 24 +-
.../AbstractControllerResourceProvider.java | 2 +
.../AmbariConfigurationResourceProvider.java | 88 +++++--
.../internal/DefaultProviderModule.java | 2 -
.../server/orm/dao/AmbariConfigurationDAO.java | 4 +
...AmbariConfigurationResourceProviderTest.java | 231 +++++++++++++++++++
8 files changed, 364 insertions(+), 78 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/ambari/blob/1e8cde47/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationService.java b/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationService.java
index 0c159b9..0632361 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationService.java
@@ -56,16 +56,10 @@ import io.swagger.annotations.ApiResponses;
* "data": [
* {
* "authentication.ldap.primaryUrl": "localhost:33389"
- * },
- * {
- * "authentication.ldap.secondaryUrl": "localhost:333"
- * },
- * {
+ "authentication.ldap.secondaryUrl": "localhost:333"
* "authentication.ldap.baseDn": "dc=ambari,dc=apache,dc=org"
- * }
- * // ......
- * ]
- * }
+ * // ......
+ * ]
* }
* </pre>
*/
@@ -74,7 +68,7 @@ import io.swagger.annotations.ApiResponses;
public class AmbariConfigurationService extends BaseService {
private static final String AMBARI_CONFIGURATION_REQUEST_TYPE =
- "org.apache.ambari.server.api.services.AmbariConfigurationRequestSwagger";
+ "org.apache.ambari.server.api.services.AmbariConfigurationRequestSwagger";
/**
* Creates an ambari configuration resource.
@@ -87,9 +81,9 @@ public class AmbariConfigurationService extends BaseService {
@POST
@Produces(MediaType.TEXT_PLAIN)
@ApiOperation(value = "Creates an ambari configuration resource",
- nickname = "AmbariConfigurationService#createAmbariConfiguration")
+ nickname = "AmbariConfigurationService#createAmbariConfiguration")
@ApiImplicitParams({
- @ApiImplicitParam(dataType = AMBARI_CONFIGURATION_REQUEST_TYPE, paramType = PARAM_TYPE_BODY)
+ @ApiImplicitParam(dataType = AMBARI_CONFIGURATION_REQUEST_TYPE, paramType = PARAM_TYPE_BODY)
})
@ApiResponses({
@ApiResponse(code = HttpStatus.SC_CREATED, message = MSG_SUCCESSFUL_OPERATION),
@@ -108,24 +102,24 @@ public class AmbariConfigurationService extends BaseService {
@GET
@Produces(MediaType.TEXT_PLAIN)
@ApiOperation(value = "Retrieve all ambari configuration resources",
- nickname = "AmbariConfigurationService#getAmbariConfigurations",
- notes = "Returns all Ambari configurations.",
- response = AmbariConfigurationResponseSwagger.class,
- responseContainer = RESPONSE_CONTAINER_LIST)
+ nickname = "AmbariConfigurationService#getAmbariConfigurations",
+ notes = "Returns all Ambari configurations.",
+ response = AmbariConfigurationResponseSwagger.class,
+ responseContainer = RESPONSE_CONTAINER_LIST)
@ApiImplicitParams({
- @ApiImplicitParam(name = QUERY_FIELDS, value = QUERY_FILTER_DESCRIPTION,
- defaultValue = "AmbariConfiguration/data, AmbariConfiguration/id, AmbariConfiguration/type",
- dataType = DATA_TYPE_STRING, paramType = PARAM_TYPE_QUERY),
- @ApiImplicitParam(name = QUERY_SORT, value = QUERY_SORT_DESCRIPTION,
- defaultValue = "AmbariConfiguration/id",
- dataType = DATA_TYPE_STRING, paramType = PARAM_TYPE_QUERY),
- @ApiImplicitParam(name = QUERY_PAGE_SIZE, value = QUERY_PAGE_SIZE_DESCRIPTION, defaultValue = DEFAULT_PAGE_SIZE, dataType = DATA_TYPE_INT, paramType = PARAM_TYPE_QUERY),
- @ApiImplicitParam(name = QUERY_FROM, value = QUERY_FROM_DESCRIPTION, defaultValue = DEFAULT_FROM, dataType = DATA_TYPE_STRING, paramType = PARAM_TYPE_QUERY),
- @ApiImplicitParam(name = QUERY_TO, value = QUERY_TO_DESCRIPTION, dataType = DATA_TYPE_STRING, paramType = PARAM_TYPE_QUERY)
+ @ApiImplicitParam(name = QUERY_FIELDS, value = QUERY_FILTER_DESCRIPTION,
+ defaultValue = "AmbariConfiguration/data, AmbariConfiguration/id, AmbariConfiguration/type",
+ dataType = DATA_TYPE_STRING, paramType = PARAM_TYPE_QUERY),
+ @ApiImplicitParam(name = QUERY_SORT, value = QUERY_SORT_DESCRIPTION,
+ defaultValue = "AmbariConfiguration/id",
+ dataType = DATA_TYPE_STRING, paramType = PARAM_TYPE_QUERY),
+ @ApiImplicitParam(name = QUERY_PAGE_SIZE, value = QUERY_PAGE_SIZE_DESCRIPTION, defaultValue = DEFAULT_PAGE_SIZE, dataType = DATA_TYPE_INT, paramType = PARAM_TYPE_QUERY),
+ @ApiImplicitParam(name = QUERY_FROM, value = QUERY_FROM_DESCRIPTION, defaultValue = DEFAULT_FROM, dataType = DATA_TYPE_STRING, paramType = PARAM_TYPE_QUERY),
+ @ApiImplicitParam(name = QUERY_TO, value = QUERY_TO_DESCRIPTION, dataType = DATA_TYPE_STRING, paramType = PARAM_TYPE_QUERY)
})
@ApiResponses(value = {
- @ApiResponse(code = HttpStatus.SC_OK, message = MSG_SUCCESSFUL_OPERATION),
- @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = MSG_SERVER_ERROR)
+ @ApiResponse(code = HttpStatus.SC_OK, message = MSG_SUCCESSFUL_OPERATION),
+ @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = MSG_SERVER_ERROR)
})
public Response getAmbariConfigurations(String body, @Context HttpHeaders headers, @Context UriInfo uri) {
return handleRequest(headers, body, uri, Request.Type.GET, createResource(Resource.Type.AmbariConfiguration,
@@ -136,16 +130,16 @@ public class AmbariConfigurationService extends BaseService {
@Path("{configurationId}")
@Produces(MediaType.TEXT_PLAIN)
@ApiOperation(value = "Retrieve the details of an ambari configuration resource",
- nickname = "AmbariConfigurationService#getAmbariConfiguration",
- response = AmbariConfigurationResponseSwagger.class)
+ nickname = "AmbariConfigurationService#getAmbariConfiguration",
+ response = AmbariConfigurationResponseSwagger.class)
@ApiImplicitParams({
- @ApiImplicitParam(name = QUERY_FIELDS, value = QUERY_FILTER_DESCRIPTION, defaultValue = "AmbariConfiguration/*",
- dataType = DATA_TYPE_STRING, paramType = PARAM_TYPE_QUERY)
+ @ApiImplicitParam(name = QUERY_FIELDS, value = QUERY_FILTER_DESCRIPTION, defaultValue = "AmbariConfiguration/*",
+ dataType = DATA_TYPE_STRING, paramType = PARAM_TYPE_QUERY)
})
@ApiResponses(value = {
- @ApiResponse(code = HttpStatus.SC_OK, message = MSG_SUCCESSFUL_OPERATION),
- @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = MSG_RESOURCE_NOT_FOUND),
- @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = MSG_SERVER_ERROR)
+ @ApiResponse(code = HttpStatus.SC_OK, message = MSG_SUCCESSFUL_OPERATION),
+ @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = MSG_RESOURCE_NOT_FOUND),
+ @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = MSG_SERVER_ERROR)
})
public Response getAmbariConfiguration(String body, @Context HttpHeaders headers, @Context UriInfo uri,
@PathParam("configurationId") String configurationId) {
@@ -154,30 +148,35 @@ public class AmbariConfigurationService extends BaseService {
}
@PUT
+ @Path("{configurationId}")
@Produces(MediaType.TEXT_PLAIN)
@ApiOperation(value = "Updates ambari configuration resources - Not implemented yet",
nickname = "AmbariConfigurationService#updateAmbariConfiguration")
@ApiImplicitParams({
- @ApiImplicitParam(dataType = AMBARI_CONFIGURATION_REQUEST_TYPE, paramType = PARAM_TYPE_BODY)
+ @ApiImplicitParam(dataType = AMBARI_CONFIGURATION_REQUEST_TYPE, paramType = PARAM_TYPE_BODY),
+ @ApiImplicitParam(name = QUERY_FIELDS, value = QUERY_FILTER_DESCRIPTION, defaultValue = "AmbariConfiguration/*",
+ dataType = DATA_TYPE_STRING, paramType = PARAM_TYPE_QUERY)
})
@ApiResponses({
- @ApiResponse(code = HttpStatus.SC_OK, message = MSG_SUCCESSFUL_OPERATION),
- @ApiResponse(code = HttpStatus.SC_ACCEPTED, message = MSG_REQUEST_ACCEPTED),
- @ApiResponse(code = HttpStatus.SC_BAD_REQUEST, message = MSG_INVALID_ARGUMENTS),
- @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = MSG_RESOURCE_NOT_FOUND),
- @ApiResponse(code = HttpStatus.SC_UNAUTHORIZED, message = MSG_NOT_AUTHENTICATED),
- @ApiResponse(code = HttpStatus.SC_FORBIDDEN, message = MSG_PERMISSION_DENIED),
- @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = MSG_SERVER_ERROR),
+ @ApiResponse(code = HttpStatus.SC_OK, message = MSG_SUCCESSFUL_OPERATION),
+ @ApiResponse(code = HttpStatus.SC_ACCEPTED, message = MSG_REQUEST_ACCEPTED),
+ @ApiResponse(code = HttpStatus.SC_BAD_REQUEST, message = MSG_INVALID_ARGUMENTS),
+ @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = MSG_RESOURCE_NOT_FOUND),
+ @ApiResponse(code = HttpStatus.SC_UNAUTHORIZED, message = MSG_NOT_AUTHENTICATED),
+ @ApiResponse(code = HttpStatus.SC_FORBIDDEN, message = MSG_PERMISSION_DENIED),
+ @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = MSG_SERVER_ERROR),
})
- public Response updateAmbariConfiguration() {
- throw new UnsupportedOperationException("Not yet implemented");
+ public Response updateAmbariConfiguration(String body, @Context HttpHeaders headers, @Context UriInfo uri,
+ @PathParam("configurationId") String configurationId) {
+ return handleRequest(headers, body, uri, Request.Type.PUT, createResource(Resource.Type.AmbariConfiguration,
+ Collections.singletonMap(Resource.Type.AmbariConfiguration, configurationId)));
}
@DELETE
@Path("{configurationId}")
@Produces(MediaType.TEXT_PLAIN)
@ApiOperation(value = "Deletes an ambari configuration resource",
- nickname = "AmbariConfigurationService#deleteAmbariConfiguration")
+ nickname = "AmbariConfigurationService#deleteAmbariConfiguration")
@ApiResponses({
@ApiResponse(code = HttpStatus.SC_OK, message = MSG_SUCCESSFUL_OPERATION),
@ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = MSG_RESOURCE_NOT_FOUND),
http://git-wip-us.apache.org/repos/asf/ambari/blob/1e8cde47/ambari-server/src/main/java/org/apache/ambari/server/controller/ControllerModule.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/controller/ControllerModule.java b/ambari-server/src/main/java/org/apache/ambari/server/controller/ControllerModule.java
index dc97871..b79d122 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/controller/ControllerModule.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/controller/ControllerModule.java
@@ -62,6 +62,7 @@ import org.apache.ambari.server.cleanup.ClasspathScannerUtils;
import org.apache.ambari.server.configuration.Configuration;
import org.apache.ambari.server.configuration.Configuration.ConnectionPoolType;
import org.apache.ambari.server.configuration.Configuration.DatabaseType;
+import org.apache.ambari.server.controller.internal.AmbariConfigurationResourceProvider;
import org.apache.ambari.server.controller.internal.AlertTargetResourceProvider;
import org.apache.ambari.server.controller.internal.ClusterStackVersionResourceProvider;
import org.apache.ambari.server.controller.internal.ComponentResourceProvider;
@@ -470,6 +471,7 @@ public class ControllerModule extends AbstractModule {
.implement(ResourceProvider.class, Names.named("credential"), CredentialResourceProvider.class)
.implement(ResourceProvider.class, Names.named("kerberosDescriptor"), KerberosDescriptorResourceProvider.class)
.implement(ResourceProvider.class, Names.named("upgrade"), UpgradeResourceProvider.class)
+ .implement(ResourceProvider.class, Names.named("ambariConfiguration"), AmbariConfigurationResourceProvider.class)
.implement(ResourceProvider.class, Names.named("clusterStackVersion"), ClusterStackVersionResourceProvider.class)
.implement(ResourceProvider.class, Names.named("alertTarget"), AlertTargetResourceProvider.class)
.implement(ResourceProvider.class, Names.named("viewInstance"), ViewInstanceResourceProvider.class)
http://git-wip-us.apache.org/repos/asf/ambari/blob/1e8cde47/ambari-server/src/main/java/org/apache/ambari/server/controller/ResourceProviderFactory.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/controller/ResourceProviderFactory.java b/ambari-server/src/main/java/org/apache/ambari/server/controller/ResourceProviderFactory.java
index a198775..711ae10 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/controller/ResourceProviderFactory.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/controller/ResourceProviderFactory.java
@@ -22,6 +22,8 @@ package org.apache.ambari.server.controller;
import java.util.Map;
import java.util.Set;
+import javax.inject.Named;
+
import org.apache.ambari.server.controller.internal.AlertTargetResourceProvider;
import org.apache.ambari.server.controller.internal.ClusterStackVersionResourceProvider;
import org.apache.ambari.server.controller.internal.UpgradeResourceProvider;
@@ -30,18 +32,15 @@ import org.apache.ambari.server.controller.spi.Resource;
import org.apache.ambari.server.controller.spi.Resource.Type;
import org.apache.ambari.server.controller.spi.ResourceProvider;
-import com.google.inject.name.Named;
public interface ResourceProviderFactory {
@Named("host")
- ResourceProvider getHostResourceProvider(Set<String> propertyIds,
- Map<Type, String> keyPropertyIds,
- AmbariManagementController managementController);
+ ResourceProvider getHostResourceProvider(Set<String> propertyIds, Map<Type, String> keyPropertyIds,
+ AmbariManagementController managementController);
@Named("hostComponent")
- ResourceProvider getHostComponentResourceProvider(Set<String> propertyIds,
- Map<Type, String> keyPropertyIds,
- AmbariManagementController managementController);
+ ResourceProvider getHostComponentResourceProvider(Set<String> propertyIds, Map<Type, String> keyPropertyIds,
+ AmbariManagementController managementController);
@Named("service")
ResourceProvider getServiceResourceProvider(AmbariManagementController managementController);
@@ -50,9 +49,8 @@ public interface ResourceProviderFactory {
ResourceProvider getComponentResourceProvider(AmbariManagementController managementController);
@Named("member")
- ResourceProvider getMemberResourceProvider(Set<String> propertyIds,
- Map<Type, String> keyPropertyIds,
- AmbariManagementController managementController);
+ ResourceProvider getMemberResourceProvider(Set<String> propertyIds, Map<Type, String> keyPropertyIds,
+ AmbariManagementController managementController);
@Named("hostKerberosIdentity")
ResourceProvider getHostKerberosIdentityResourceProvider(AmbariManagementController managementController);
@@ -64,13 +62,15 @@ public interface ResourceProviderFactory {
ResourceProvider getRepositoryVersionResourceProvider();
@Named("kerberosDescriptor")
- ResourceProvider getKerberosDescriptorResourceProvider(AmbariManagementController managementController,
- Set<String> propertyIds,
+ ResourceProvider getKerberosDescriptorResourceProvider(AmbariManagementController managementController, Set<String> propertyIds,
Map<Resource.Type, String> keyPropertyIds);
@Named("upgrade")
UpgradeResourceProvider getUpgradeResourceProvider(AmbariManagementController managementController);
+ @Named("ambariConfiguration")
+ ResourceProvider getAmbariConfigurationResourceProvider();
+
@Named("clusterStackVersion")
ClusterStackVersionResourceProvider getClusterStackVersionResourceProvider(AmbariManagementController managementController);
http://git-wip-us.apache.org/repos/asf/ambari/blob/1e8cde47/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AbstractControllerResourceProvider.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AbstractControllerResourceProvider.java b/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AbstractControllerResourceProvider.java
index a98ad46..1dc0841 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AbstractControllerResourceProvider.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AbstractControllerResourceProvider.java
@@ -254,6 +254,8 @@ public abstract class AbstractControllerResourceProvider extends AbstractAuthori
return new ClusterKerberosDescriptorResourceProvider(managementController);
case LoggingQuery:
return new LoggingResourceProvider(propertyIds, keyPropertyIds, managementController);
+ case AmbariConfiguration:
+ return resourceProviderFactory.getAmbariConfigurationResourceProvider();
case AlertTarget:
return resourceProviderFactory.getAlertTargetResourceProvider();
case ViewInstance:
http://git-wip-us.apache.org/repos/asf/ambari/blob/1e8cde47/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AmbariConfigurationResourceProvider.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AmbariConfigurationResourceProvider.java b/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AmbariConfigurationResourceProvider.java
index e8f186d..2302d8b 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AmbariConfigurationResourceProvider.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AmbariConfigurationResourceProvider.java
@@ -25,7 +25,6 @@ import java.util.Set;
import javax.inject.Inject;
import org.apache.ambari.server.AmbariException;
-import org.apache.ambari.server.StaticallyInject;
import org.apache.ambari.server.controller.spi.NoSuchParentResourceException;
import org.apache.ambari.server.controller.spi.NoSuchResourceException;
import org.apache.ambari.server.controller.spi.Predicate;
@@ -46,11 +45,11 @@ import org.slf4j.LoggerFactory;
import com.google.common.collect.Sets;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
+import com.google.inject.assistedinject.AssistedInject;
/**
* Resource provider for AmbariConfiguration resources.
*/
-@StaticallyInject
public class AmbariConfigurationResourceProvider extends AbstractAuthorizedResourceProvider {
private static final Logger LOGGER = LoggerFactory.getLogger(AmbariConfigurationResourceProvider.class);
@@ -60,7 +59,7 @@ public class AmbariConfigurationResourceProvider extends AbstractAuthorizedResou
/**
* Resource property id constants.
*/
- private enum ResourcePropertyId {
+ public enum ResourcePropertyId {
ID("AmbariConfiguration/id"),
TYPE("AmbariConfiguration/type"),
@@ -112,11 +111,12 @@ public class AmbariConfigurationResourceProvider extends AbstractAuthorizedResou
@Inject
- private static AmbariConfigurationDAO ambariConfigurationDAO;
+ private AmbariConfigurationDAO ambariConfigurationDAO;
private Gson gson;
- protected AmbariConfigurationResourceProvider() {
+ @AssistedInject
+ public AmbariConfigurationResourceProvider() {
super(PROPERTIES, PK_PROPERTY_MAP);
setRequiredCreateAuthorizations(EnumSet.of(RoleAuthorization.AMBARI_MANAGE_CONFIGURATION));
setRequiredDeleteAuthorizations(EnumSet.of(RoleAuthorization.AMBARI_MANAGE_CONFIGURATION));
@@ -134,7 +134,12 @@ public class AmbariConfigurationResourceProvider extends AbstractAuthorizedResou
ResourceAlreadyExistsException, NoSuchParentResourceException {
LOGGER.info("Creating new ambari configuration resource ...");
- AmbariConfigurationEntity ambariConfigurationEntity = getEntityFromRequest(request);
+ AmbariConfigurationEntity ambariConfigurationEntity = null;
+ try {
+ ambariConfigurationEntity = getEntityFromRequest(request);
+ } catch (AmbariException e) {
+ throw new NoSuchParentResourceException(e.getMessage());
+ }
LOGGER.info("Persisting new ambari configuration: {} ", ambariConfigurationEntity);
ambariConfigurationDAO.create(ambariConfigurationEntity);
@@ -148,6 +153,7 @@ public class AmbariConfigurationResourceProvider extends AbstractAuthorizedResou
UnsupportedPropertyException, NoSuchResourceException, NoSuchParentResourceException {
Set<Resource> resources = Sets.newHashSet();
+ // retrieves allconfigurations, filtering is done at a higher level
List<AmbariConfigurationEntity> ambariConfigurationEntities = ambariConfigurationDAO.findAll();
for (AmbariConfigurationEntity ambariConfigurationEntity : ambariConfigurationEntities) {
try {
@@ -181,40 +187,86 @@ public class AmbariConfigurationResourceProvider extends AbstractAuthorizedResou
}
+ @Override
+ protected RequestStatus updateResourcesAuthorized(Request request, Predicate predicate) throws SystemException,
+ UnsupportedPropertyException, NoSuchResourceException, NoSuchParentResourceException {
+ Long idFromRequest = Long.valueOf((String) PredicateHelper.getProperties(predicate).get(ResourcePropertyId.ID.getPropertyId()));
+
+ AmbariConfigurationEntity persistedEntity = ambariConfigurationDAO.findByPK(idFromRequest);
+ if (persistedEntity == null) {
+ String errorMsg = String.format("Entity with primary key [ %s ] not found in the database.", idFromRequest);
+ LOGGER.error(errorMsg);
+ throw new NoSuchResourceException(errorMsg);
+ }
+
+ try {
+
+ AmbariConfigurationEntity entityFromRequest = getEntityFromRequest(request);
+ persistedEntity.getConfigurationBaseEntity().setVersionTag(entityFromRequest.getConfigurationBaseEntity().getVersionTag());
+ persistedEntity.getConfigurationBaseEntity().setVersion(entityFromRequest.getConfigurationBaseEntity().getVersion());
+ persistedEntity.getConfigurationBaseEntity().setType(entityFromRequest.getConfigurationBaseEntity().getType());
+ persistedEntity.getConfigurationBaseEntity().setConfigurationData(entityFromRequest.getConfigurationBaseEntity().getConfigurationData());
+ persistedEntity.getConfigurationBaseEntity().setConfigurationAttributes(entityFromRequest.getConfigurationBaseEntity().getConfigurationAttributes());
+
+
+ ambariConfigurationDAO.create(persistedEntity);
+ } catch (AmbariException e) {
+ throw new NoSuchParentResourceException(e.getMessage());
+ }
+
+ return getRequestStatus(null);
+
+ }
+
private Resource toResource(AmbariConfigurationEntity entity, Set<String> requestedIds) throws AmbariException {
+
+ if (null == entity) {
+ throw new IllegalArgumentException("Null entity can't be transformed into a resource");
+ }
+
+ if (null == entity.getConfigurationBaseEntity()) {
+ throw new IllegalArgumentException("Invalid configuration entity can't be transformed into a resource");
+ }
Resource resource = new ResourceImpl(Resource.Type.AmbariConfiguration);
Set<Map<String, String>> configurationSet = gson.fromJson(entity.getConfigurationBaseEntity().getConfigurationData(), Set.class);
setResourceProperty(resource, ResourcePropertyId.ID.getPropertyId(), entity.getId(), requestedIds);
setResourceProperty(resource, ResourcePropertyId.TYPE.getPropertyId(), entity.getConfigurationBaseEntity().getType(), requestedIds);
setResourceProperty(resource, ResourcePropertyId.DATA.getPropertyId(), configurationSet, requestedIds);
+ setResourceProperty(resource, ResourcePropertyId.VERSION.getPropertyId(), entity.getConfigurationBaseEntity().getVersion(), requestedIds);
+ setResourceProperty(resource, ResourcePropertyId.VERSION_TAG.getPropertyId(), entity.getConfigurationBaseEntity().getVersionTag(), requestedIds);
return resource;
}
- private AmbariConfigurationEntity getEntityFromRequest(Request request) {
+ private AmbariConfigurationEntity getEntityFromRequest(Request request) throws AmbariException {
AmbariConfigurationEntity ambariConfigurationEntity = new AmbariConfigurationEntity();
ambariConfigurationEntity.setConfigurationBaseEntity(new ConfigurationBaseEntity());
+ // set of resource properties (eache entry in the set belongs to a different resource)
+ Set<Map<String, Object>> resourcePropertiesSet = request.getProperties();
+
+ if (resourcePropertiesSet.size() != 1) {
+ throw new AmbariException("There must be only one resource specified in the request");
+ }
+
for (ResourcePropertyId resourcePropertyId : ResourcePropertyId.values()) {
- Object requestValue = getValueFromRequest(resourcePropertyId, request);
+ Object requestValue = getValueFromResourceProperties(resourcePropertyId, resourcePropertiesSet.iterator().next());
switch (resourcePropertyId) {
case DATA:
if (requestValue == null) {
throw new IllegalArgumentException("No configuration data is provided in the request");
}
-
ambariConfigurationEntity.getConfigurationBaseEntity().setConfigurationData(gson.toJson(requestValue));
break;
case TYPE:
ambariConfigurationEntity.getConfigurationBaseEntity().setType((String) requestValue);
break;
-
case VERSION:
- Integer version = (requestValue == null) ? DEFAULT_VERSION : Integer.valueOf((Integer) requestValue);
+ Integer version = (requestValue == null) ? DEFAULT_VERSION : Integer.valueOf((String) requestValue);
ambariConfigurationEntity.getConfigurationBaseEntity().setVersion((version));
break;
case VERSION_TAG:
@@ -231,15 +283,13 @@ public class AmbariConfigurationResourceProvider extends AbstractAuthorizedResou
}
- private Object getValueFromRequest(ResourcePropertyId resourcePropertyIdEnum, Request request) {
- LOGGER.debug("Locating resource property [{}] in the request ...", resourcePropertyIdEnum);
+ private Object getValueFromResourceProperties(ResourcePropertyId resourcePropertyIdEnum, Map<String, Object> resourceProperties) {
+ LOGGER.debug("Locating resource property [{}] in the resource properties map ...", resourcePropertyIdEnum);
Object requestValue = null;
- for (Map<String, Object> propertyMap : request.getProperties()) {
- if (propertyMap.containsKey(resourcePropertyIdEnum.getPropertyId())) {
- requestValue = propertyMap.get(resourcePropertyIdEnum.getPropertyId());
- LOGGER.debug("Found resource property {} in the request, value: {} ...", resourcePropertyIdEnum, requestValue);
- break;
- }
+
+ if (resourceProperties.containsKey(resourcePropertyIdEnum.getPropertyId())) {
+ requestValue = resourceProperties.get(resourcePropertyIdEnum.getPropertyId());
+ LOGGER.debug("Found resource property {} in the resource properties map, value: {}", resourcePropertyIdEnum, requestValue);
}
return requestValue;
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/1e8cde47/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/DefaultProviderModule.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/DefaultProviderModule.java b/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/DefaultProviderModule.java
index fdf4a97..c3758b3 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/DefaultProviderModule.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/DefaultProviderModule.java
@@ -116,8 +116,6 @@ public class DefaultProviderModule extends AbstractProviderModule {
return new ArtifactResourceProvider(managementController);
case RemoteCluster:
return new RemoteClusterResourceProvider();
- case AmbariConfiguration:
- return new AmbariConfigurationResourceProvider();
default:
LOGGER.debug("Delegating creation of resource provider for: {} to the AbstractControllerResourceProvider", type.getInternalType());
return AbstractControllerResourceProvider.getResourceProvider(type, propertyIds,
http://git-wip-us.apache.org/repos/asf/ambari/blob/1e8cde47/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/AmbariConfigurationDAO.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/AmbariConfigurationDAO.java b/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/AmbariConfigurationDAO.java
index c29a423..5710a7f 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/AmbariConfigurationDAO.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/AmbariConfigurationDAO.java
@@ -19,8 +19,11 @@ import javax.inject.Singleton;
import org.apache.ambari.server.orm.entities.AmbariConfigurationEntity;
+import com.google.inject.persist.Transactional;
+
/**
* DAO dealing with ambari configuration related JPA operations.
+ * Operations delegate to the JPA provider implementation of CRUD operations.
*/
@Singleton
@@ -31,6 +34,7 @@ public class AmbariConfigurationDAO extends CrudDAO<AmbariConfigurationEntity, L
super(AmbariConfigurationEntity.class);
}
+ @Transactional
public void create(AmbariConfigurationEntity entity) {
super.create(entity);
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/1e8cde47/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/AmbariConfigurationResourceProviderTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/AmbariConfigurationResourceProviderTest.java b/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/AmbariConfigurationResourceProviderTest.java
new file mode 100644
index 0000000..d974682
--- /dev/null
+++ b/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/AmbariConfigurationResourceProviderTest.java
@@ -0,0 +1,231 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.controller.internal;
+
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.ambari.server.controller.spi.Predicate;
+import org.apache.ambari.server.controller.spi.Request;
+import org.apache.ambari.server.controller.spi.Resource;
+import org.apache.ambari.server.controller.utilities.PredicateBuilder;
+import org.apache.ambari.server.orm.dao.AmbariConfigurationDAO;
+import org.apache.ambari.server.orm.entities.AmbariConfigurationEntity;
+import org.apache.ambari.server.orm.entities.ConfigurationBaseEntity;
+import org.easymock.Capture;
+import org.easymock.EasyMock;
+import org.easymock.EasyMockRule;
+import org.easymock.EasyMockSupport;
+import org.easymock.Mock;
+import org.easymock.TestSubject;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+public class AmbariConfigurationResourceProviderTest extends EasyMockSupport {
+
+ @Rule
+ public EasyMockRule mocks = new EasyMockRule(this);
+
+ @Mock
+ private Request requestMock;
+
+ @Mock
+ private AmbariConfigurationDAO ambariConfigurationDAO;
+
+ private Capture<AmbariConfigurationEntity> ambariConfigurationEntityCapture;
+
+ private Gson gson;
+
+ private static final String DATA_MOCK_STR = "[\n" +
+ " {\n" +
+ " \"authentication.ldap.baseDn\" : \"dc=ambari,dc=apache,dc=org\",\n" +
+ " \"authentication.ldap.primaryUrl\" : \"localhost:33389\",\n" +
+ " \"authentication.ldap.secondaryUrl\" : \"localhost:333\"\n" +
+ " }\n" +
+ " ]";
+
+ private static final Long PK_LONG = Long.valueOf(1);
+ private static final String PK_STRING = String.valueOf(1);
+ private static final String VERSION_TAG = "test version";
+ private static final String VERSION = "1";
+
+ @TestSubject
+ private AmbariConfigurationResourceProvider ambariConfigurationResourceProvider = new AmbariConfigurationResourceProvider();
+
+ @Before
+ public void setup() {
+ ambariConfigurationEntityCapture = Capture.newInstance();
+ gson = new GsonBuilder().create();
+ }
+
+ @Test
+ public void testCreateAmbariConfigurationRequestResultsInTheProperPersistenceCall() throws Exception {
+
+ // GIVEN
+ // configuration properties parsed from the request
+ Set<Map<String, Object>> resourcePropertiesSet = Sets.newHashSet(
+ new PropertiesMapBuilder()
+ .withId(PK_LONG)
+ .withVersion(VERSION)
+ .withVersionTag(VERSION_TAG)
+ .withData(DATA_MOCK_STR)
+ .build());
+
+ // mock the request to return the properties
+ EasyMock.expect(requestMock.getProperties()).andReturn(resourcePropertiesSet);
+
+ // capture the entity the DAO gets called with
+ ambariConfigurationDAO.create(EasyMock.capture(ambariConfigurationEntityCapture));
+ replayAll();
+
+ // WHEN
+ ambariConfigurationResourceProvider.createResourcesAuthorized(requestMock);
+
+ // THEN
+ AmbariConfigurationEntity capturedAmbariConfigurationEntity = ambariConfigurationEntityCapture.getValue();
+ Assert.assertNotNull(capturedAmbariConfigurationEntity);
+ Assert.assertNull("The entity identifier should be null", capturedAmbariConfigurationEntity.getId());
+ Assert.assertEquals("The entity version is not the expected", Integer.valueOf(VERSION),
+ capturedAmbariConfigurationEntity.getConfigurationBaseEntity().getVersion());
+ Assert.assertEquals("The entity version tag is not the expected", VERSION_TAG,
+ capturedAmbariConfigurationEntity.getConfigurationBaseEntity().getVersionTag());
+ Assert.assertEquals("The entity data is not the expected", DATA_MOCK_STR,
+ gson.fromJson(capturedAmbariConfigurationEntity.getConfigurationBaseEntity().getConfigurationData(), String.class));
+ }
+
+ @Test
+ public void testRemoveAmbariConfigurationRequestResultsInTheProperPersistenceCall() throws Exception {
+ // GIVEN
+ Predicate predicate = new PredicateBuilder().property(
+ AmbariConfigurationResourceProvider.ResourcePropertyId.ID.getPropertyId()).equals("1").toPredicate();
+
+ Capture<Long> pkCapture = Capture.newInstance();
+ ambariConfigurationDAO.removeByPK(EasyMock.capture(pkCapture));
+ replayAll();
+
+ // WHEN
+ ambariConfigurationResourceProvider.deleteResourcesAuthorized(requestMock, predicate);
+
+ // THEN
+ Assert.assertEquals("The pk of the entity to be removed doen't match the expected id", Long.valueOf(1), pkCapture.getValue());
+ }
+
+
+ @Test
+ public void testRetrieveAmbariConfigurationShouldResultsInTheProperDAOCall() throws Exception {
+ // GIVEN
+ Predicate predicate = new PredicateBuilder().property(
+ AmbariConfigurationResourceProvider.ResourcePropertyId.ID.getPropertyId()).equals("1").toPredicate();
+
+ EasyMock.expect(ambariConfigurationDAO.findAll()).andReturn(Lists.newArrayList(createDummyAmbariConfigurationEntity()));
+ replayAll();
+
+ // WHEN
+ Set<Resource> resourceSet = ambariConfigurationResourceProvider.getResourcesAuthorized(requestMock, predicate);
+
+ // THEN
+ Assert.assertNotNull(resourceSet);
+ Assert.assertFalse(resourceSet.isEmpty());
+ }
+
+ @Test
+ public void testUpdateAmbariConfigurationShouldResultInTheProperDAOCalls() throws Exception {
+ // GIVEN
+
+ Predicate predicate = new PredicateBuilder().property(
+ AmbariConfigurationResourceProvider.ResourcePropertyId.ID.getPropertyId()).equals("1").toPredicate();
+
+ // properteies in the request, representing the updated configuration
+ Set<Map<String, Object>> resourcePropertiesSet = Sets.newHashSet(new PropertiesMapBuilder()
+ .withId(PK_LONG)
+ .withVersion("2")
+ .withVersionTag("version-2")
+ .withData(DATA_MOCK_STR).build());
+
+ EasyMock.expect(requestMock.getProperties()).andReturn(resourcePropertiesSet);
+
+ AmbariConfigurationEntity persistedEntity = createDummyAmbariConfigurationEntity();
+ EasyMock.expect(ambariConfigurationDAO.findByPK(PK_LONG)).andReturn(persistedEntity);
+ ambariConfigurationDAO.create(EasyMock.capture(ambariConfigurationEntityCapture));
+
+ replayAll();
+
+ // WHEN
+ ambariConfigurationResourceProvider.updateResourcesAuthorized(requestMock, predicate);
+
+ // the captured entity should be the updated one
+ AmbariConfigurationEntity updatedEntity = ambariConfigurationEntityCapture.getValue();
+
+ // THEN
+ Assert.assertNotNull(updatedEntity);
+ Assert.assertEquals("The updated version is wrong", Integer.valueOf(2), updatedEntity.getConfigurationBaseEntity().getVersion());
+ }
+
+ private class PropertiesMapBuilder {
+
+ private Map<String, Object> resourcePropertiesMap = Maps.newHashMap();
+
+ private PropertiesMapBuilder() {
+ }
+
+ public PropertiesMapBuilder withId(Long id) {
+ resourcePropertiesMap.put(AmbariConfigurationResourceProvider.ResourcePropertyId.ID.getPropertyId(), id);
+ return this;
+ }
+
+ private PropertiesMapBuilder withVersion(String version) {
+ resourcePropertiesMap.put(AmbariConfigurationResourceProvider.ResourcePropertyId.VERSION.getPropertyId(), version);
+ return this;
+ }
+
+ private PropertiesMapBuilder withVersionTag(String versionTag) {
+ resourcePropertiesMap.put(AmbariConfigurationResourceProvider.ResourcePropertyId.VERSION_TAG.getPropertyId(), versionTag);
+ return this;
+ }
+
+ private PropertiesMapBuilder withData(String dataJson) {
+ resourcePropertiesMap.put(AmbariConfigurationResourceProvider.ResourcePropertyId.DATA.getPropertyId(), dataJson);
+ return this;
+ }
+
+ public Map<String, Object> build() {
+ return this.resourcePropertiesMap;
+ }
+
+ }
+
+ private AmbariConfigurationEntity createDummyAmbariConfigurationEntity() {
+ AmbariConfigurationEntity acEntity = new AmbariConfigurationEntity();
+ ConfigurationBaseEntity configurationBaseEntity = new ConfigurationBaseEntity();
+ acEntity.setConfigurationBaseEntity(configurationBaseEntity);
+ acEntity.setId(PK_LONG);
+ acEntity.getConfigurationBaseEntity().setConfigurationData(DATA_MOCK_STR);
+ acEntity.getConfigurationBaseEntity().setVersion(Integer.valueOf(VERSION));
+ acEntity.getConfigurationBaseEntity().setVersionTag(VERSION_TAG);
+ acEntity.getConfigurationBaseEntity().setType("ldap-config");
+
+ return acEntity;
+ }
+
+
+}
\ No newline at end of file
[13/33] ambari git commit: AMBARI-21307 Groups for the test user
returned to the caller
Posted by lp...@apache.org.
AMBARI-21307 Groups for the test user returned to the caller
Project: http://git-wip-us.apache.org/repos/asf/ambari/repo
Commit: http://git-wip-us.apache.org/repos/asf/ambari/commit/28180465
Tree: http://git-wip-us.apache.org/repos/asf/ambari/tree/28180465
Diff: http://git-wip-us.apache.org/repos/asf/ambari/diff/28180465
Branch: refs/heads/feature-branch-AMBARI-21307
Commit: 28180465404d20e61f4b71167042ae551569bec1
Parents: 86e105f
Author: lpuskas <lp...@apache.org>
Authored: Tue Aug 8 15:50:29 2017 +0200
Committer: lpuskas <lp...@apache.org>
Committed: Fri Oct 13 17:20:49 2017 +0200
----------------------------------------------------------------------
.../api/services/ldap/LdapRestService.java | 16 +++++-
.../server/ldap/AmbariLdapConfiguration.java | 2 +-
.../apache/ambari/server/ldap/LdapModule.java | 3 +
.../server/ldap/service/AmbariLdapFacade.java | 3 +-
.../ambari/server/ldap/service/LdapFacade.java | 3 +-
...efaultLdapConfigurationValidatorService.java | 25 ++++++---
.../ad/DefaultLdapConnectionService.java | 2 +-
...ltLdapConfigurationValidatorServiceTest.java | 59 +++-----------------
8 files changed, 49 insertions(+), 64 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/ambari/blob/28180465/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapRestService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapRestService.java b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapRestService.java
index 33b10fa..8578204 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapRestService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapRestService.java
@@ -28,6 +28,8 @@
package org.apache.ambari.server.api.services.ldap;
+import java.util.Set;
+
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
@@ -41,12 +43,16 @@ import org.apache.ambari.server.api.services.BaseService;
import org.apache.ambari.server.api.services.Result;
import org.apache.ambari.server.api.services.ResultImpl;
import org.apache.ambari.server.api.services.ResultStatus;
+import org.apache.ambari.server.controller.internal.ResourceImpl;
+import org.apache.ambari.server.controller.spi.Resource;
import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
import org.apache.ambari.server.ldap.LdapConfigurationFactory;
import org.apache.ambari.server.ldap.service.LdapFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import com.google.common.collect.Sets;
+
/**
* Endpoint designated to LDAP specific operations.
*/
@@ -68,6 +74,8 @@ public class LdapRestService extends BaseService {
@Consumes(MediaType.APPLICATION_JSON)
public Response validateConfiguration(LdapCheckConfigurationRequest ldapCheckConfigurationRequest) {
+ Set<String> groups = Sets.newHashSet();
+
Result result = new ResultImpl(new ResultStatus(ResultStatus.STATUS.OK));
try {
@@ -86,7 +94,11 @@ public class LdapRestService extends BaseService {
case "test-attributes":
LOGGER.info("Testing LDAP attributes ....");
- ldapFacade.checkLdapAttibutes(ldapCheckConfigurationRequest.getRequestInfo().getParameters(), ambariLdapConfiguration);
+ groups = ldapFacade.checkLdapAttibutes(ldapCheckConfigurationRequest.getRequestInfo().getParameters(), ambariLdapConfiguration);
+ // todo factor out the resource creation, design better the structure in the response
+ Resource resource = new ResourceImpl(Resource.Type.AmbariConfiguration);
+ resource.setProperty("groups", groups);
+ result.getResultTree().addChild(resource, "payload");
break;
case "detect-attributes":
@@ -101,7 +113,7 @@ public class LdapRestService extends BaseService {
}
} catch (Exception e) {
- result = new ResultImpl(new ResultStatus(ResultStatus.STATUS.BAD_REQUEST, e));
+ result.setResultStatus(new ResultStatus(ResultStatus.STATUS.BAD_REQUEST, e));
}
return Response.status(result.getStatus().getStatusCode()).entity(getResultSerializer().serialize(result)).build();
http://git-wip-us.apache.org/repos/asf/ambari/blob/28180465/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
index a6ff80b..8ab587b 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
@@ -48,7 +48,7 @@ public class AmbariLdapConfiguration {
MANAGER_PASSWORD("ambari.ldap.managerpassword"),
USER_OBJECT_CLASS("ambari.ldap.user.object.class"),
USER_NAME_ATTRIBUTE("ambari.ldap.user.name.attribute"),
- USER_SEARCH_BASE("ambari.ldap.user.search.Base"),
+ USER_SEARCH_BASE("ambari.ldap.user.search.base"),
GROUP_OBJECT_CLASS("ambari.ldap.group.object.class"),
GROUP_NAME_ATTRIBUTE("ambari.ldap.group.name.attribute"),
http://git-wip-us.apache.org/repos/asf/ambari/blob/28180465/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
index 545f220..1b49159 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
@@ -16,8 +16,10 @@
package org.apache.ambari.server.ldap;
import org.apache.ambari.server.ldap.service.AmbariLdapFacade;
+import org.apache.ambari.server.ldap.service.LdapConnectionService;
import org.apache.ambari.server.ldap.service.LdapFacade;
import org.apache.ambari.server.ldap.service.ad.DefaultLdapConfigurationValidatorService;
+import org.apache.ambari.server.ldap.service.ad.DefaultLdapConnectionService;
import com.google.inject.AbstractModule;
import com.google.inject.assistedinject.FactoryModuleBuilder;
@@ -31,6 +33,7 @@ public class LdapModule extends AbstractModule {
protected void configure() {
bind(LdapFacade.class).to(AmbariLdapFacade.class);
bind(LdapConfigurationValidatorService.class).to(DefaultLdapConfigurationValidatorService.class);
+ bind(LdapConnectionService.class).to(DefaultLdapConnectionService.class);
install(new FactoryModuleBuilder().build(LdapConfigurationFactory.class));
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/28180465/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
index abb464b..eec47ce 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
@@ -79,7 +79,7 @@ public class AmbariLdapFacade implements LdapFacade {
}
@Override
- public void checkLdapAttibutes(Map<String, Object> parameters, AmbariLdapConfiguration ldapConfiguration) throws AmbariLdapException {
+ public Set<String> checkLdapAttibutes(Map<String, Object> parameters, AmbariLdapConfiguration ldapConfiguration) throws AmbariLdapException {
String userName = getTestUserNameFromParameters(parameters);
String testUserPass = getTestUserPasswordFromParameters(parameters);
@@ -95,6 +95,7 @@ public class AmbariLdapFacade implements LdapFacade {
LOGGER.info("Testing LDAP group attributes with test user dn: {}", userDn);
Set<String> groups = ldapConfigurationValidatorService.checkGroupAttributes(ldapConnection, userDn, ldapConfiguration);
+ return groups;
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/28180465/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java
index 7bb1198..eadff7d 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java
@@ -15,6 +15,7 @@
package org.apache.ambari.server.ldap.service;
import java.util.Map;
+import java.util.Set;
import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
@@ -47,5 +48,5 @@ public interface LdapFacade {
* @param ambariLdapConfiguration configutration instance with available attributes
* @throws AmbariLdapException if the attribute checking fails
*/
- void checkLdapAttibutes(Map<String, Object> parameters, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException;
+ Set<String> checkLdapAttibutes(Map<String, Object> parameters, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException;
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/28180465/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConfigurationValidatorService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConfigurationValidatorService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConfigurationValidatorService.java
index 838ef4c..a8503ca 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConfigurationValidatorService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConfigurationValidatorService.java
@@ -37,7 +37,6 @@ import org.apache.directory.api.ldap.model.message.SearchRequestImpl;
import org.apache.directory.api.ldap.model.message.SearchScope;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.ldap.client.api.LdapConnection;
-import org.apache.directory.ldap.client.api.LdapNetworkConnection;
import org.apache.directory.ldap.client.api.search.FilterBuilder;
import org.apache.directory.shared.ldap.constants.SchemaConstants;
import org.slf4j.Logger;
@@ -84,18 +83,18 @@ public class DefaultLdapConfigurationValidatorService implements LdapConfigurati
* @param testUserName the test username
* @param testPassword the test password
* @param ambariLdapConfiguration configuration instance holding ldap configuration details
+ * @return the DN of the test user
* @throws AmbariException if the attributes are not valid or any errors occurs
*/
@Override
public String checkUserAttributes(LdapConnection ldapConnection, String testUserName, String testPassword, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
- LdapNetworkConnection connection = null;
SearchCursor searchCursor = null;
String userDn = null;
try {
LOGGER.info("Checking user attributes for user {} r ...", testUserName);
// bind anonimously or with manager data
- bind(ambariLdapConfiguration, connection);
+ bind(ambariLdapConfiguration, ldapConnection);
// set up a filter based on the provided attributes
String filter = FilterBuilder.and(
@@ -104,7 +103,7 @@ public class DefaultLdapConfigurationValidatorService implements LdapConfigurati
.toString();
LOGGER.info("Searching for the user: {} using the search filter: {}", testUserName, filter);
- EntryCursor entryCursor = connection.search(new Dn(ambariLdapConfiguration.userSearchBase()), filter, SearchScope.SUBTREE);
+ EntryCursor entryCursor = ldapConnection.search(new Dn(ambariLdapConfiguration.userSearchBase()), filter, SearchScope.SUBTREE);
// collecting search result entries
List<Entry> users = Lists.newArrayList();
@@ -128,7 +127,7 @@ public class DefaultLdapConfigurationValidatorService implements LdapConfigurati
throw new AmbariLdapException(e.getMessage(), e);
} finally {
- closeResources(connection, searchCursor);
+ closeResources(ldapConnection, searchCursor);
}
return userDn;
}
@@ -172,14 +171,19 @@ public class DefaultLdapConfigurationValidatorService implements LdapConfigurati
throw new AmbariLdapException(e.getMessage(), e);
} finally {
-
closeResources(ldapConnection, searchCursor);
-
}
return processGroupResults(groupResponses, ambariLdapConfiguration);
}
+ /**
+ * Binds to the LDAP server (anonimously or wit manager credentials)
+ *
+ * @param ambariLdapConfiguration configuration instance
+ * @param connection connection instance
+ * @throws LdapException if the bind operation fails
+ */
private void bind(AmbariLdapConfiguration ambariLdapConfiguration, LdapConnection connection) throws LdapException {
LOGGER.info("Connecting to LDAP ....");
if (!ambariLdapConfiguration.bindAnonimously()) {
@@ -198,6 +202,13 @@ public class DefaultLdapConfigurationValidatorService implements LdapConfigurati
}
+ /**
+ * Extracts meaningful values from the search result.
+ *
+ * @param groupResponses the result entries returned by the search
+ * @param ambariLdapConfiguration holds the keys of the meaningful attributes
+ * @return a set with the group names the test user belongs to
+ */
private Set<String> processGroupResults(Set<Response> groupResponses, AmbariLdapConfiguration ambariLdapConfiguration) {
Set<String> groupStrSet = Sets.newHashSet();
for (Response response : groupResponses) {
http://git-wip-us.apache.org/repos/asf/ambari/blob/28180465/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConnectionService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConnectionService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConnectionService.java
index b5559d9..25dc1f2 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConnectionService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConnectionService.java
@@ -56,7 +56,7 @@ public class DefaultLdapConnectionService implements LdapConnectionService {
ldapConnectionConfig.setLdapPort(ambariAmbariLdapConfiguration.ldapServerPort());
ldapConnectionConfig.setUseSsl(ambariAmbariLdapConfiguration.useSSL());
- //todo set the other values as required
+ // todo set the other values as required
return ldapConnectionConfig;
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/28180465/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConfigurationValidatorServiceTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConfigurationValidatorServiceTest.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConfigurationValidatorServiceTest.java
index 5c9d304..663ea12 100644
--- a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConfigurationValidatorServiceTest.java
+++ b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConfigurationValidatorServiceTest.java
@@ -18,23 +18,15 @@ import static org.junit.Assert.assertNotNull;
import java.util.Map;
-import org.apache.ambari.server.AmbariException;
import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
import org.apache.ambari.server.ldap.LdapConfigurationValidatorService;
import org.apache.ambari.server.ldap.service.LdapConnectionService;
import org.apache.directory.api.ldap.model.cursor.EntryCursor;
-import org.apache.directory.api.ldap.model.cursor.SearchCursor;
import org.apache.directory.api.ldap.model.entry.Entry;
-import org.apache.directory.api.ldap.model.message.Response;
-import org.apache.directory.api.ldap.model.message.SearchRequest;
-import org.apache.directory.api.ldap.model.message.SearchRequestImpl;
-import org.apache.directory.api.ldap.model.message.SearchResultEntry;
import org.apache.directory.api.ldap.model.message.SearchScope;
-import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.LdapConnectionConfig;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;
-import org.apache.directory.ldap.client.api.search.FilterBuilder;
import org.apache.directory.shared.ldap.constants.SchemaConstants;
import org.junit.Test;
import org.slf4j.Logger;
@@ -75,57 +67,24 @@ public class DefaultLdapConfigurationValidatorServiceTest {
@Test
public void testCheckUserAttributes() throws Exception {
+ // GIVEN
Map<String, Object> ldapPropsMap = Maps.newHashMap();
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.BIND_ANONIMOUSLY.propertyName(), false);
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.BIND_ANONIMOUSLY.propertyName(), "true");
ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.LDAP_SERVER_HOST.propertyName(), "ldap.forumsys.com");
ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.LDAP_SERVER_PORT.propertyName(), "389");
ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.BASE_DN.propertyName(), "dc=example,dc=com");
+
ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.USER_OBJECT_CLASS.propertyName(), SchemaConstants.PERSON_OC);
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.GROUP_OBJECT_CLASS.propertyName(), SchemaConstants.GROUP_OF_UNIQUE_NAMES_OC);
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.GROUP_NAME_ATTRIBUTE.propertyName(), SchemaConstants.CN_AT);
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.GROUP_MEMBER_ATTRIBUTE.propertyName(), SchemaConstants.UNIQUE_MEMBER_AT);
ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.USER_NAME_ATTRIBUTE.propertyName(), SchemaConstants.UID_AT);
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.USER_SEARCH_BASE.propertyName(), "dc=example,dc=com");
- AmbariLdapConfiguration ambariLdapConfiguration = new AmbariLdapConfiguration(ldapPropsMap);
-
-
- try {
- LOGGER.info("Authenticating user {} against the LDAP server ...", TEST_USER);
- LdapConnectionService connectionService = new DefaultLdapConnectionService();
- LdapNetworkConnection connection = connectionService.createLdapConnection(ambariLdapConfiguration);
-
- String filter = FilterBuilder.and(
- FilterBuilder.equal(SchemaConstants.OBJECT_CLASS_AT, ambariLdapConfiguration.userObjectClass()),
- FilterBuilder.equal(ambariLdapConfiguration.userNameAttribute(), TEST_USER))
- .toString();
-
- SearchRequest searchRequest = new SearchRequestImpl();
- searchRequest.setBase(new Dn(ambariLdapConfiguration.baseDn()));
- searchRequest.setFilter(filter);
- searchRequest.setScope(SearchScope.SUBTREE);
- LOGGER.info("loking up user: {} based on the filtr: {}", TEST_USER, filter);
-
- connection.bind();
- SearchCursor searchCursor = connection.search(searchRequest);
-
- while (searchCursor.next()) {
- Response response = searchCursor.get();
-
- // process the SearchResultEntry
- if (response instanceof SearchResultEntry) {
- Entry resultEntry = ((SearchResultEntry) response).getEntry();
- System.out.println(resultEntry);
- }
- }
-
- searchCursor.close();
-
- } catch (Exception e) {
- throw new AmbariException("Error during user authentication check", e);
- }
+ AmbariLdapConfiguration ambariLdapConfiguration = new AmbariLdapConfiguration(ldapPropsMap);
+ LdapConnectionService connectionService = new DefaultLdapConnectionService();
+ LdapNetworkConnection ldapConnection = connectionService.createLdapConnection(ambariLdapConfiguration);
+ ldapConfigurationValidatorService.checkUserAttributes(ldapConnection, "einstein", "", ambariLdapConfiguration);
}
@Test
@@ -138,8 +97,6 @@ public class DefaultLdapConfigurationValidatorServiceTest {
ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.LDAP_SERVER_PORT.propertyName(), "389");
ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.BASE_DN.propertyName(), "dc=example,dc=com");
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.USER_OBJECT_CLASS.propertyName(), SchemaConstants.PERSON_OC);
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.USER_NAME_ATTRIBUTE.propertyName(), SchemaConstants.UID_AT);
ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.GROUP_OBJECT_CLASS.propertyName(), SchemaConstants.GROUP_OF_UNIQUE_NAMES_OC);
ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.GROUP_NAME_ATTRIBUTE.propertyName(), SchemaConstants.CN_AT);
[28/33] ambari git commit: AMBARI-21307 Refactor - using the
LdapConnectionTemplate for ldap operations
Posted by lp...@apache.org.
AMBARI-21307 Refactor - using the LdapConnectionTemplate for ldap operations
Project: http://git-wip-us.apache.org/repos/asf/ambari/repo
Commit: http://git-wip-us.apache.org/repos/asf/ambari/commit/1ecd85c4
Tree: http://git-wip-us.apache.org/repos/asf/ambari/tree/1ecd85c4
Diff: http://git-wip-us.apache.org/repos/asf/ambari/diff/1ecd85c4
Branch: refs/heads/feature-branch-AMBARI-21307
Commit: 1ecd85c4da518a0c59735f8a8d30f245a69bcae9
Parents: b8128f0
Author: lpuskas <lp...@apache.org>
Authored: Wed Oct 4 15:54:34 2017 +0200
Committer: lpuskas <lp...@apache.org>
Committed: Fri Oct 13 17:20:52 2017 +0200
----------------------------------------------------------------------
.../services/ldap/LdapConfigurationService.java | 6 +-
.../server/controller/ControllerModule.java | 2 +-
.../apache/ambari/server/ldap/LdapModule.java | 12 +-
.../domain/AmbariLdapConfigurationFactory.java | 34 +++++
.../ldap/domain/LdapConfigurationFactory.java | 34 -----
.../AmbariLdapConfigurationProvider.java | 5 +-
.../server/ldap/service/AmbariLdapFacade.java | 36 +----
.../server/ldap/service/AttributeDetector.java | 2 +-
.../service/LdapAttributeDetectionService.java | 8 +-
.../ldap/service/LdapConfigurationService.java | 22 +--
.../ldap/service/LdapConnectionService.java | 43 ------
.../service/LdapConnectionTemplateProvider.java | 56 ++++++++
.../DefaultLdapAttributeDetectionService.java | 129 ++++++-----------
.../ads/DefaultLdapConfigurationService.java | 110 +++++++-------
.../ads/DefaultLdapConnectionService.java | 86 -----------
.../ads/LdapConnectionTemplateFactory.java | 95 ++++++++++++
.../ads/detectors/GroupMemberAttrDetector.java | 4 +-
.../ads/detectors/GroupNameAttrDetector.java | 4 +-
.../ads/detectors/GroupObjectClassDetector.java | 4 +-
.../OccurranceAndWeightBasedDetector.java | 103 -------------
.../OccurrenceAndWeightBasedDetector.java | 103 +++++++++++++
.../detectors/UserGroupMemberAttrDetector.java | 4 +-
.../ads/detectors/UserNameAttrDetector.java | 4 +-
.../ads/detectors/UserObjectClassDetector.java | 4 +-
.../server/ldap/LdapModuleFunctionalTest.java | 143 +++++++++++++++++++
.../domain/AmbariLdapConfigurationTest.java | 19 ---
...estAmbariAmbariLdapConfigurationFactory.java | 29 ++++
.../TestAmbariLdapConfigurationFactory.java | 29 ----
...efaultLdapAttributeDetectionServiceTest.java | 112 ---------------
.../DefaultLdapConfigurationServiceTest.java | 129 -----------------
30 files changed, 601 insertions(+), 770 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/ambari/blob/1ecd85c4/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationService.java b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationService.java
index ff95066..13f8835 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationService.java
@@ -47,7 +47,7 @@ import org.apache.ambari.server.api.services.ResultStatus;
import org.apache.ambari.server.controller.internal.ResourceImpl;
import org.apache.ambari.server.controller.spi.Resource;
import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
-import org.apache.ambari.server.ldap.domain.LdapConfigurationFactory;
+import org.apache.ambari.server.ldap.domain.AmbariLdapConfigurationFactory;
import org.apache.ambari.server.ldap.service.LdapFacade;
import org.apache.ambari.server.security.authorization.AuthorizationException;
import org.apache.ambari.server.security.authorization.AuthorizationHelper;
@@ -72,7 +72,7 @@ public class LdapConfigurationService extends AmbariConfigurationService {
private static LdapFacade ldapFacade;
@Inject
- private static LdapConfigurationFactory ldapConfigurationFactory;
+ private static AmbariLdapConfigurationFactory ambariLdapConfigurationFactory;
@POST
@@ -93,7 +93,7 @@ public class LdapConfigurationService extends AmbariConfigurationService {
validateRequest(ldapConfigurationRequest);
- AmbariLdapConfiguration ambariLdapConfiguration = ldapConfigurationFactory.createLdapConfiguration(
+ AmbariLdapConfiguration ambariLdapConfiguration = ambariLdapConfigurationFactory.createLdapConfiguration(
ldapConfigurationRequest.getAmbariConfiguration().getData().iterator().next());
LdapConfigOperation action = LdapConfigOperation.fromAction(ldapConfigurationRequest.getRequestInfo().getAction());
http://git-wip-us.apache.org/repos/asf/ambari/blob/1ecd85c4/ambari-server/src/main/java/org/apache/ambari/server/controller/ControllerModule.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/controller/ControllerModule.java b/ambari-server/src/main/java/org/apache/ambari/server/controller/ControllerModule.java
index 4f30b15..1425e1b 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/controller/ControllerModule.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/controller/ControllerModule.java
@@ -62,8 +62,8 @@ import org.apache.ambari.server.cleanup.ClasspathScannerUtils;
import org.apache.ambari.server.configuration.Configuration;
import org.apache.ambari.server.configuration.Configuration.ConnectionPoolType;
import org.apache.ambari.server.configuration.Configuration.DatabaseType;
-import org.apache.ambari.server.controller.internal.AmbariConfigurationResourceProvider;
import org.apache.ambari.server.controller.internal.AlertTargetResourceProvider;
+import org.apache.ambari.server.controller.internal.AmbariConfigurationResourceProvider;
import org.apache.ambari.server.controller.internal.ClusterStackVersionResourceProvider;
import org.apache.ambari.server.controller.internal.ComponentResourceProvider;
import org.apache.ambari.server.controller.internal.CredentialResourceProvider;
http://git-wip-us.apache.org/repos/asf/ambari/blob/1ecd85c4/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
index 83a73d1..d59264a 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
@@ -16,16 +16,16 @@
package org.apache.ambari.server.ldap;
import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
-import org.apache.ambari.server.ldap.domain.LdapConfigurationFactory;
+import org.apache.ambari.server.ldap.domain.AmbariLdapConfigurationFactory;
import org.apache.ambari.server.ldap.service.AmbariLdapConfigurationProvider;
import org.apache.ambari.server.ldap.service.AmbariLdapFacade;
import org.apache.ambari.server.ldap.service.LdapAttributeDetectionService;
import org.apache.ambari.server.ldap.service.LdapConfigurationService;
-import org.apache.ambari.server.ldap.service.LdapConnectionService;
+import org.apache.ambari.server.ldap.service.LdapConnectionTemplateProvider;
import org.apache.ambari.server.ldap.service.LdapFacade;
import org.apache.ambari.server.ldap.service.ads.DefaultLdapAttributeDetectionService;
import org.apache.ambari.server.ldap.service.ads.DefaultLdapConfigurationService;
-import org.apache.ambari.server.ldap.service.ads.DefaultLdapConnectionService;
+import org.apache.directory.ldap.client.template.LdapConnectionTemplate;
import com.google.inject.AbstractModule;
import com.google.inject.assistedinject.FactoryModuleBuilder;
@@ -39,12 +39,14 @@ public class LdapModule extends AbstractModule {
protected void configure() {
bind(LdapFacade.class).to(AmbariLdapFacade.class);
bind(LdapConfigurationService.class).to(DefaultLdapConfigurationService.class);
- bind(LdapConnectionService.class).to(DefaultLdapConnectionService.class);
bind(LdapAttributeDetectionService.class).to(DefaultLdapAttributeDetectionService.class);
// this binding requires the JPA module!
bind(AmbariLdapConfiguration.class).toProvider(AmbariLdapConfigurationProvider.class);
- install(new FactoryModuleBuilder().build(LdapConfigurationFactory.class));
+ // bind to the provider implementation (let GUICE deal with instantiating 3rd party instances)
+ bind(LdapConnectionTemplate.class).toProvider(LdapConnectionTemplateProvider.class);
+
+ install(new FactoryModuleBuilder().build(AmbariLdapConfigurationFactory.class));
}
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/1ecd85c4/ambari-server/src/main/java/org/apache/ambari/server/ldap/domain/AmbariLdapConfigurationFactory.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/domain/AmbariLdapConfigurationFactory.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/domain/AmbariLdapConfigurationFactory.java
new file mode 100644
index 0000000..2b9f24b
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/domain/AmbariLdapConfigurationFactory.java
@@ -0,0 +1,34 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.domain;
+
+import java.util.Map;
+
+/**
+ * Factory interface for AmbariLdapConfiguration instances.
+ * It's registered as a factory in the GUICE context (so no implementations required)
+ *
+ * To be extended with other factory methods upon needs.
+ */
+public interface AmbariLdapConfigurationFactory {
+
+ /**
+ * Creates an AmbariLdapConfiguration instance with the provided map of configuration settings.
+ *
+ * @param configuration a map where keys are the configuration properties and values are the configuration values
+ * @return an AmbariLdapConfiguration instance
+ */
+ AmbariLdapConfiguration createLdapConfiguration(Map<String, Object> configuration);
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/ambari/blob/1ecd85c4/ambari-server/src/main/java/org/apache/ambari/server/ldap/domain/LdapConfigurationFactory.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/domain/LdapConfigurationFactory.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/domain/LdapConfigurationFactory.java
deleted file mode 100644
index bf8f825..0000000
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/domain/LdapConfigurationFactory.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.ambari.server.ldap.domain;
-
-import java.util.Map;
-
-/**
- * Factory interface for AmbariLdapConfiguration instances.
- * It's registered as a factory in the GUICE context (so no implementations required)
- *
- * To be extended with other factory methods upon needs.
- */
-public interface LdapConfigurationFactory {
-
- /**
- * Creates an AmbariLdapConfiguration instance with the provided map of configuration settings.
- *
- * @param configuration a map where keys are the configuration properties and values are the configuration values
- * @return an AmbariLdapConfiguration instance
- */
- AmbariLdapConfiguration createLdapConfiguration(Map<String, Object> configuration);
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/ambari/blob/1ecd85c4/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapConfigurationProvider.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapConfigurationProvider.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapConfigurationProvider.java
index af9f2e7..9fad896 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapConfigurationProvider.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapConfigurationProvider.java
@@ -24,7 +24,7 @@ import javax.inject.Singleton;
import org.apache.ambari.server.events.AmbariLdapConfigChangedEvent;
import org.apache.ambari.server.events.publishers.AmbariEventPublisher;
import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
-import org.apache.ambari.server.ldap.domain.LdapConfigurationFactory;
+import org.apache.ambari.server.ldap.domain.AmbariLdapConfigurationFactory;
import org.apache.ambari.server.orm.dao.AmbariConfigurationDAO;
import org.apache.ambari.server.orm.entities.AmbariConfigurationEntity;
import org.apache.ambari.server.security.authorization.AmbariLdapAuthenticationProvider;
@@ -57,7 +57,7 @@ public class AmbariLdapConfigurationProvider implements Provider<AmbariLdapConfi
private Provider<AmbariConfigurationDAO> ambariConfigurationDAOProvider;
@Inject
- private LdapConfigurationFactory ldapConfigurationFactory;
+ private AmbariLdapConfigurationFactory ldapConfigurationFactory;
private Gson gson = new GsonBuilder().create();
@@ -107,6 +107,7 @@ public class AmbariLdapConfigurationProvider implements Provider<AmbariLdapConfi
return instance;
}
+ // On changing the configuration, the provider gets updated with the fresh value
@Subscribe
public void ambariLdapConfigChanged(AmbariLdapConfigChangedEvent event) {
LOGGER.info("LDAP config changed event received: {}", event);
http://git-wip-us.apache.org/repos/asf/ambari/blob/1ecd85c4/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
index 7a6ad5a..c75b0c4 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
@@ -22,7 +22,6 @@ import javax.inject.Inject;
import javax.inject.Singleton;
import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
-import org.apache.directory.ldap.client.api.LdapConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -54,9 +53,6 @@ public class AmbariLdapFacade implements LdapFacade {
private LdapConfigurationService ldapConfigurationService;
@Inject
- private LdapConnectionService ldapConnectionService;
-
- @Inject
private LdapAttributeDetectionService ldapAttributeDetectionService;
@Inject
@@ -65,13 +61,8 @@ public class AmbariLdapFacade implements LdapFacade {
@Override
public void checkConnection(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
- LdapConnection connection = null;
try {
-
- LOGGER.info("Validating LDAP connection related configuration based on: {}", ambariLdapConfiguration);
- connection = ldapConnectionService.getBoundLdapConnection(ambariLdapConfiguration);
-
- ldapConfigurationService.checkConnection(connection, ambariLdapConfiguration);
+ ldapConfigurationService.checkConnection(ambariLdapConfiguration);
LOGGER.info("Validating LDAP connection related configuration: SUCCESS");
} catch (Exception e) {
@@ -79,13 +70,6 @@ public class AmbariLdapFacade implements LdapFacade {
LOGGER.error("Validating LDAP connection configuration failed", e);
throw new AmbariLdapException(e);
- } finally {
- try {
- connection.unBind();
- connection.close();
- } catch (Exception e) {
- throw new AmbariLdapException(e);
- }
}
}
@@ -95,14 +79,13 @@ public class AmbariLdapFacade implements LdapFacade {
public AmbariLdapConfiguration detectAttributes(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
LOGGER.info("Detecting LDAP configuration attributes ...");
- LdapConnection connection = ldapConnectionService.getBoundLdapConnection(ambariLdapConfiguration);
try {
// decorate the configuration with detected user attributes
- ambariLdapConfiguration = ldapAttributeDetectionService.detectLdapUserAttributes(connection, ambariLdapConfiguration);
+ ambariLdapConfiguration = ldapAttributeDetectionService.detectLdapUserAttributes(ambariLdapConfiguration);
// decorate the configuration with detected group attributes
- ambariLdapConfiguration = ldapAttributeDetectionService.detectLdapGroupAttributes(connection, ambariLdapConfiguration);
+ ambariLdapConfiguration = ldapAttributeDetectionService.detectLdapGroupAttributes(ambariLdapConfiguration);
return ambariLdapConfiguration;
} catch (Exception e) {
@@ -110,13 +93,6 @@ public class AmbariLdapFacade implements LdapFacade {
LOGGER.error("Error during LDAP attribute detection", e);
throw new AmbariLdapException(e);
- } finally {
- try {
- connection.unBind();
- connection.close();
- } catch (Exception e) {
- throw new AmbariLdapException(e);
- }
}
}
@@ -129,14 +105,12 @@ public class AmbariLdapFacade implements LdapFacade {
throw new IllegalArgumentException("No test user available for testing LDAP attributes");
}
- LdapConnection ldapConnection = ldapConnectionService.getBoundLdapConnection(ldapConfiguration);
-
LOGGER.info("Testing LDAP user attributes with test user: {}", userName);
- String userDn = ldapConfigurationService.checkUserAttributes(ldapConnection, userName, testUserPass, ldapConfiguration);
+ String userDn = ldapConfigurationService.checkUserAttributes(userName, testUserPass, ldapConfiguration);
// todo handle the case where group membership is stored in the user rather than the group
LOGGER.info("Testing LDAP group attributes with test user dn: {}", userDn);
- Set<String> groups = ldapConfigurationService.checkGroupAttributes(ldapConnection, userDn, ldapConfiguration);
+ Set<String> groups = ldapConfigurationService.checkGroupAttributes(userDn, ldapConfiguration);
return groups;
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/1ecd85c4/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AttributeDetector.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AttributeDetector.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AttributeDetector.java
index 1b28148..c694b17 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AttributeDetector.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AttributeDetector.java
@@ -29,7 +29,7 @@ public interface AttributeDetector<T> {
void collect(T entry);
/**
- * Implements the decision based on whiche the "best" possible attribute or value is selected.
+ * Implements the decision based on which the "best" possible attribute or value is selected.
*
* @return the most probable attribute name or value (based on the logic in the implementer)
*/
http://git-wip-us.apache.org/repos/asf/ambari/blob/1ecd85c4/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapAttributeDetectionService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapAttributeDetectionService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapAttributeDetectionService.java
index 90e3b8b..6cd369b 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapAttributeDetectionService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapAttributeDetectionService.java
@@ -19,24 +19,22 @@ import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
/**
* Contract defining operations to detect user and group attributes.
*/
-public interface LdapAttributeDetectionService<T> {
+public interface LdapAttributeDetectionService {
/**
* Decorates the passed in configuration with the detected ldap user attribute values
*
- * @param ldapConnection the connection instance to LDAP
* @param ambariLdapConfiguration configuration instance holding connection details
* @return the configuration decorated with user related attributes
*/
- AmbariLdapConfiguration detectLdapUserAttributes(T ldapConnection, AmbariLdapConfiguration ambariLdapConfiguration);
+ AmbariLdapConfiguration detectLdapUserAttributes(AmbariLdapConfiguration ambariLdapConfiguration);
/**
* Decorates the passed in configuration with the detected ldap group attribute values
*
- * @param ldapConnection the connection instance to LDAP
* @param ambariLdapConfiguration configuration instance holding connection details
* @return the configuration decorated with group related attributes
*/
- AmbariLdapConfiguration detectLdapGroupAttributes(T ldapConnection, AmbariLdapConfiguration ambariLdapConfiguration);
+ AmbariLdapConfiguration detectLdapGroupAttributes(AmbariLdapConfiguration ambariLdapConfiguration);
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/1ecd85c4/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConfigurationService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConfigurationService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConfigurationService.java
index 5c376c9..4b82aa2 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConfigurationService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConfigurationService.java
@@ -18,7 +18,6 @@ import java.util.Set;
import org.apache.ambari.server.AmbariException;
import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
-import org.apache.directory.ldap.client.api.LdapConnection;
/**
* Collection of operations for validating ldap configuration.
@@ -29,11 +28,10 @@ public interface LdapConfigurationService {
/**
* Tests the connection based on the provided configuration.
*
- * @param ldapConnection connection instance
- * @param configuration the ambari ldap configuration instance
+ * @param configuration the ambari ldap configuration instance
* @throws AmbariLdapException if the connection is not possible
*/
- void checkConnection(LdapConnection ldapConnection, AmbariLdapConfiguration configuration) throws AmbariLdapException;
+ void checkConnection(AmbariLdapConfiguration configuration) throws AmbariLdapException;
/**
@@ -41,20 +39,22 @@ public interface LdapConfigurationService {
* Implementers communicate with the LDAP server (search, bind) to validate attributes in the provided configuration
* instance
*
- * @param ldapConnection connection instance used to connect to the LDAP server
- * @param testUserName the test username
- * @param testPassword the test password
- * @param configuration the available ldap configuration
+ * @param testUserName the test username
+ * @param testPassword the test password
+ * @param configuration the available ldap configuration
* @return The DN of the found user entry
* @throws AmbariException if the connection couldn't be estabilisheds
*/
- String checkUserAttributes(LdapConnection ldapConnection, String testUserName, String testPassword, AmbariLdapConfiguration configuration) throws AmbariLdapException;
+ String checkUserAttributes(String testUserName, String testPassword, AmbariLdapConfiguration configuration) throws AmbariLdapException;
/**
* Checks whether the group related LDAP attributes in the configuration are correct.
*
- * @throws AmbariException if the attributes are not valid
+ * @param userDn
+ * @param ambariLdapConfiguration
+ * @return
+ * @throws AmbariLdapException
*/
- Set<String> checkGroupAttributes(LdapConnection ldapConnection, String userDn, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException;
+ Set<String> checkGroupAttributes(String userDn, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException;
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/1ecd85c4/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConnectionService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConnectionService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConnectionService.java
deleted file mode 100644
index 6f1e1ff..0000000
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConnectionService.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.ambari.server.ldap.service;
-
-import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
-import org.apache.directory.ldap.client.api.LdapConnection;
-
-/**
- * Contract defining factory methods for creating LDAP connection instances.
- * Implementers contain the logic of creating different connection instances and the afferent boilerplate code.
- */
-public interface LdapConnectionService {
-
- /**
- * Creates an LdapConnection instance based on the provided configuration
- *
- * @param ambariLdapConfiguration configuration instance with information for creating the connection instance
- * @return a set up LdapConnection instance
- */
- LdapConnection createLdapConnection(AmbariLdapConfiguration ambariLdapConfiguration);
-
- /**
- * Creates an LdapConnection instance and binds to the LDAP server based on the provided configuration entries
- *
- * @param ambariLdapConfiguration ambari configuration instance
- * @return
- */
- LdapConnection getBoundLdapConnection(AmbariLdapConfiguration ambariLdapConfiguration);
-
-
-}
http://git-wip-us.apache.org/repos/asf/ambari/blob/1ecd85c4/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConnectionTemplateProvider.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConnectionTemplateProvider.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConnectionTemplateProvider.java
new file mode 100644
index 0000000..5ed06e3
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConnectionTemplateProvider.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service;
+
+
+import javax.inject.Inject;
+import javax.inject.Provider;
+
+import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
+import org.apache.directory.ldap.client.api.DefaultLdapConnectionFactory;
+import org.apache.directory.ldap.client.api.LdapConnectionConfig;
+import org.apache.directory.ldap.client.api.LdapConnectionFactory;
+import org.apache.directory.ldap.client.api.LdapConnectionPool;
+import org.apache.directory.ldap.client.api.ValidatingPoolableLdapConnectionFactory;
+import org.apache.directory.ldap.client.template.LdapConnectionTemplate;
+
+public class LdapConnectionTemplateProvider implements Provider<LdapConnectionTemplate> {
+
+ // Inject the persisted configuration (when available) check the provider implementation for details.
+ @Inject
+ private Provider<AmbariLdapConfiguration> ambariLdapConfigurationProvider;
+
+ @Override
+ public LdapConnectionTemplate get() {
+ return new LdapConnectionTemplate(new LdapConnectionPool(
+ new ValidatingPoolableLdapConnectionFactory(getLdapConnectionFactory())));
+ }
+
+ private LdapConnectionConfig getLdapConnectionConfig() {
+ LdapConnectionConfig config = new LdapConnectionConfig();
+ config.setLdapHost(ambariLdapConfigurationProvider.get().serverHost());
+ config.setLdapPort(ambariLdapConfigurationProvider.get().serverPort());
+ config.setName(ambariLdapConfigurationProvider.get().bindDn());
+ config.setCredentials(ambariLdapConfigurationProvider.get().bindPassword());
+
+ return config;
+ }
+
+ private LdapConnectionFactory getLdapConnectionFactory() {
+ return new DefaultLdapConnectionFactory(getLdapConnectionConfig());
+ }
+
+
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/1ecd85c4/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionService.java
index cddb952..639d48d 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionService.java
@@ -14,6 +14,8 @@
package org.apache.ambari.server.ldap.service.ads;
+import java.util.List;
+
import javax.inject.Inject;
import javax.inject.Singleton;
@@ -27,27 +29,23 @@ import org.apache.ambari.server.ldap.service.ads.detectors.GroupObjectClassDetec
import org.apache.ambari.server.ldap.service.ads.detectors.UserGroupMemberAttrDetector;
import org.apache.ambari.server.ldap.service.ads.detectors.UserNameAttrDetector;
import org.apache.ambari.server.ldap.service.ads.detectors.UserObjectClassDetector;
-import org.apache.directory.api.ldap.model.cursor.SearchCursor;
import org.apache.directory.api.ldap.model.entry.Entry;
-import org.apache.directory.api.ldap.model.message.Response;
+import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.api.ldap.model.message.SearchRequest;
-import org.apache.directory.api.ldap.model.message.SearchRequestImpl;
-import org.apache.directory.api.ldap.model.message.SearchResultEntry;
import org.apache.directory.api.ldap.model.message.SearchScope;
-import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.api.util.Strings;
-import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.search.FilterBuilder;
+import org.apache.directory.ldap.client.template.EntryMapper;
+import org.apache.directory.ldap.client.template.LdapConnectionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
-public class DefaultLdapAttributeDetectionService implements LdapAttributeDetectionService<LdapConnection> {
+public class DefaultLdapAttributeDetectionService implements LdapAttributeDetectionService {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultLdapAttributeDetectionService.class);
private static final int SAMPLE_RESULT_SIZE = 50;
-
@Inject
private UserNameAttrDetector userNameAttrDetector;
@@ -67,12 +65,18 @@ public class DefaultLdapAttributeDetectionService implements LdapAttributeDetect
private GroupMemberAttrDetector groupMemberAttrDetector;
@Inject
+ private LdapConnectionTemplateFactory ldapConnectionTemplateFactory;
+
+
+ @Inject
public DefaultLdapAttributeDetectionService() {
}
@Override
- public AmbariLdapConfiguration detectLdapUserAttributes(LdapConnection connection, AmbariLdapConfiguration ambariLdapConfiguration) {
+ public AmbariLdapConfiguration detectLdapUserAttributes(AmbariLdapConfiguration ambariLdapConfiguration) {
LOGGER.info("Detecting LDAP user attributes ...");
+ LdapConnectionTemplate ldapConnectionTemplate = ldapConnectionTemplateFactory.create(ambariLdapConfiguration);
+
// perform a search using the user search base
if (Strings.isEmpty(ambariLdapConfiguration.userSearchBase())) {
@@ -80,37 +84,21 @@ public class DefaultLdapAttributeDetectionService implements LdapAttributeDetect
return ambariLdapConfiguration;
}
- SearchCursor searchCursor = null;
-
try {
- SearchRequest searchRequest = assembleUserSearchRequest(ambariLdapConfiguration);
+ SearchRequest searchRequest = assembleUserSearchRequest(ldapConnectionTemplate, ambariLdapConfiguration);
// do the search
- searchCursor = connection.search(searchRequest);
-
- int processedUserCnt = 0;
-
- while (searchCursor.next()) {
+ List<Entry> entries = ldapConnectionTemplate.search(searchRequest, getEntryMapper());
- if (processedUserCnt >= SAMPLE_RESULT_SIZE) {
- LOGGER.debug("The maximum count of results for attribute detection has exceeded. Quit user attribute detection.");
- break;
- }
+ for (Entry entry : entries) {
- Response response = searchCursor.get();
- // process the SearchResultEntry
+ LOGGER.info("Processing sample entry with dn: [{}]", entry.getDn());
- if (response instanceof SearchResultEntry) {
- Entry resultEntry = ((SearchResultEntry) response).getEntry();
- LOGGER.info("Processing sample entry with dn: [{}]", resultEntry.getDn());
+ userNameAttrDetector.collect(entry);
+ userObjectClassDetector.collect(entry);
+ userGroupMemberAttrDetector.collect(entry);
- userNameAttrDetector.collect(resultEntry);
- userObjectClassDetector.collect(resultEntry);
- userGroupMemberAttrDetector.collect(resultEntry);
-
- processedUserCnt++;
- }
}
ambariLdapConfiguration.setValueFor(AmbariLdapConfigKeys.USER_NAME_ATTRIBUTE, userNameAttrDetector.detect());
@@ -120,13 +108,7 @@ public class DefaultLdapAttributeDetectionService implements LdapAttributeDetect
LOGGER.info("Decorated ambari ldap config : [{}]", ambariLdapConfiguration);
} catch (Exception e) {
-
LOGGER.error("Ldap operation failed", e);
- } finally {
- // housekeeping
- if (null != searchCursor) {
- searchCursor.close();
- }
}
return ambariLdapConfiguration;
@@ -134,7 +116,7 @@ public class DefaultLdapAttributeDetectionService implements LdapAttributeDetect
@Override
- public AmbariLdapConfiguration detectLdapGroupAttributes(LdapConnection connection, AmbariLdapConfiguration ambariLdapConfiguration) {
+ public AmbariLdapConfiguration detectLdapGroupAttributes(AmbariLdapConfiguration ambariLdapConfiguration) {
LOGGER.info("Detecting LDAP group attributes ...");
// perform a search using the user search base
@@ -143,39 +125,23 @@ public class DefaultLdapAttributeDetectionService implements LdapAttributeDetect
return ambariLdapConfiguration;
}
- SearchCursor searchCursor = null;
+ LdapConnectionTemplate ldapConnectionTemplate = ldapConnectionTemplateFactory.create(ambariLdapConfiguration);
try {
- // todo should the bind operation be done in the facade?
- connection.bind(ambariLdapConfiguration.bindDn(), ambariLdapConfiguration.bindPassword());
- SearchRequest searchRequest = assembleGroupSearchRequest(ambariLdapConfiguration);
+ SearchRequest searchRequest = assembleGroupSearchRequest(ldapConnectionTemplate, ambariLdapConfiguration);
// do the search
- searchCursor = connection.search(searchRequest);
-
- int processedGroupCnt = 0;
-
- while (searchCursor.next()) {
+ List<Entry> groupEntries = ldapConnectionTemplate.search(searchRequest, getEntryMapper());
- if (processedGroupCnt >= SAMPLE_RESULT_SIZE) {
- LOGGER.debug("The maximum number of results for attribute detection has exceeded. Quit detection.");
- break;
- }
- Response response = searchCursor.get();
- // process the SearchResultEntry
+ for (Entry groupEntry : groupEntries) {
- if (response instanceof SearchResultEntry) {
- Entry resultEntry = ((SearchResultEntry) response).getEntry();
- LOGGER.info("Processing sample entry with dn: [{}]", resultEntry.getDn());
+ LOGGER.info("Processing sample entry with dn: [{}]", groupEntry.getDn());
+ groupNameAttrDetector.collect(groupEntry);
+ groupObjectClassDetector.collect(groupEntry);
+ groupMemberAttrDetector.collect(groupEntry);
- groupNameAttrDetector.collect(resultEntry);
- groupObjectClassDetector.collect(resultEntry);
- groupMemberAttrDetector.collect(resultEntry);
-
- processedGroupCnt++;
- }
}
ambariLdapConfiguration.setValueFor(AmbariLdapConfigKeys.GROUP_NAME_ATTRIBUTE, groupNameAttrDetector.detect());
@@ -187,26 +153,17 @@ public class DefaultLdapAttributeDetectionService implements LdapAttributeDetect
} catch (Exception e) {
LOGGER.error("Ldap operation failed", e);
- } finally {
- // housekeeping
- if (null != searchCursor) {
- searchCursor.close();
- }
}
return ambariLdapConfiguration;
}
- private SearchRequest assembleUserSearchRequest(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
+ private SearchRequest assembleUserSearchRequest(LdapConnectionTemplate ldapConnectionTemplate, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
try {
- SearchRequest req = new SearchRequestImpl();
- req.setScope(SearchScope.SUBTREE);
- req.addAttributes("*");
- req.setTimeLimit(0);
- req.setBase(new Dn(ambariLdapConfiguration.userSearchBase()));
- // the filter must be set!
- req.setFilter(FilterBuilder.present(ambariLdapConfiguration.dnAttribute()).toString());
+ SearchRequest req = ldapConnectionTemplate.newSearchRequest(ambariLdapConfiguration.userSearchBase(),
+ FilterBuilder.present(ambariLdapConfiguration.dnAttribute()).toString(), SearchScope.SUBTREE);
+ req.setSizeLimit(SAMPLE_RESULT_SIZE);
return req;
@@ -216,16 +173,12 @@ public class DefaultLdapAttributeDetectionService implements LdapAttributeDetect
}
}
- private SearchRequest assembleGroupSearchRequest(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
+ private SearchRequest assembleGroupSearchRequest(LdapConnectionTemplate ldapConnectionTemplate, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
try {
- SearchRequest req = new SearchRequestImpl();
- req.setScope(SearchScope.SUBTREE);
- req.addAttributes("*");
- req.setTimeLimit(0);
- req.setBase(new Dn(ambariLdapConfiguration.groupSearchBase()));
- // the filter must be set!
- req.setFilter(FilterBuilder.present(ambariLdapConfiguration.dnAttribute()).toString());
+ SearchRequest req = ldapConnectionTemplate.newSearchRequest(ambariLdapConfiguration.groupSearchBase(),
+ FilterBuilder.present(ambariLdapConfiguration.dnAttribute()).toString(), SearchScope.SUBTREE);
+ req.setSizeLimit(SAMPLE_RESULT_SIZE);
return req;
@@ -236,4 +189,12 @@ public class DefaultLdapAttributeDetectionService implements LdapAttributeDetect
}
+ public EntryMapper<Entry> getEntryMapper() {
+ return new EntryMapper<Entry>() {
+ @Override
+ public Entry map(Entry entry) throws LdapException {
+ return entry;
+ }
+ };
+ }
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/1ecd85c4/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
index 7214fd3..bbe4d0a 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
@@ -14,6 +14,7 @@
package org.apache.ambari.server.ldap.service.ads;
+import java.util.HashSet;
import java.util.List;
import java.util.Set;
@@ -23,23 +24,22 @@ import javax.inject.Singleton;
import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
import org.apache.ambari.server.ldap.service.AmbariLdapException;
import org.apache.ambari.server.ldap.service.LdapConfigurationService;
-import org.apache.directory.api.ldap.codec.decorators.SearchResultEntryDecorator;
import org.apache.directory.api.ldap.model.constants.SchemaConstants;
-import org.apache.directory.api.ldap.model.cursor.EntryCursor;
-import org.apache.directory.api.ldap.model.cursor.SearchCursor;
import org.apache.directory.api.ldap.model.entry.Entry;
-import org.apache.directory.api.ldap.model.message.Response;
+import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.api.ldap.model.message.SearchRequest;
import org.apache.directory.api.ldap.model.message.SearchRequestImpl;
import org.apache.directory.api.ldap.model.message.SearchScope;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.search.FilterBuilder;
+import org.apache.directory.ldap.client.template.ConnectionCallback;
+import org.apache.directory.ldap.client.template.EntryMapper;
+import org.apache.directory.ldap.client.template.LdapConnectionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Lists;
-import com.google.common.collect.Sets;
/**
* Implementation of the validation logic using the Apache Directory API.
@@ -50,13 +50,27 @@ public class DefaultLdapConfigurationService implements LdapConfigurationService
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultLdapConfigurationService.class);
@Inject
+ private LdapConnectionTemplateFactory ldapConnectionTemplateFactory;
+
+ @Inject
public DefaultLdapConfigurationService() {
}
+
@Override
- public void checkConnection(LdapConnection ldapConnection, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
+ public void checkConnection(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
+
+ LdapConnectionTemplate ldapConnectionTemplate = ldapConnectionTemplateFactory.create(ambariLdapConfiguration);
- if (!ldapConnection.isConnected()) {
+ // check if the connection from the connection pool of the template is connected
+ Boolean isConnected = ldapConnectionTemplate.execute(new ConnectionCallback<Boolean>() {
+ @Override
+ public Boolean doWithConnection(LdapConnection connection) throws LdapException {
+ return connection.isConnected();
+ }
+ });
+
+ if (!isConnected) {
LOGGER.error("Could not connect to the LDAP server");
throw new AmbariLdapException("Could not connect to the LDAP server. Configuration: " + ambariLdapConfiguration);
}
@@ -69,7 +83,6 @@ public class DefaultLdapConfigurationService implements LdapConfigurationService
*
* Invalid attributes are signaled by throwing an exception.
*
- * @param ldapConnection connection instance used to connect to the LDAP server
* @param testUserName the test username
* @param testPassword the test password
* @param ambariLdapConfiguration the available LDAP configuration to be validated
@@ -77,9 +90,8 @@ public class DefaultLdapConfigurationService implements LdapConfigurationService
* @throws AmbariLdapException if an error occurs
*/
@Override
- public String checkUserAttributes(LdapConnection ldapConnection, String testUserName, String testPassword, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
- String userDn = null;
- EntryCursor entryCursor = null;
+ public String checkUserAttributes(String testUserName, String testPassword, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
+ String userDn;
try {
LOGGER.info("Checking user attributes for user {} r ...", testUserName);
@@ -90,33 +102,15 @@ public class DefaultLdapConfigurationService implements LdapConfigurationService
.toString();
LOGGER.info("Searching for the user: {} using the search filter: {}", testUserName, filter);
- entryCursor = ldapConnection.search(new Dn(ambariLdapConfiguration.userSearchBase()), filter, SearchScope.SUBTREE);
+ userDn = ldapConnectionTemplateFactory.create(ambariLdapConfiguration).searchFirst(new Dn(ambariLdapConfiguration.userSearchBase()), filter, SearchScope.SUBTREE, getUserDnNameEntryMapper(ambariLdapConfiguration));
- // collecting search result entries
- List<Entry> users = Lists.newArrayList();
- for (Entry entry : entryCursor) {
- users.add(entry);
- userDn = entry.getDn().getNormName();
- }
-
- // there should be at least one user found
- if (users.isEmpty()) {
- String msg = String.format("There are no users found using the filter: [ %s ]. Try changing the attribute values", filter);
- LOGGER.error(msg);
- throw new Exception(msg);
- }
-
- LOGGER.info("Attibute validation succeeded. Filter: {}", filter);
+ LOGGER.info("Attribute validation succeeded. Filter: {}", filter);
} catch (Exception e) {
LOGGER.error("User attributes validation failed.", e);
throw new AmbariLdapException(e.getMessage(), e);
- } finally {
- if (null != entryCursor) {
- entryCursor.close();
- }
}
return userDn;
}
@@ -125,17 +119,14 @@ public class DefaultLdapConfigurationService implements LdapConfigurationService
* Checks whether the provided group related settings are correct.
* The algorithm implemented in this method per
*
- * @param ldapConnection a connecion instance bound to an LDAP server
* @param userDn a user DN to check
* @param ambariLdapConfiguration the available LDAP configuration to be validated
* @return
* @throws AmbariLdapException
*/
@Override
- public Set<String> checkGroupAttributes(LdapConnection ldapConnection, String userDn, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
- SearchCursor searchCursor = null;
- Set<Response> groupResponses = Sets.newHashSet();
-
+ public Set<String> checkGroupAttributes(String userDn, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
+ List<String> groups = Lists.newArrayList();
try {
LOGGER.info("Checking group attributes for user dn {} ...", userDn);
@@ -156,43 +147,42 @@ public class DefaultLdapConfigurationService implements LdapConfigurationService
searchRequest.addAttributes(ambariLdapConfiguration.groupMemberAttribute(), ambariLdapConfiguration.groupNameAttribute());
// perform the search
- searchCursor = ldapConnection.search(searchRequest);
+ groups = ldapConnectionTemplateFactory.create(ambariLdapConfiguration).search(searchRequest, getGroupNameEntryMapper(ambariLdapConfiguration));
- for (Response response : searchCursor) {
- groupResponses.add(response);
- }
} catch (Exception e) {
LOGGER.error("User attributes validation failed.", e);
throw new AmbariLdapException(e.getMessage(), e);
- } finally {
- if (null != searchCursor) {
- searchCursor.close();
- }
}
- return processGroupResults(groupResponses, ambariLdapConfiguration);
+ return new HashSet<>(groups);
}
- /**
- * Extracts meaningful values from the search result.
- *
- * @param groupResponses the result entries returned by the search
- * @param ambariLdapConfiguration holds the keys of the meaningful attributes
- * @return a set with the group names the test user belongs to
- */
- private Set<String> processGroupResults(Set<Response> groupResponses, AmbariLdapConfiguration ambariLdapConfiguration) {
- Set<String> groupStrSet = Sets.newHashSet();
- for (Response response : groupResponses) {
- Entry entry = ((SearchResultEntryDecorator) response).getEntry();
- groupStrSet.add(entry.get(ambariLdapConfiguration.groupNameAttribute()).get().getString());
- }
+ private EntryMapper<String> getGroupNameEntryMapper(AmbariLdapConfiguration ambariLdapConfiguration) {
+
+ EntryMapper<String> entryMapper = new EntryMapper<String>() {
+ @Override
+ public String map(Entry entry) throws LdapException {
+ return entry.get(ambariLdapConfiguration.groupNameAttribute()).get().getString();
+ }
+ };
+
+ return entryMapper;
+ }
+
+ private EntryMapper<String> getUserDnNameEntryMapper(AmbariLdapConfiguration ambariLdapConfiguration) {
+
+ EntryMapper<String> entryMapper = new EntryMapper<String>() {
+ @Override
+ public String map(Entry entry) throws LdapException {
+ return entry.getDn().getNormName();
+ }
+ };
- LOGGER.debug("Extracted group names from group search responses: {}", groupStrSet);
- return groupStrSet;
+ return entryMapper;
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/1ecd85c4/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConnectionService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConnectionService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConnectionService.java
deleted file mode 100644
index 1e9c612..0000000
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConnectionService.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.ambari.server.ldap.service.ads;
-
-import javax.inject.Singleton;
-
-import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
-import org.apache.ambari.server.ldap.service.LdapConnectionService;
-import org.apache.directory.ldap.client.api.LdapConnection;
-import org.apache.directory.ldap.client.api.LdapConnectionConfig;
-import org.apache.directory.ldap.client.api.LdapNetworkConnection;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-@Singleton
-public class DefaultLdapConnectionService implements LdapConnectionService {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(DefaultLdapConnectionService.class);
-
- @Override
- public LdapNetworkConnection createLdapConnection(AmbariLdapConfiguration ambariLdapConfiguration) {
- LOGGER.debug("Creating ldap connection instance from: {}", ambariLdapConfiguration);
-
- return new LdapNetworkConnection(getLdapConnectionConfig(ambariLdapConfiguration));
- }
-
- @Override
- public LdapConnection getBoundLdapConnection(AmbariLdapConfiguration ambariLdapConfiguration) {
- LOGGER.info("Creating LDAP connection instance and binding to LDAP server ...");
-
- try {
- LdapConnection connection = createLdapConnection(ambariLdapConfiguration);
-
- if (!ambariLdapConfiguration.anonymousBind()) {
-
- LOGGER.debug("Anonymous binding not supported, binding with the manager detailas...");
- connection.bind(ambariLdapConfiguration.bindDn(), ambariLdapConfiguration.bindPassword());
-
- } else {
-
- LOGGER.debug("Binding anonymously ...");
- connection.bind();
-
- }
-
- if (!connection.isConnected()) {
-
- LOGGER.error("Not connected to the LDAP server. Connection instance: {}", connection);
- throw new IllegalStateException("The connection to the LDAP server is not alive");
-
- }
-
- LOGGER.info("Connected / bound to LDAP server.");
- return connection;
-
- } catch (Exception e) {
- LOGGER.error("Could not create or bind LdapConnection", e);
- throw new IllegalArgumentException(e);
- }
-
- }
-
- private LdapConnectionConfig getLdapConnectionConfig(AmbariLdapConfiguration ambariAmbariLdapConfiguration) {
- LOGGER.debug("Creating a LDAP connection config instance based on the ambari configuration: {}", ambariAmbariLdapConfiguration);
-
- LdapConnectionConfig ldapConnectionConfig = new LdapConnectionConfig();
- ldapConnectionConfig.setLdapHost(ambariAmbariLdapConfiguration.serverHost());
- ldapConnectionConfig.setLdapPort(ambariAmbariLdapConfiguration.serverPort());
- ldapConnectionConfig.setUseSsl(ambariAmbariLdapConfiguration.useSSL());
-
- return ldapConnectionConfig;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/ambari/blob/1ecd85c4/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/LdapConnectionTemplateFactory.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/LdapConnectionTemplateFactory.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/LdapConnectionTemplateFactory.java
new file mode 100644
index 0000000..50345bc
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/LdapConnectionTemplateFactory.java
@@ -0,0 +1,95 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service.ads;
+
+import javax.inject.Inject;
+import javax.inject.Provider;
+import javax.inject.Singleton;
+
+import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
+import org.apache.directory.ldap.client.api.DefaultLdapConnectionFactory;
+import org.apache.directory.ldap.client.api.LdapConnectionConfig;
+import org.apache.directory.ldap.client.api.LdapConnectionFactory;
+import org.apache.directory.ldap.client.api.LdapConnectionPool;
+import org.apache.directory.ldap.client.api.ValidatingPoolableLdapConnectionFactory;
+import org.apache.directory.ldap.client.template.LdapConnectionTemplate;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Factory for creating LdapConnectionTemplate instances.
+ * Depending on the usage context, the instance can be constructed based on the provided configuration or based on the persisted settings.
+ */
+@Singleton
+public class LdapConnectionTemplateFactory {
+
+ private static final Logger LOG = LoggerFactory.getLogger(LdapConnectionTemplateFactory.class);
+
+ @Inject
+ private Provider<LdapConnectionTemplate> ldapConnectionTemplate;
+
+ @Inject
+ public LdapConnectionTemplateFactory() {
+ }
+
+ /**
+ * Creates a new instance based on the provided configuration. Use this factory method whle operating with ambari configuration not yet persisted.
+ *
+ * @param ambariLdapConfiguration ambari ldap configuration instance
+ * @return an instance of LdapConnectionTemplate
+ */
+ public LdapConnectionTemplate create(AmbariLdapConfiguration ambariLdapConfiguration) {
+ LOG.info("Constructing new instance based on the provided ambari ldap configuration: {}", ambariLdapConfiguration);
+
+ // create the connection config
+ LdapConnectionConfig ldapConnectionConfig = getLdapConnectionConfig(ambariLdapConfiguration);
+
+ // create the connection factory
+ LdapConnectionFactory ldapConnectionFactory = new DefaultLdapConnectionFactory(ldapConnectionConfig);
+
+ // create the connection pool
+ LdapConnectionPool ldapConnectionPool = new LdapConnectionPool(new ValidatingPoolableLdapConnectionFactory(ldapConnectionFactory));
+
+ LdapConnectionTemplate template = new LdapConnectionTemplate(ldapConnectionPool);
+ LOG.info("Ldap connection template instance: {}", template);
+
+ return template;
+
+ }
+
+ public LdapConnectionTemplate load() {
+ // the construction logic is implemented in the provider class
+ return ldapConnectionTemplate.get();
+ }
+
+
+ private LdapConnectionConfig getLdapConnectionConfig(AmbariLdapConfiguration ambariLdapConfiguration) {
+
+ LdapConnectionConfig config = new LdapConnectionConfig();
+ config.setLdapHost(ambariLdapConfiguration.serverHost());
+ config.setLdapPort(ambariLdapConfiguration.serverPort());
+ config.setName(ambariLdapConfiguration.bindDn());
+ config.setCredentials(ambariLdapConfiguration.bindPassword());
+
+ // todo set the other required properties here, eg.: trustmanager
+ return config;
+ }
+
+ private LdapConnectionFactory getLdapConnectionFactory(AmbariLdapConfiguration ambariLdapConfiguration) {
+ return new DefaultLdapConnectionFactory(getLdapConnectionConfig(ambariLdapConfiguration));
+ }
+
+
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/1ecd85c4/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupMemberAttrDetector.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupMemberAttrDetector.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupMemberAttrDetector.java
index aa444ab..9f38357 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupMemberAttrDetector.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupMemberAttrDetector.java
@@ -18,7 +18,7 @@ import javax.inject.Inject;
import org.apache.directory.api.ldap.model.entry.Entry;
-public class GroupMemberAttrDetector extends OccurranceAndWeightBasedDetector {
+public class GroupMemberAttrDetector extends OccurrenceAndWeightBasedDetector {
private enum GroupMemberAttr {
@@ -47,7 +47,7 @@ public class GroupMemberAttrDetector extends OccurranceAndWeightBasedDetector {
@Inject
public GroupMemberAttrDetector() {
for (GroupMemberAttr groupMemberAttr : GroupMemberAttr.values()) {
- occurranceMap().put(groupMemberAttr.attrName(), 0);
+ occurrenceMap().put(groupMemberAttr.attrName(), 0);
weightsMap().put(groupMemberAttr.attrName(), groupMemberAttr.weight());
}
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/1ecd85c4/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupNameAttrDetector.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupNameAttrDetector.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupNameAttrDetector.java
index d4dcdff..0f48348 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupNameAttrDetector.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupNameAttrDetector.java
@@ -20,7 +20,7 @@ import org.apache.directory.api.ldap.model.entry.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class GroupNameAttrDetector extends OccurranceAndWeightBasedDetector {
+public class GroupNameAttrDetector extends OccurrenceAndWeightBasedDetector {
private static final Logger LOGGER = LoggerFactory.getLogger(UserNameAttrDetector.class);
private enum GroupNameAttr {
@@ -51,7 +51,7 @@ public class GroupNameAttrDetector extends OccurranceAndWeightBasedDetector {
public GroupNameAttrDetector() {
for (GroupNameAttr groupNameAttr : GroupNameAttr.values()) {
- occurranceMap().put(groupNameAttr.attrName(), 0);
+ occurrenceMap().put(groupNameAttr.attrName(), 0);
weightsMap().put(groupNameAttr.attrName(), groupNameAttr.weight());
}
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/1ecd85c4/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupObjectClassDetector.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupObjectClassDetector.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupObjectClassDetector.java
index 88824c4..9338e70 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupObjectClassDetector.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupObjectClassDetector.java
@@ -20,7 +20,7 @@ import org.apache.directory.api.ldap.model.entry.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class GroupObjectClassDetector extends OccurranceAndWeightBasedDetector {
+public class GroupObjectClassDetector extends OccurrenceAndWeightBasedDetector {
private static final Logger LOGGER = LoggerFactory.getLogger(GroupObjectClassDetector.class);
@@ -55,7 +55,7 @@ public class GroupObjectClassDetector extends OccurranceAndWeightBasedDetector {
@Inject
public GroupObjectClassDetector() {
for (ObjectClassValue ocVal : ObjectClassValue.values()) {
- occurranceMap().put(ocVal.ocVal(), 0);
+ occurrenceMap().put(ocVal.ocVal(), 0);
weightsMap().put(ocVal.ocVal(), ocVal.weight());
}
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/1ecd85c4/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/OccurranceAndWeightBasedDetector.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/OccurranceAndWeightBasedDetector.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/OccurranceAndWeightBasedDetector.java
deleted file mode 100644
index 71dfb42..0000000
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/OccurranceAndWeightBasedDetector.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.ambari.server.ldap.service.ads.detectors;
-
-import java.util.Map;
-
-import org.apache.ambari.server.ldap.service.AttributeDetector;
-import org.apache.directory.api.ldap.model.entry.Entry;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.Maps;
-
-public abstract class OccurranceAndWeightBasedDetector implements AttributeDetector<Entry> {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(OccurranceAndWeightBasedDetector.class);
-
- private Map<String, Integer> occurranceMap = Maps.newHashMap();
- private Map<String, Integer> weightsMap = Maps.newHashMap();
-
- protected Map<String, Integer> occurranceMap() {
- return occurranceMap;
- }
-
- protected Map<String, Integer> weightsMap() {
- return weightsMap;
- }
-
-
- protected abstract boolean applies(Entry entry, String value);
-
- @Override
- public String detect() {
- LOGGER.info("Calculating the most probable attribute/value ...");
- Map.Entry<String, Integer> selectedEntry = null;
-
- for (Map.Entry<String, Integer> entry : occurranceMap().entrySet()) {
- if (selectedEntry == null) {
-
- selectedEntry = entry;
- LOGGER.debug("Initial attribute / value entry: {}", selectedEntry);
- continue;
-
- }
-
- if (selectedEntry.getValue() < entry.getValue()) {
-
- LOGGER.info("Changing potential attribute / value entry from : [{}] to: [{}]", selectedEntry, entry);
- selectedEntry = entry;
-
- }
- }
-
- // check whether the selected entry is valid (has occured in the sample result set)
- String detectedVal = "N/A";
-
- if (selectedEntry.getValue() > 0) {
- detectedVal = selectedEntry.getKey();
- } else {
- LOGGER.warn("Unable to detect attribute or attribute value");
- }
-
- LOGGER.info("Detected attribute or value: [{}]", detectedVal);
- return detectedVal;
- }
-
- @Override
- public void collect(Entry entry) {
- LOGGER.info("Collecting ldap attributes/values form entry with dn: [{}]", entry.getDn());
-
- for (String attributeValue : occurranceMap().keySet()) {
- if (applies(entry, attributeValue)) {
-
- Integer cnt = occurranceMap().get(attributeValue).intValue();
- if (weightsMap().containsKey(attributeValue)) {
- cnt = cnt + weightsMap().get(attributeValue);
- } else {
- cnt = cnt + 1;
- }
- occurranceMap().put(attributeValue, cnt);
-
- LOGGER.info("Collected potential name attr: {}, count: {}", attributeValue, cnt);
-
- } else {
- LOGGER.info("The result entry doesn't contain the attribute: [{}]", attributeValue);
- }
- }
- }
-
-
-}
http://git-wip-us.apache.org/repos/asf/ambari/blob/1ecd85c4/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/OccurrenceAndWeightBasedDetector.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/OccurrenceAndWeightBasedDetector.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/OccurrenceAndWeightBasedDetector.java
new file mode 100644
index 0000000..2ec559b
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/OccurrenceAndWeightBasedDetector.java
@@ -0,0 +1,103 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service.ads.detectors;
+
+import java.util.Map;
+
+import org.apache.ambari.server.ldap.service.AttributeDetector;
+import org.apache.directory.api.ldap.model.entry.Entry;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.collect.Maps;
+
+public abstract class OccurrenceAndWeightBasedDetector implements AttributeDetector<Entry> {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(OccurrenceAndWeightBasedDetector.class);
+
+ private Map<String, Integer> occurranceMap = Maps.newHashMap();
+ private Map<String, Integer> weightsMap = Maps.newHashMap();
+
+ protected Map<String, Integer> occurrenceMap() {
+ return occurranceMap;
+ }
+
+ protected Map<String, Integer> weightsMap() {
+ return weightsMap;
+ }
+
+
+ protected abstract boolean applies(Entry entry, String value);
+
+ @Override
+ public String detect() {
+ LOGGER.info("Calculating the most probable attribute/value ...");
+ Map.Entry<String, Integer> selectedEntry = null;
+
+ for (Map.Entry<String, Integer> entry : occurrenceMap().entrySet()) {
+ if (selectedEntry == null) {
+
+ selectedEntry = entry;
+ LOGGER.debug("Initial attribute / value entry: {}", selectedEntry);
+ continue;
+
+ }
+
+ if (selectedEntry.getValue() < entry.getValue()) {
+
+ LOGGER.info("Changing potential attribute / value entry from : [{}] to: [{}]", selectedEntry, entry);
+ selectedEntry = entry;
+
+ }
+ }
+
+ // check whether the selected entry is valid (has occured in the sample result set)
+ String detectedVal = "N/A";
+
+ if (selectedEntry.getValue() > 0) {
+ detectedVal = selectedEntry.getKey();
+ } else {
+ LOGGER.warn("Unable to detect attribute or attribute value");
+ }
+
+ LOGGER.info("Detected attribute or value: [{}]", detectedVal);
+ return detectedVal;
+ }
+
+ @Override
+ public void collect(Entry entry) {
+ LOGGER.info("Collecting ldap attributes/values form entry with dn: [{}]", entry.getDn());
+
+ for (String attributeValue : occurrenceMap().keySet()) {
+ if (applies(entry, attributeValue)) {
+
+ Integer cnt = occurrenceMap().get(attributeValue).intValue();
+ if (weightsMap().containsKey(attributeValue)) {
+ cnt = cnt + weightsMap().get(attributeValue);
+ } else {
+ cnt = cnt + 1;
+ }
+ occurrenceMap().put(attributeValue, cnt);
+
+ LOGGER.info("Collected potential name attr: {}, count: {}", attributeValue, cnt);
+
+ } else {
+ LOGGER.info("The result entry doesn't contain the attribute: [{}]", attributeValue);
+ }
+ }
+ }
+
+
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/1ecd85c4/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserGroupMemberAttrDetector.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserGroupMemberAttrDetector.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserGroupMemberAttrDetector.java
index a7f03dd..f04201e 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserGroupMemberAttrDetector.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserGroupMemberAttrDetector.java
@@ -18,7 +18,7 @@ import javax.inject.Inject;
import org.apache.directory.api.ldap.model.entry.Entry;
-public class UserGroupMemberAttrDetector extends OccurranceAndWeightBasedDetector {
+public class UserGroupMemberAttrDetector extends OccurrenceAndWeightBasedDetector {
private enum UserGroupMemberAttr {
@@ -46,7 +46,7 @@ public class UserGroupMemberAttrDetector extends OccurranceAndWeightBasedDetecto
@Inject
public UserGroupMemberAttrDetector() {
for (UserGroupMemberAttr userGroupMemberAttr : UserGroupMemberAttr.values()) {
- occurranceMap().put(userGroupMemberAttr.attrName(), 0);
+ occurrenceMap().put(userGroupMemberAttr.attrName(), 0);
weightsMap().put(userGroupMemberAttr.attrName(), userGroupMemberAttr.weight);
}
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/1ecd85c4/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserNameAttrDetector.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserNameAttrDetector.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserNameAttrDetector.java
index eade3c8..2c41162 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserNameAttrDetector.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserNameAttrDetector.java
@@ -20,7 +20,7 @@ import org.apache.directory.api.ldap.model.entry.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class UserNameAttrDetector extends OccurranceAndWeightBasedDetector {
+public class UserNameAttrDetector extends OccurrenceAndWeightBasedDetector {
private static final Logger LOGGER = LoggerFactory.getLogger(UserNameAttrDetector.class);
private enum UserNameAttrs {
@@ -49,7 +49,7 @@ public class UserNameAttrDetector extends OccurranceAndWeightBasedDetector {
@Inject
public UserNameAttrDetector() {
for (UserNameAttrs nameAttr : UserNameAttrs.values()) {
- occurranceMap().put(nameAttr.attrName(), 0);
+ occurrenceMap().put(nameAttr.attrName(), 0);
weightsMap().put(nameAttr.attrName(), nameAttr.weight());
}
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/1ecd85c4/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserObjectClassDetector.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserObjectClassDetector.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserObjectClassDetector.java
index 97b3c52..2b47671 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserObjectClassDetector.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserObjectClassDetector.java
@@ -20,7 +20,7 @@ import org.apache.directory.api.ldap.model.entry.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class UserObjectClassDetector extends OccurranceAndWeightBasedDetector {
+public class UserObjectClassDetector extends OccurrenceAndWeightBasedDetector {
private static final Logger LOGGER = LoggerFactory.getLogger(UserObjectClassDetector.class);
@@ -49,7 +49,7 @@ public class UserObjectClassDetector extends OccurranceAndWeightBasedDetector {
@Inject
public UserObjectClassDetector() {
for (ObjectClassValue ocVal : ObjectClassValue.values()) {
- occurranceMap().put(ocVal.ocVal(), 0);
+ occurrenceMap().put(ocVal.ocVal(), 0);
weightsMap().put(ocVal.ocVal(), ocVal.weight());
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/1ecd85c4/ambari-server/src/test/java/org/apache/ambari/server/ldap/LdapModuleFunctionalTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/LdapModuleFunctionalTest.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/LdapModuleFunctionalTest.java
new file mode 100644
index 0000000..8059723
--- /dev/null
+++ b/ambari-server/src/test/java/org/apache/ambari/server/ldap/LdapModuleFunctionalTest.java
@@ -0,0 +1,143 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap;
+
+import java.util.Map;
+
+import org.apache.ambari.server.ldap.domain.AmbariLdapConfigKeys;
+import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.domain.TestAmbariAmbariLdapConfigurationFactory;
+import org.apache.ambari.server.ldap.service.LdapConfigurationService;
+import org.apache.ambari.server.ldap.service.LdapFacade;
+import org.apache.directory.api.ldap.model.constants.SchemaConstants;
+import org.apache.directory.api.ldap.model.exception.LdapException;
+import org.apache.directory.api.ldap.model.exception.LdapInvalidDnException;
+import org.apache.directory.api.ldap.model.name.Dn;
+import org.apache.directory.ldap.client.api.LdapConnection;
+import org.apache.directory.ldap.client.template.ConnectionCallback;
+import org.apache.directory.ldap.client.template.LdapConnectionTemplate;
+import org.apache.directory.ldap.client.template.exception.PasswordException;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import com.google.common.collect.Maps;
+import com.google.inject.AbstractModule;
+import com.google.inject.Guice;
+import com.google.inject.Injector;
+import com.google.inject.Module;
+import com.google.inject.util.Modules;
+
+public class LdapModuleFunctionalTest {
+
+ private static Injector injector;
+ private static Module testModule;
+ private static TestAmbariAmbariLdapConfigurationFactory ldapConfigurationFactory = new TestAmbariAmbariLdapConfigurationFactory();
+
+ @BeforeClass
+ public static void beforeClass() throws Exception {
+
+ // overriding bindings for testing purposes
+ testModule = Modules.override(new LdapModule()).with(new AbstractModule() {
+ @Override
+ protected void configure() {
+ // override the configuration instance binding not to access the database
+ bind(AmbariLdapConfiguration.class).toInstance(ldapConfigurationFactory.createLdapConfiguration(getProps()));
+ }
+ });
+
+ injector = Guice.createInjector(testModule);
+ }
+
+ @Test
+ public void shouldLdapTemplateBeInstantiated() throws LdapInvalidDnException, PasswordException {
+ // GIVEN
+ // the injector is set up
+ Assert.assertNotNull(injector);
+
+ // WHEN
+ // the ldap connection template is retrieved
+ LdapConnectionTemplate template = injector.getInstance(LdapConnectionTemplate.class);
+
+ // THEN
+ Assert.assertNotNull(template);
+ template.authenticate(new Dn("cn=read-only-admin,dc=example,dc=com"), "password".toCharArray());
+
+ Boolean success = template.execute(new ConnectionCallback<Boolean>() {
+ @Override
+ public Boolean doWithConnection(LdapConnection connection) throws LdapException {
+ connection.unBind();
+ connection.bind(new Dn("cn=read-only-admin,dc=example,dc=com"), "password");
+ return connection.isConnected() && connection.isAuthenticated();
+ }
+ });
+
+ Assert.assertTrue("Could not bind to the LDAP server", success);
+
+ }
+
+
+ @Test
+ public void testShouldConnectionCheckSucceedWhenProperConfigurationProvided() throws Exception {
+ // GIVEN
+ AmbariLdapConfiguration ambariLdapConfiguration = ldapConfigurationFactory.createLdapConfiguration(getProps());
+
+ LdapFacade ldapFacade = injector.getInstance(LdapFacade.class);
+
+
+ // WHEN
+ ldapFacade.checkConnection(ambariLdapConfiguration);
+
+ ldapFacade.detectAttributes(ambariLdapConfiguration);
+
+ // THEN
+ // no exceptions thrown
+
+ }
+
+ @Test
+ public void testShouldAttributeDetectionSucceedWhenProperConfigurationProvided() throws Exception {
+ // GIVEN
+ AmbariLdapConfiguration ambariLdapConfiguration = ldapConfigurationFactory.createLdapConfiguration(getProps());
+ LdapConfigurationService ldapConfigurationService = injector.getInstance(LdapConfigurationService.class);
+
+
+ // WHEN
+ ldapConfigurationService.checkUserAttributes("euclid", "", ambariLdapConfiguration);
+
+ // THEN
+ // no exceptions thrown
+
+ }
+
+ private static Map<String, Object> getProps() {
+ Map<String, Object> ldapPropsMap = Maps.newHashMap();
+
+ ldapPropsMap.put(AmbariLdapConfigKeys.ANONYMOUS_BIND.key(), "true");
+ ldapPropsMap.put(AmbariLdapConfigKeys.SERVER_HOST.key(), "ldap.forumsys.com");
+ ldapPropsMap.put(AmbariLdapConfigKeys.SERVER_PORT.key(), "389");
+ ldapPropsMap.put(AmbariLdapConfigKeys.BIND_DN.key(), "cn=read-only-admin,dc=example,dc=com");
+ ldapPropsMap.put(AmbariLdapConfigKeys.BIND_PASSWORD.key(), "password");
+
+ ldapPropsMap.put(AmbariLdapConfigKeys.USER_OBJECT_CLASS.key(), SchemaConstants.PERSON_OC);
+ ldapPropsMap.put(AmbariLdapConfigKeys.USER_NAME_ATTRIBUTE.key(), SchemaConstants.UID_AT);
+ ldapPropsMap.put(AmbariLdapConfigKeys.USER_SEARCH_BASE.key(), "dc=example,dc=com");
+ ldapPropsMap.put(AmbariLdapConfigKeys.DN_ATTRIBUTE.key(), SchemaConstants.UID_AT);
+
+
+ return ldapPropsMap;
+ }
+
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/ambari/blob/1ecd85c4/ambari-server/src/test/java/org/apache/ambari/server/ldap/domain/AmbariLdapConfigurationTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/domain/AmbariLdapConfigurationTest.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/domain/AmbariLdapConfigurationTest.java
deleted file mode 100644
index 0d02a0e..0000000
--- a/ambari-server/src/test/java/org/apache/ambari/server/ldap/domain/AmbariLdapConfigurationTest.java
+++ /dev/null
@@ -1,19 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.ambari.server.ldap.domain;
-
-public class AmbariLdapConfigurationTest {
-
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/ambari/blob/1ecd85c4/ambari-server/src/test/java/org/apache/ambari/server/ldap/domain/TestAmbariAmbariLdapConfigurationFactory.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/domain/TestAmbariAmbariLdapConfigurationFactory.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/domain/TestAmbariAmbariLdapConfigurationFactory.java
new file mode 100644
index 0000000..1155494
--- /dev/null
+++ b/ambari-server/src/test/java/org/apache/ambari/server/ldap/domain/TestAmbariAmbariLdapConfigurationFactory.java
@@ -0,0 +1,29 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.domain;
+
+
+import java.util.Map;
+
+/**
+ * Implementation used for testing purposes only!
+ */
+public class TestAmbariAmbariLdapConfigurationFactory implements AmbariLdapConfigurationFactory {
+
+ @Override
+ public AmbariLdapConfiguration createLdapConfiguration(Map<String, Object> configuration) {
+ return new AmbariLdapConfiguration(configuration);
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/1ecd85c4/ambari-server/src/test/java/org/apache/ambari/server/ldap/domain/TestAmbariLdapConfigurationFactory.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/domain/TestAmbariLdapConfigurationFactory.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/domain/TestAmbariLdapConfigurationFactory.java
deleted file mode 100644
index ec86568..0000000
--- a/ambari-server/src/test/java/org/apache/ambari/server/ldap/domain/TestAmbariLdapConfigurationFactory.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.ambari.server.ldap.domain;
-
-
-import java.util.Map;
-
-/**
- * Implementation used for testing purposes only!
- */
-public class TestAmbariLdapConfigurationFactory implements LdapConfigurationFactory {
-
- @Override
- public AmbariLdapConfiguration createLdapConfiguration(Map<String, Object> configuration) {
- return new AmbariLdapConfiguration(configuration);
- }
-}
[16/33] ambari git commit: AMBARI-21307 LDAP config rest service
implementation extends the ambari config rest implementaiton
Posted by lp...@apache.org.
AMBARI-21307 LDAP config rest service implementation extends the ambari config rest implementaiton
Project: http://git-wip-us.apache.org/repos/asf/ambari/repo
Commit: http://git-wip-us.apache.org/repos/asf/ambari/commit/d062cf05
Tree: http://git-wip-us.apache.org/repos/asf/ambari/tree/d062cf05
Diff: http://git-wip-us.apache.org/repos/asf/ambari/diff/d062cf05
Branch: refs/heads/feature-branch-AMBARI-21307
Commit: d062cf05e4947e3b728b1495e4c19da5fc2cafc7
Parents: 5b7c55f
Author: lpuskas <lp...@apache.org>
Authored: Mon Aug 21 15:53:45 2017 +0200
Committer: lpuskas <lp...@apache.org>
Committed: Fri Oct 13 17:20:50 2017 +0200
----------------------------------------------------------------------
.../services/ldap/LdapConfigurationService.java | 208 +++++++++++++++++++
.../api/services/ldap/LdapRestService.java | 149 -------------
2 files changed, 208 insertions(+), 149 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/ambari/blob/d062cf05/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationService.java b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationService.java
new file mode 100644
index 0000000..52244bc
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationService.java
@@ -0,0 +1,208 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.api.services.ldap;
+
+import java.util.Set;
+
+import javax.inject.Inject;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+import org.apache.ambari.annotations.ApiIgnore;
+import org.apache.ambari.server.StaticallyInject;
+import org.apache.ambari.server.api.services.AmbariConfigurationService;
+import org.apache.ambari.server.api.services.Result;
+import org.apache.ambari.server.api.services.ResultImpl;
+import org.apache.ambari.server.api.services.ResultStatus;
+import org.apache.ambari.server.controller.internal.ResourceImpl;
+import org.apache.ambari.server.controller.spi.Resource;
+import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.LdapConfigurationFactory;
+import org.apache.ambari.server.ldap.service.LdapFacade;
+import org.apache.ambari.server.security.authorization.AuthorizationException;
+import org.apache.ambari.server.security.authorization.AuthorizationHelper;
+import org.apache.ambari.server.security.authorization.ResourceType;
+import org.apache.ambari.server.security.authorization.RoleAuthorization;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.security.core.Authentication;
+
+import com.google.common.collect.Sets;
+
+/**
+ * Endpoint designated to LDAP specific operations.
+ */
+@StaticallyInject
+@Path("/ldapconfigs/")
+public class LdapConfigurationService extends AmbariConfigurationService {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(LdapConfigurationService.class);
+
+ @Inject
+ private static LdapFacade ldapFacade;
+
+ @Inject
+ private static LdapConfigurationFactory ldapConfigurationFactory;
+
+ /**
+ * Actions supported by this endpoint
+ */
+ private enum LdapAction {
+ TEST_CONNECTION("test-connection"),
+ TEST_ATTRIBUTES("test-attributes"),
+ DETECT_ATTRIBUTES("detect-attributes");
+
+ private String actionStr;
+
+ LdapAction(String actionStr) {
+ this.actionStr = actionStr;
+ }
+
+ public static LdapAction fromAction(String action) {
+ for (LdapAction val : LdapAction.values()) {
+ if (val.action().equals(action)) {
+ return val;
+ }
+ }
+ throw new IllegalStateException("Action [ " + action + " ] is not supported");
+ }
+
+ public String action() {
+ return this.actionStr;
+ }
+ }
+
+ @POST
+ @ApiIgnore // until documented
+ @Path("/validate")
+ @Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response validateConfiguration(LdapCheckConfigurationRequest ldapCheckConfigurationRequest) {
+
+ authorize();
+
+ Set<String> groups = Sets.newHashSet();
+
+ Result result = new ResultImpl(new ResultStatus(ResultStatus.STATUS.OK));
+ try {
+
+ validateRequest(ldapCheckConfigurationRequest);
+
+ AmbariLdapConfiguration ambariLdapConfiguration = ldapConfigurationFactory.createLdapConfiguration(
+ ldapCheckConfigurationRequest.getAmbariConfiguration().getData().iterator().next());
+
+ LdapAction action = LdapAction.fromAction(ldapCheckConfigurationRequest.getRequestInfo().getAction());
+ switch (action) {
+
+ case TEST_CONNECTION:
+
+ LOGGER.info("Testing connection to the LDAP server ...");
+ ldapFacade.checkConnection(ambariLdapConfiguration);
+
+ break;
+ case TEST_ATTRIBUTES:
+
+ LOGGER.info("Testing LDAP attributes ....");
+ groups = ldapFacade.checkLdapAttibutes(ldapCheckConfigurationRequest.getRequestInfo().getParameters(), ambariLdapConfiguration);
+ setResult(groups, result);
+
+ break;
+ case DETECT_ATTRIBUTES:
+
+ LOGGER.info("Detecting LDAP attributes ...");
+ ldapFacade.detectAttributes(ambariLdapConfiguration);
+
+ break;
+ default:
+ LOGGER.warn("No action provided ...");
+ throw new IllegalArgumentException("No request action provided");
+ }
+
+ } catch (Exception e) {
+ result.setResultStatus(new ResultStatus(ResultStatus.STATUS.BAD_REQUEST, e));
+ }
+
+ return Response.status(result.getStatus().getStatusCode()).entity(getResultSerializer().serialize(result)).build();
+ }
+
+ private void setResult(Set<String> groups, Result result) {
+ Resource resource = new ResourceImpl(Resource.Type.AmbariConfiguration);
+ resource.setProperty("groups", groups);
+ result.getResultTree().addChild(resource, "payload");
+ }
+
+ private void validateRequest(LdapCheckConfigurationRequest ldapCheckConfigurationRequest) {
+ String errMsg;
+
+ if (null == ldapCheckConfigurationRequest) {
+ errMsg = "No ldap configuraiton request provided";
+ LOGGER.error(errMsg);
+ throw new IllegalArgumentException(errMsg);
+ }
+
+ if (null == ldapCheckConfigurationRequest.getRequestInfo()) {
+ errMsg = String.format("No request information provided. Request: [%s]", ldapCheckConfigurationRequest);
+ LOGGER.error(errMsg);
+ throw new IllegalArgumentException(errMsg);
+ }
+
+ if (null == ldapCheckConfigurationRequest.getAmbariConfiguration()
+ || ldapCheckConfigurationRequest.getAmbariConfiguration().getData().size() != 1) {
+ errMsg = String.format("No / Invalid configuration data provided. Request: [%s]", ldapCheckConfigurationRequest);
+ LOGGER.error(errMsg);
+ throw new IllegalArgumentException(errMsg);
+ }
+ }
+
+ private void authorize() {
+ try {
+ Authentication authentication = AuthorizationHelper.getAuthentication();
+
+ if (authentication == null || !authentication.isAuthenticated()) {
+ throw new AuthorizationException("Authentication data is not available, authorization to perform the requested operation is not granted");
+ }
+
+ if (!AuthorizationHelper.isAuthorized(authentication, ResourceType.AMBARI, null, requiredAuthorizations())) {
+ throw new AuthorizationException("The authenticated user does not have the appropriate authorizations to create the requested resource(s)");
+ }
+ } catch (AuthorizationException e) {
+ LOGGER.error("Unauthorized operation.", e);
+ throw new IllegalArgumentException("User is not authorized to perform the operation", e);
+ }
+
+ }
+
+ Set<RoleAuthorization> requiredAuthorizations() {
+ return Sets.newHashSet(RoleAuthorization.AMBARI_MANAGE_CONFIGURATION);
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/d062cf05/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapRestService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapRestService.java b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapRestService.java
deleted file mode 100644
index 4e654dc..0000000
--- a/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapRestService.java
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.ambari.server.api.services.ldap;
-
-import java.util.Set;
-
-import javax.inject.Inject;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-
-import org.apache.ambari.annotations.ApiIgnore;
-import org.apache.ambari.server.StaticallyInject;
-import org.apache.ambari.server.api.services.BaseService;
-import org.apache.ambari.server.api.services.Result;
-import org.apache.ambari.server.api.services.ResultImpl;
-import org.apache.ambari.server.api.services.ResultStatus;
-import org.apache.ambari.server.controller.internal.ResourceImpl;
-import org.apache.ambari.server.controller.spi.Resource;
-import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
-import org.apache.ambari.server.ldap.LdapConfigurationFactory;
-import org.apache.ambari.server.ldap.service.LdapFacade;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.Sets;
-
-/**
- * Endpoint designated to LDAP specific operations.
- */
-@StaticallyInject
-@Path("/ldap")
-public class LdapRestService extends BaseService {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(LdapRestService.class);
-
- @Inject
- private static LdapFacade ldapFacade;
-
- @Inject
- private static LdapConfigurationFactory ldapConfigurationFactory;
-
- @POST
- @ApiIgnore // until documented
- @Path("/validate") // todo this needs to be moved under the resource
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- public Response validateConfiguration(LdapCheckConfigurationRequest ldapCheckConfigurationRequest) {
-
- Set<String> groups = Sets.newHashSet();
-
- Result result = new ResultImpl(new ResultStatus(ResultStatus.STATUS.OK));
- try {
-
- validateRequest(ldapCheckConfigurationRequest);
-
- AmbariLdapConfiguration ambariLdapConfiguration = ldapConfigurationFactory.createLdapConfiguration(
- ldapCheckConfigurationRequest.getAmbariConfiguration().getData().iterator().next());
-
- switch (ldapCheckConfigurationRequest.getRequestInfo().getAction()) {
- case "test-connection":
-
- LOGGER.info("Testing connection to the LDAP server ...");
- ldapFacade.checkConnection(ambariLdapConfiguration);
-
- break;
- case "test-attributes":
-
- LOGGER.info("Testing LDAP attributes ....");
- groups = ldapFacade.checkLdapAttibutes(ldapCheckConfigurationRequest.getRequestInfo().getParameters(), ambariLdapConfiguration);
- setResult(groups, result);
-
- break;
- case "detect-attributes":
-
- LOGGER.info("Detecting LDAP attributes ...");
- ldapFacade.detectAttributes(ambariLdapConfiguration);
-
- break;
- default:
- LOGGER.warn("No action provided ...");
- throw new IllegalArgumentException("No request action provided");
- }
-
- } catch (Exception e) {
- result.setResultStatus(new ResultStatus(ResultStatus.STATUS.BAD_REQUEST, e));
- }
-
- return Response.status(result.getStatus().getStatusCode()).entity(getResultSerializer().serialize(result)).build();
- }
-
- private void setResult(Set<String> groups, Result result) {
- Resource resource = new ResourceImpl(Resource.Type.AmbariConfiguration);
- resource.setProperty("groups", groups);
- result.getResultTree().addChild(resource, "payload");
- }
-
- private void validateRequest(LdapCheckConfigurationRequest ldapCheckConfigurationRequest) {
- String errMsg;
-
- if (null == ldapCheckConfigurationRequest) {
- errMsg = "No ldap configuraiton request provided";
- LOGGER.error(errMsg);
- throw new IllegalArgumentException(errMsg);
- }
-
- if (null == ldapCheckConfigurationRequest.getRequestInfo()) {
- errMsg = String.format("No request information provided. Request: [%s]", ldapCheckConfigurationRequest);
- LOGGER.error(errMsg);
- throw new IllegalArgumentException(errMsg);
- }
-
- if (null == ldapCheckConfigurationRequest.getAmbariConfiguration()
- || ldapCheckConfigurationRequest.getAmbariConfiguration().getData().size() != 1) {
- errMsg = String.format("No / Invalid configuration data provided. Request: [%s]", ldapCheckConfigurationRequest);
- LOGGER.error(errMsg);
- throw new IllegalArgumentException(errMsg);
- }
- }
-}
[31/33] ambari git commit: AMBARI-21307 cleand apache ditectory
related dependencies
Posted by lp...@apache.org.
AMBARI-21307 cleand apache ditectory related dependencies
Project: http://git-wip-us.apache.org/repos/asf/ambari/repo
Commit: http://git-wip-us.apache.org/repos/asf/ambari/commit/060b85ca
Tree: http://git-wip-us.apache.org/repos/asf/ambari/tree/060b85ca
Diff: http://git-wip-us.apache.org/repos/asf/ambari/diff/060b85ca
Branch: refs/heads/feature-branch-AMBARI-21307
Commit: 060b85ca37f97c5499cc5b9dcf8e57c24d085cb1
Parents: 9a50bc1
Author: lpuskas <lp...@apache.org>
Authored: Wed Oct 11 17:54:57 2017 +0200
Committer: lpuskas <lp...@apache.org>
Committed: Fri Oct 13 17:20:53 2017 +0200
----------------------------------------------------------------------
ambari-funtest/pom.xml | 67 ------------------------------------
ambari-project/pom.xml | 51 ---------------------------
ambari-server/pom.xml | 84 ++++++++-------------------------------------
3 files changed, 14 insertions(+), 188 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/ambari/blob/060b85ca/ambari-funtest/pom.xml
----------------------------------------------------------------------
diff --git a/ambari-funtest/pom.xml b/ambari-funtest/pom.xml
index bb2068d..6466af3 100644
--- a/ambari-funtest/pom.xml
+++ b/ambari-funtest/pom.xml
@@ -197,73 +197,6 @@
<artifactId>spring-ldap-core</artifactId>
</dependency>
<dependency>
- <groupId>org.apache.directory.server</groupId>
- <artifactId>apacheds-server-annotations</artifactId>
- <scope>test</scope>
- <exclusions>
- <exclusion>
- <groupId>net.sf.ehcache</groupId>
- <artifactId>ehcache-core</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>org.apache.directory.server</groupId>
- <artifactId>apacheds-core-integ</artifactId>
- <scope>test</scope>
- <exclusions>
- <exclusion>
- <groupId>net.sf.ehcache</groupId>
- <artifactId>ehcache-core</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>org.apache.directory.server</groupId>
- <artifactId>apacheds-server-integ</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.directory.server</groupId>
- <artifactId>apacheds-jdbm</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.directory.server</groupId>
- <artifactId>apacheds-kerberos-codec</artifactId>
- <exclusions>
- <exclusion>
- <groupId>net.sf.ehcache</groupId>
- <artifactId>ehcache-core</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>org.apache.directory.server</groupId>
- <artifactId>apacheds-core</artifactId>
- <scope>test</scope>
- <exclusions>
- <exclusion>
- <groupId>net.sf.ehcache</groupId>
- <artifactId>ehcache-core</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>org.apache.directory.server</groupId>
- <artifactId>apacheds-protocol-ldap</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.directory.server</groupId>
- <artifactId>kerberos-client</artifactId>
- </dependency>
- <dependency>
- <groupId>org.apache.directory.shared</groupId>
- <artifactId>shared-ldap</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.20</version>
http://git-wip-us.apache.org/repos/asf/ambari/blob/060b85ca/ambari-project/pom.xml
----------------------------------------------------------------------
diff --git a/ambari-project/pom.xml b/ambari-project/pom.xml
index e4d4423..f6e3bc7 100644
--- a/ambari-project/pom.xml
+++ b/ambari-project/pom.xml
@@ -162,57 +162,6 @@
<version>2.0.4.RELEASE</version>
</dependency>
<dependency>
- <groupId>org.apache.directory.server</groupId>
- <artifactId>apacheds-server-annotations</artifactId>
- <version>2.0.0-M19</version>
- </dependency>
- <dependency>
- <groupId>org.apache.directory.server</groupId>
- <artifactId>apacheds-core-integ</artifactId>
- <version>2.0.0-M19</version>
- </dependency>
- <dependency>
- <groupId>org.apache.directory.server</groupId>
- <artifactId>apacheds-server-integ</artifactId>
- <version>2.0.0-M19</version>
- </dependency>
- <dependency>
- <groupId>org.apache.directory.server</groupId>
- <artifactId>apacheds-jdbm</artifactId>
- <version>2.0.0-M5</version>
- </dependency>
- <dependency>
- <groupId>org.apache.directory.server</groupId>
- <artifactId>apacheds-kerberos-codec</artifactId>
- <version>2.0.0-M19</version>
- </dependency>
- <dependency>
- <groupId>org.apache.directory.server</groupId>
- <artifactId>apacheds-core</artifactId>
- <version>2.0.0-M19</version>
- </dependency>
- <dependency>
- <groupId>org.apache.directory.server</groupId>
- <artifactId>kerberos-client</artifactId>
- <version>2.0.0-M19</version>
- </dependency>
- <dependency>
- <groupId>org.apache.directory.server</groupId>
- <artifactId>apacheds-protocol-ldap</artifactId>
- <version>2.0.0-M19</version>
- <exclusions>
- <exclusion>
- <groupId>org.apache.directory.jdbm</groupId>
- <artifactId>apacheds-jdbm1</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>org.apache.directory.shared</groupId>
- <artifactId>shared-ldap</artifactId>
- <version>0.9.17</version>
- </dependency>
- <dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
http://git-wip-us.apache.org/repos/asf/ambari/blob/060b85ca/ambari-server/pom.xml
----------------------------------------------------------------------
diff --git a/ambari-server/pom.xml b/ambari-server/pom.xml
index 8d52821..a86acf5 100644
--- a/ambari-server/pom.xml
+++ b/ambari-server/pom.xml
@@ -1225,73 +1225,6 @@
<artifactId>spring-ldap-core</artifactId>
</dependency>
<dependency>
- <groupId>org.apache.directory.server</groupId>
- <artifactId>apacheds-server-annotations</artifactId>
- <scope>test</scope>
- <exclusions>
- <exclusion>
- <groupId>net.sf.ehcache</groupId>
- <artifactId>ehcache-core</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>org.apache.directory.server</groupId>
- <artifactId>apacheds-core-integ</artifactId>
- <scope>test</scope>
- <exclusions>
- <exclusion>
- <groupId>net.sf.ehcache</groupId>
- <artifactId>ehcache-core</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>org.apache.directory.server</groupId>
- <artifactId>apacheds-server-integ</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.directory.server</groupId>
- <artifactId>apacheds-jdbm</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.directory.server</groupId>
- <artifactId>apacheds-kerberos-codec</artifactId>
- <exclusions>
- <exclusion>
- <groupId>net.sf.ehcache</groupId>
- <artifactId>ehcache-core</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>org.apache.directory.server</groupId>
- <artifactId>apacheds-core</artifactId>
- <scope>test</scope>
- <exclusions>
- <exclusion>
- <groupId>net.sf.ehcache</groupId>
- <artifactId>ehcache-core</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>org.apache.directory.server</groupId>
- <artifactId>apacheds-protocol-ldap</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.directory.server</groupId>
- <artifactId>kerberos-client</artifactId>
- </dependency>
- <dependency>
- <groupId>org.apache.directory.shared</groupId>
- <artifactId>shared-ldap</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
@@ -1622,6 +1555,12 @@
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-auth</artifactId>
<version>${hadoop.version}</version>
+ <exclusions>
+ <exclusion>
+ <groupId>org.apache.directory.server</groupId>
+ <artifactId>apacheds-kerberos-codec</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
@@ -1689,9 +1628,14 @@
<version>4.2.2</version>
</dependency>
<dependency>
- <groupId>org.apache.directory.api</groupId>
- <artifactId>api-all</artifactId>
- <version>${ldap-api.version}</version>
+ <groupId>org.apache.directory.server</groupId>
+ <artifactId>apacheds-all</artifactId>
+ <version>2.0.0-M24</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.directory.server</groupId>
+ <artifactId>kerberos-client</artifactId>
+ <version>2.0.0-M24</version>
</dependency>
<dependency>
<groupId>com.networknt</groupId>
[20/33] ambari git commit: Â AMBARI-21307 Implemented more detectors. Organized the code
Posted by lp...@apache.org.
 AMBARI-21307 Implemented more detectors. Organized the code
Project: http://git-wip-us.apache.org/repos/asf/ambari/repo
Commit: http://git-wip-us.apache.org/repos/asf/ambari/commit/14ec2aee
Tree: http://git-wip-us.apache.org/repos/asf/ambari/tree/14ec2aee
Diff: http://git-wip-us.apache.org/repos/asf/ambari/diff/14ec2aee
Branch: refs/heads/feature-branch-AMBARI-21307
Commit: 14ec2aee699254a5b0dedb6da974e4cdf6bb3fbb
Parents: d0e543c
Author: lpuskas <lp...@apache.org>
Authored: Tue Sep 12 11:58:45 2017 +0200
Committer: lpuskas <lp...@apache.org>
Committed: Fri Oct 13 17:20:51 2017 +0200
----------------------------------------------------------------------
.../server/ldap/AmbariLdapConfiguration.java | 1 +
.../ads/DefaultAttributeDetectionService.java | 134 ++++++++++++++-----
.../ldap/service/ads/ObjectClassDetector.java | 81 -----------
.../ads/OccurranceAndWeightBasedDetector.java | 81 -----------
.../service/ads/UserNameAttributeDetector.java | 75 -----------
.../ads/detectors/GroupMemberAttrDetector.java | 56 ++++++++
.../ads/detectors/GroupNameAttrDetector.java | 61 +++++++++
.../ads/detectors/GroupObjectClassDetector.java | 64 +++++++++
.../OccurranceAndWeightBasedDetector.java | 103 ++++++++++++++
.../detectors/UserGroupMemberAttrDetector.java | 56 ++++++++
.../ads/detectors/UserNameAttrDetector.java | 60 +++++++++
.../ads/detectors/UserObjectClassDetector.java | 64 +++++++++
.../DefaultAttributeDetectionServiceTest.java | 10 +-
13 files changed, 571 insertions(+), 275 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/ambari/blob/14ec2aee/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
index e28c6ed..ebb567d 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
@@ -56,6 +56,7 @@ public class AmbariLdapConfiguration {
USER_OBJECT_CLASS("ambari.ldap.attributes.user.object_class"),
USER_NAME_ATTRIBUTE("ambari.ldap.attributes.user.name_attr"),
+ USER_GROUP_MEMBER_ATTRIBUTE("ambari.ldap.attributes.user.group_member_attr"),
USER_SEARCH_BASE("ambari.ldap.attributes.user.search_base"),
GROUP_OBJECT_CLASS("ambari.ldap.attributes.group.object_class"),
http://git-wip-us.apache.org/repos/asf/ambari/blob/14ec2aee/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionService.java
index 710adf1..b3a4fde 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionService.java
@@ -14,15 +14,18 @@
package org.apache.ambari.server.ldap.service.ads;
-import java.util.Set;
-
import javax.inject.Inject;
import javax.inject.Singleton;
import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
import org.apache.ambari.server.ldap.service.AmbariLdapException;
-import org.apache.ambari.server.ldap.service.AttributeDetector;
import org.apache.ambari.server.ldap.service.LdapAttributeDetectionService;
+import org.apache.ambari.server.ldap.service.ads.detectors.GroupMemberAttrDetector;
+import org.apache.ambari.server.ldap.service.ads.detectors.GroupNameAttrDetector;
+import org.apache.ambari.server.ldap.service.ads.detectors.GroupObjectClassDetector;
+import org.apache.ambari.server.ldap.service.ads.detectors.UserGroupMemberAttrDetector;
+import org.apache.ambari.server.ldap.service.ads.detectors.UserNameAttrDetector;
+import org.apache.ambari.server.ldap.service.ads.detectors.UserObjectClassDetector;
import org.apache.directory.api.ldap.model.cursor.SearchCursor;
import org.apache.directory.api.ldap.model.entry.Entry;
import org.apache.directory.api.ldap.model.message.Response;
@@ -37,24 +40,29 @@ import org.apache.directory.ldap.client.api.search.FilterBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.google.common.collect.Sets;
-
@Singleton
public class DefaultAttributeDetectionService implements LdapAttributeDetectionService<LdapConnection> {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultAttributeDetectionService.class);
private static final int SAMPLE_RESULT_SIZE = 50;
- // ordered list of possible username attribute values (the most significant valus should be first)
- private static final Set<String> USER_OBJECT_CLASS_VALUES = Sets.newHashSet("person", "posixAccount");
- private static final Set<String> USER_GROUP_MEMBER_ATTR_VALUES = Sets.newHashSet("memberOf", "ismemberOf");
+ @Inject
+ private UserNameAttrDetector userNameAttrDetector = new UserNameAttrDetector(); // todo remove instantition
+
+ @Inject
+ private UserObjectClassDetector userObjectClassDetector = new UserObjectClassDetector(); // todo remove instantition
@Inject
- private UserNameAttributeDetector userNameAttrDetector = new UserNameAttributeDetector(); // todo remove instantition
+ private UserGroupMemberAttrDetector userGroupMemberAttrDetector = new UserGroupMemberAttrDetector(); // todo remove instantition
@Inject
- private ObjectClassDetector objectClassDetector = new ObjectClassDetector(); // todo remove instantition
+ private GroupNameAttrDetector groupNameAttrDetector = new GroupNameAttrDetector(); // todo remove instantition
+
+ @Inject
+ private GroupObjectClassDetector groupObjectClassDetector = new GroupObjectClassDetector(); // todo remove instantition
+
+ private GroupMemberAttrDetector groupMemberAttrDetector = new GroupMemberAttrDetector(); // todo remove instantition
@Inject
public DefaultAttributeDetectionService() {
@@ -76,7 +84,7 @@ public class DefaultAttributeDetectionService implements LdapAttributeDetectionS
// todo should the bind operation be done in the facade?
connection.bind(ambariLdapConfiguration.bindDn(), ambariLdapConfiguration.bindPassword());
- SearchRequest searchRequest = assembleSearchRequest(ambariLdapConfiguration);
+ SearchRequest searchRequest = assembleUserSearchRequest(ambariLdapConfiguration);
// do the search
searchCursor = connection.search(searchRequest);
@@ -95,15 +103,19 @@ public class DefaultAttributeDetectionService implements LdapAttributeDetectionS
if (response instanceof SearchResultEntry) {
Entry resultEntry = ((SearchResultEntry) response).getEntry();
- LOGGER.info("Processing sample entry: [{}]", resultEntry.getDn());
+ LOGGER.info("Processing sample entry with dn: [{}]", resultEntry.getDn());
+
userNameAttrDetector.collect(resultEntry);
- objectClassDetector.collect(resultEntry);
+ userObjectClassDetector.collect(resultEntry);
+ userGroupMemberAttrDetector.collect(resultEntry);
+
processedUserCnt++;
}
}
ambariLdapConfiguration.setValueFor(AmbariLdapConfiguration.AmbariLdapConfig.USER_NAME_ATTRIBUTE, userNameAttrDetector.detect());
- ambariLdapConfiguration.setValueFor(AmbariLdapConfiguration.AmbariLdapConfig.USER_OBJECT_CLASS, objectClassDetector.detect());
+ ambariLdapConfiguration.setValueFor(AmbariLdapConfiguration.AmbariLdapConfig.USER_OBJECT_CLASS, userObjectClassDetector.detect());
+ ambariLdapConfiguration.setValueFor(AmbariLdapConfiguration.AmbariLdapConfig.USER_GROUP_MEMBER_ATTRIBUTE, userGroupMemberAttrDetector.detect());
LOGGER.info("Decorated ambari ldap config : [{}]", ambariLdapConfiguration);
@@ -120,25 +132,72 @@ public class DefaultAttributeDetectionService implements LdapAttributeDetectionS
return ambariLdapConfiguration;
}
- private void detectUserAttributes(Entry resultEntry, AttributeDetector attributeDetector) {
- attributeDetector.collect(resultEntry);
+ @Override
+ public AmbariLdapConfiguration detectLdapGroupAttributes(LdapConnection connection, AmbariLdapConfiguration ambariLdapConfiguration) {
+ LOGGER.info("Detecting LDAP group attributes ...");
-// Set<String> objectClasses = detectUserObjectClass(resultEntry);
-// if (!objectClasses.isEmpty()) {
-// ambariLdapConfiguration.setValueFor(AmbariLdapConfiguration.AmbariLdapConfig.USER_OBJECT_CLASS, StringUtils.join(objectClasses, ","));
-// }
+ // perform a search using the user search base
+ if (Strings.isEmpty(ambariLdapConfiguration.groupSearchBase())) {
+ LOGGER.warn("No group search base provided");
+ return ambariLdapConfiguration;
+ }
+ SearchCursor searchCursor = null;
- }
+ try {
+ // todo should the bind operation be done in the facade?
+ connection.bind(ambariLdapConfiguration.bindDn(), ambariLdapConfiguration.bindPassword());
- @Override
- public AmbariLdapConfiguration detectLdapGroupAttributes(LdapConnection connection, AmbariLdapConfiguration ambariLdapConfiguration) {
- LOGGER.info("Detecting LDAP group attributes ...");
- return null;
+ SearchRequest searchRequest = assembleGroupSearchRequest(ambariLdapConfiguration);
+
+ // do the search
+ searchCursor = connection.search(searchRequest);
+
+ int processedGroupCnt = 0;
+
+ while (searchCursor.next()) {
+
+ if (processedGroupCnt >= SAMPLE_RESULT_SIZE) {
+ LOGGER.debug("The maximum number of results for attribute detection has exceeded. Quit detection.");
+ break;
+ }
+
+ Response response = searchCursor.get();
+ // process the SearchResultEntry
+
+ if (response instanceof SearchResultEntry) {
+ Entry resultEntry = ((SearchResultEntry) response).getEntry();
+ LOGGER.info("Processing sample entry with dn: [{}]", resultEntry.getDn());
+
+ groupNameAttrDetector.collect(resultEntry);
+ groupObjectClassDetector.collect(resultEntry);
+ groupMemberAttrDetector.collect(resultEntry);
+
+ processedGroupCnt++;
+ }
+ }
+
+ ambariLdapConfiguration.setValueFor(AmbariLdapConfiguration.AmbariLdapConfig.GROUP_NAME_ATTRIBUTE, groupNameAttrDetector.detect());
+ ambariLdapConfiguration.setValueFor(AmbariLdapConfiguration.AmbariLdapConfig.GROUP_OBJECT_CLASS, groupObjectClassDetector.detect());
+ ambariLdapConfiguration.setValueFor(AmbariLdapConfiguration.AmbariLdapConfig.GROUP_MEMBER_ATTRIBUTE, groupMemberAttrDetector.detect());
+
+ LOGGER.info("Decorated ambari ldap config : [{}]", ambariLdapConfiguration);
+
+ } catch (Exception e) {
+
+ LOGGER.error("Ldap operation failed", e);
+ } finally {
+ // housekeeping
+ if (null != searchCursor) {
+ searchCursor.close();
+ }
+ }
+
+ return ambariLdapConfiguration;
}
- private SearchRequest assembleSearchRequest(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
+ private SearchRequest assembleUserSearchRequest(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
try {
SearchRequest req = new SearchRequestImpl();
@@ -157,18 +216,23 @@ public class DefaultAttributeDetectionService implements LdapAttributeDetectionS
}
}
+ private SearchRequest assembleGroupSearchRequest(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
+ try {
- private Set<String> detectUserObjectClass(Entry entry) {
- LOGGER.info("Detecting user object class. Attributes: {}", entry.getAttributes());
- throw new UnsupportedOperationException("Not yet implemented");
- }
+ SearchRequest req = new SearchRequestImpl();
+ req.setScope(SearchScope.SUBTREE);
+ req.addAttributes("*");
+ req.setTimeLimit(0);
+ req.setBase(new Dn(ambariLdapConfiguration.groupSearchBase()));
+ // the filter must be set!
+ req.setFilter(FilterBuilder.present(ambariLdapConfiguration.dnAttribute()).toString());
- private String detectGroupNameAttribute(Entry entry) {
- throw new UnsupportedOperationException("Not yet implemented");
- }
+ return req;
- private Set<String> detectGroupObjectClass(Entry entry) {
- throw new UnsupportedOperationException("Not yet implemented");
+ } catch (Exception e) {
+ LOGGER.error("Could not assemble ldap search request", e);
+ throw new AmbariLdapException(e);
+ }
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/14ec2aee/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/ObjectClassDetector.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/ObjectClassDetector.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/ObjectClassDetector.java
deleted file mode 100644
index 2613517..0000000
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/ObjectClassDetector.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.ambari.server.ldap.service.ads;
-
-import java.util.Map;
-
-import javax.inject.Inject;
-
-import org.apache.directory.api.ldap.model.entry.Entry;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.Maps;
-
-public class ObjectClassDetector extends OccurranceAndWeightBasedDetector {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(ObjectClassDetector.class);
- private Map<String, Integer> occurranceMap = Maps.newHashMap();
- private Map<String, Integer> weightsMap = Maps.newHashMap();
-
-
- private enum ObjectClassValue {
- PERSON("person", 1),
- POSIX_ACCOUNT("posixAccount", 1);
-
- private String ocVal;
- private Integer weight;
-
- ObjectClassValue(String attr, Integer weght) {
- this.ocVal = attr;
- this.weight = weght;
- }
-
- Integer weight() {
- return this.weight;
- }
-
- String ocVal() {
- return this.ocVal;
- }
-
- }
-
- @Inject
- public ObjectClassDetector() {
- for (ObjectClassValue ocVal : ObjectClassValue.values()) {
- occurranceMap.put(ocVal.ocVal(), 0);
- weightsMap.put(ocVal.ocVal(), ocVal.weight());
- }
-
- }
-
- @Override
- protected Map<String, Integer> occurranceMap() {
- return occurranceMap;
- }
-
- @Override
- protected Map<String, Integer> weightsMap() {
- return weightsMap;
- }
-
- @Override
- protected boolean applies(Entry entry, String value) {
- LOGGER.info("Checking for object class [{}] in entry [{}]", value, entry.getDn());
- return entry.hasObjectClass(value);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/ambari/blob/14ec2aee/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/OccurranceAndWeightBasedDetector.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/OccurranceAndWeightBasedDetector.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/OccurranceAndWeightBasedDetector.java
deleted file mode 100644
index 32dc238..0000000
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/OccurranceAndWeightBasedDetector.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.ambari.server.ldap.service.ads;
-
-import java.util.Map;
-
-import org.apache.ambari.server.ldap.service.AttributeDetector;
-import org.apache.directory.api.ldap.model.entry.Entry;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public abstract class OccurranceAndWeightBasedDetector implements AttributeDetector<Entry> {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(OccurranceAndWeightBasedDetector.class);
-
- protected abstract Map<String, Integer> occurranceMap();
-
- protected abstract Map<String, Integer> weightsMap();
-
- protected abstract boolean applies(Entry entry, String value);
-
- @Override
- public String detect() {
- Map.Entry<String, Integer> selectedEntry = null;
-
- for (Map.Entry<String, Integer> entry : occurranceMap().entrySet()) {
- if (selectedEntry == null) {
-
- selectedEntry = entry;
- LOGGER.info("Initial name attribute: {}", selectedEntry);
- continue;
-
- }
-
- if (selectedEntry.getValue() < entry.getValue()) {
-
- LOGGER.info("Changing potential name attribute from : [{}] to: [{}]", selectedEntry, entry);
- selectedEntry = entry;
-
- }
- }
- return selectedEntry.getKey();
- }
-
- @Override
- public void collect(Entry entry) {
- LOGGER.info("Detecting ldap attributes/values ...");
-
- for (String attributeValue : occurranceMap().keySet()) {
- if (applies(entry, attributeValue)) {
-
- Integer cnt = occurranceMap().get(attributeValue).intValue();
- if (weightsMap().containsKey(attributeValue)) {
- cnt = cnt + weightsMap().get(attributeValue);
- } else {
- cnt = cnt + 1;
- }
- occurranceMap().put(attributeValue, cnt);
-
- LOGGER.info("Collected potential name attr: {}, count: {}", attributeValue, cnt);
-
- } else {
- LOGGER.info("The result entry doesn't contain the attribute: [{}]", attributeValue);
- }
- }
- }
-
-
-}
http://git-wip-us.apache.org/repos/asf/ambari/blob/14ec2aee/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/UserNameAttributeDetector.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/UserNameAttributeDetector.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/UserNameAttributeDetector.java
deleted file mode 100644
index bbb4b43..0000000
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/UserNameAttributeDetector.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.ambari.server.ldap.service.ads;
-
-import java.util.Map;
-
-import org.apache.directory.api.ldap.model.entry.Entry;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.Maps;
-
-public class UserNameAttributeDetector extends OccurranceAndWeightBasedDetector {
- private static final Logger LOGGER = LoggerFactory.getLogger(UserNameAttributeDetector.class);
-
- private Map<String, Integer> occurranceMap = Maps.newHashMap();
- private Map<String, Integer> weightsMap = Maps.newHashMap();
-
- private enum NameAttrs {
- SAM_ACCOUNT_NAME("sAMAccountName", 5),
- UID("uid", 3),
- CN("cn", 1);
-
- private String attrName;
- private Integer weight;
-
- NameAttrs(String attr, Integer weght) {
- this.attrName = attr;
- this.weight = weght;
- }
-
- Integer weight() {
- return this.weight;
- }
-
- String attrName() {
- return this.attrName;
- }
-
- }
-
- public UserNameAttributeDetector() {
- for (NameAttrs nameAttr : NameAttrs.values()) {
- occurranceMap.put(nameAttr.attrName(), 0);
- weightsMap.put(nameAttr.attrName(), nameAttr.weight());
- }
- }
-
- protected Map<String, Integer> occurranceMap() {
- return occurranceMap;
- }
-
- protected Map<String, Integer> weightsMap() {
- return weightsMap;
- }
-
- @Override
- protected boolean applies(Entry entry, String value) {
- LOGGER.info("Checking for attribute [{}] in entry [{}]", value, entry.getDn());
- return entry.containsAttribute(value);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/ambari/blob/14ec2aee/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupMemberAttrDetector.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupMemberAttrDetector.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupMemberAttrDetector.java
new file mode 100644
index 0000000..6931736
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupMemberAttrDetector.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service.ads.detectors;
+
+import org.apache.directory.api.ldap.model.entry.Entry;
+
+public class GroupMemberAttrDetector extends OccurranceAndWeightBasedDetector {
+
+ private enum GroupMemberAttr {
+
+ MEMBER("member", 1),
+ MEMBER_UID("memberUid", 1),
+ UNIQUE_MEMBER("uniqueMember", 1);
+
+ private String attrName;
+ private Integer weight;
+
+ GroupMemberAttr(String attr, Integer weght) {
+ this.attrName = attr;
+ this.weight = weght;
+ }
+
+ Integer weight() {
+ return this.weight;
+ }
+
+ String attrName() {
+ return this.attrName;
+ }
+
+ }
+
+ public GroupMemberAttrDetector() {
+ for (GroupMemberAttr groupMemberAttr : GroupMemberAttr.values()) {
+ occurranceMap().put(groupMemberAttr.attrName(), 0);
+ weightsMap().put(groupMemberAttr.attrName(), groupMemberAttr.weight());
+ }
+ }
+
+ @Override
+ protected boolean applies(Entry entry, String value) {
+ return entry.containsAttribute(value);
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/14ec2aee/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupNameAttrDetector.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupNameAttrDetector.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupNameAttrDetector.java
new file mode 100644
index 0000000..f868383
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupNameAttrDetector.java
@@ -0,0 +1,61 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service.ads.detectors;
+
+import org.apache.directory.api.ldap.model.entry.Entry;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class GroupNameAttrDetector extends OccurranceAndWeightBasedDetector {
+ private static final Logger LOGGER = LoggerFactory.getLogger(UserNameAttrDetector.class);
+
+ private enum GroupNameAttr {
+
+ DISTINGUISHED_NAME("distinguishedName", 1),
+
+ CN("cn", 1);
+
+ private String attrName;
+ private Integer weight;
+
+ GroupNameAttr(String attr, Integer weght) {
+ this.attrName = attr;
+ this.weight = weght;
+ }
+
+ Integer weight() {
+ return this.weight;
+ }
+
+ String attrName() {
+ return this.attrName;
+ }
+
+ }
+
+ public GroupNameAttrDetector() {
+
+ for (GroupNameAttr groupNameAttr : GroupNameAttr.values()) {
+ occurranceMap().put(groupNameAttr.attrName(), 0);
+ weightsMap().put(groupNameAttr.attrName(), groupNameAttr.weight());
+ }
+ }
+
+
+ @Override
+ protected boolean applies(Entry entry, String value) {
+ return entry.containsAttribute(value);
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/14ec2aee/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupObjectClassDetector.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupObjectClassDetector.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupObjectClassDetector.java
new file mode 100644
index 0000000..fddc5a5
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupObjectClassDetector.java
@@ -0,0 +1,64 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service.ads.detectors;
+
+import org.apache.directory.api.ldap.model.entry.Entry;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class GroupObjectClassDetector extends OccurranceAndWeightBasedDetector {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(GroupObjectClassDetector.class);
+
+ private enum ObjectClassValue {
+
+ GROUP("group", 1),
+
+ GROUP_OF_NAMES("groupOfNames", 1),
+
+ POSIX_GROUP("posixGroup", 1),
+
+ GROUP_OF_UNIQUE_NAMES("groupOfUniqueNames", 1);
+
+ private String ocVal;
+ private Integer weight;
+
+ ObjectClassValue(String attr, Integer weght) {
+ this.ocVal = attr;
+ this.weight = weght;
+ }
+
+ Integer weight() {
+ return this.weight;
+ }
+
+ String ocVal() {
+ return this.ocVal;
+ }
+
+ }
+
+ public GroupObjectClassDetector() {
+ for (ObjectClassValue ocVal : ObjectClassValue.values()) {
+ occurranceMap().put(ocVal.ocVal(), 0);
+ weightsMap().put(ocVal.ocVal(), ocVal.weight());
+ }
+ }
+
+ @Override
+ protected boolean applies(Entry entry, String value) {
+ return entry.hasObjectClass(value);
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/14ec2aee/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/OccurranceAndWeightBasedDetector.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/OccurranceAndWeightBasedDetector.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/OccurranceAndWeightBasedDetector.java
new file mode 100644
index 0000000..8aaf6c1
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/OccurranceAndWeightBasedDetector.java
@@ -0,0 +1,103 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service.ads.detectors;
+
+import java.util.Map;
+
+import org.apache.ambari.server.ldap.service.AttributeDetector;
+import org.apache.directory.api.ldap.model.entry.Entry;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.collect.Maps;
+
+public abstract class OccurranceAndWeightBasedDetector implements AttributeDetector<Entry> {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(OccurranceAndWeightBasedDetector.class);
+
+ private Map<String, Integer> occurranceMap = Maps.newHashMap();
+ private Map<String, Integer> weightsMap = Maps.newHashMap();
+
+ protected Map<String, Integer> occurranceMap() {
+ return occurranceMap;
+ }
+
+ protected Map<String, Integer> weightsMap() {
+ return weightsMap;
+ }
+
+
+ protected abstract boolean applies(Entry entry, String value);
+
+ @Override
+ public String detect() {
+ LOGGER.info("Calculating the most probable attribute/value ...");
+ Map.Entry<String, Integer> selectedEntry = null;
+
+ for (Map.Entry<String, Integer> entry : occurranceMap().entrySet()) {
+ if (selectedEntry == null) {
+
+ selectedEntry = entry;
+ LOGGER.debug("Initial attribute / value entry: {}", selectedEntry);
+ continue;
+
+ }
+
+ if (selectedEntry.getValue() < entry.getValue()) {
+
+ LOGGER.info("Changing potential attribute / value entry from : [{}] to: [{}]", selectedEntry, entry);
+ selectedEntry = entry;
+
+ }
+ }
+
+ // check whether the selected entry is valid (has occured in the sample result set)
+ String detectedVal = "N/A";
+
+ if (selectedEntry.getValue() > 0) {
+ detectedVal = selectedEntry.getKey();
+ } else {
+ LOGGER.warn("Unable to detect attribute or attribute value");
+ }
+
+ LOGGER.info("Detected attribute or value: [{}]", detectedVal);
+ return detectedVal;
+ }
+
+ @Override
+ public void collect(Entry entry) {
+ LOGGER.info("Collecting ldap attributes/values form entry with dn: [{]]", entry.getDn());
+
+ for (String attributeValue : occurranceMap().keySet()) {
+ if (applies(entry, attributeValue)) {
+
+ Integer cnt = occurranceMap().get(attributeValue).intValue();
+ if (weightsMap().containsKey(attributeValue)) {
+ cnt = cnt + weightsMap().get(attributeValue);
+ } else {
+ cnt = cnt + 1;
+ }
+ occurranceMap().put(attributeValue, cnt);
+
+ LOGGER.info("Collected potential name attr: {}, count: {}", attributeValue, cnt);
+
+ } else {
+ LOGGER.info("The result entry doesn't contain the attribute: [{}]", attributeValue);
+ }
+ }
+ }
+
+
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/14ec2aee/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserGroupMemberAttrDetector.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserGroupMemberAttrDetector.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserGroupMemberAttrDetector.java
new file mode 100644
index 0000000..c3f2ab4
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserGroupMemberAttrDetector.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service.ads.detectors;
+
+import org.apache.directory.api.ldap.model.entry.Entry;
+
+public class UserGroupMemberAttrDetector extends OccurranceAndWeightBasedDetector {
+ private static String[] userGroupMemAttrValues = {"memberOf", "ismemberOf"};
+
+ private enum UserGroupMemberAttr {
+
+ MEMBER_OF("memberOf", 1),
+ IS_MEMBER_OF("ismemberOf", 1);
+
+ private String attrName;
+ private Integer weight;
+
+ UserGroupMemberAttr(String attr, Integer weght) {
+ this.attrName = attr;
+ this.weight = weght;
+ }
+
+ Integer weight() {
+ return this.weight;
+ }
+
+ String attrName() {
+ return this.attrName;
+ }
+
+ }
+
+ public UserGroupMemberAttrDetector() {
+ for (UserGroupMemberAttr userGroupMemberAttr : UserGroupMemberAttr.values()) {
+ occurranceMap().put(userGroupMemberAttr.attrName(), 0);
+ weightsMap().put(userGroupMemberAttr.attrName(), userGroupMemberAttr.weight);
+ }
+ }
+
+ @Override
+ protected boolean applies(Entry entry, String value) {
+ return entry.containsAttribute(value);
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/14ec2aee/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserNameAttrDetector.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserNameAttrDetector.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserNameAttrDetector.java
new file mode 100644
index 0000000..40bf09b
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserNameAttrDetector.java
@@ -0,0 +1,60 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service.ads.detectors;
+
+import org.apache.directory.api.ldap.model.entry.Entry;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class UserNameAttrDetector extends OccurranceAndWeightBasedDetector {
+ private static final Logger LOGGER = LoggerFactory.getLogger(UserNameAttrDetector.class);
+
+ private enum UserNameAttrs {
+ SAM_ACCOUNT_NAME("sAMAccountName", 5),
+ UID("uid", 3),
+ CN("cn", 1);
+
+ private String attrName;
+ private Integer weight;
+
+ UserNameAttrs(String attr, Integer weght) {
+ this.attrName = attr;
+ this.weight = weght;
+ }
+
+ Integer weight() {
+ return this.weight;
+ }
+
+ String attrName() {
+ return this.attrName;
+ }
+
+ }
+
+ public UserNameAttrDetector() {
+ for (UserNameAttrs nameAttr : UserNameAttrs.values()) {
+ occurranceMap().put(nameAttr.attrName(), 0);
+ weightsMap().put(nameAttr.attrName(), nameAttr.weight());
+ }
+ }
+
+ @Override
+ protected boolean applies(Entry entry, String value) {
+ LOGGER.info("Checking for attribute [{}] in entry [{}]", value, entry.getDn());
+ return entry.containsAttribute(value);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/14ec2aee/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserObjectClassDetector.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserObjectClassDetector.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserObjectClassDetector.java
new file mode 100644
index 0000000..97b3c52
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserObjectClassDetector.java
@@ -0,0 +1,64 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service.ads.detectors;
+
+import javax.inject.Inject;
+
+import org.apache.directory.api.ldap.model.entry.Entry;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class UserObjectClassDetector extends OccurranceAndWeightBasedDetector {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(UserObjectClassDetector.class);
+
+ private enum ObjectClassValue {
+ PERSON("person", 1),
+ POSIX_ACCOUNT("posixAccount", 1);
+
+ private String ocVal;
+ private Integer weight;
+
+ ObjectClassValue(String attr, Integer weght) {
+ this.ocVal = attr;
+ this.weight = weght;
+ }
+
+ Integer weight() {
+ return this.weight;
+ }
+
+ String ocVal() {
+ return this.ocVal;
+ }
+
+ }
+
+ @Inject
+ public UserObjectClassDetector() {
+ for (ObjectClassValue ocVal : ObjectClassValue.values()) {
+ occurranceMap().put(ocVal.ocVal(), 0);
+ weightsMap().put(ocVal.ocVal(), ocVal.weight());
+ }
+
+ }
+
+ @Override
+ protected boolean applies(Entry entry, String value) {
+ LOGGER.info("Checking for object class [{}] in entry [{}]", value, entry.getDn());
+ return entry.hasObjectClass(value);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/14ec2aee/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionServiceTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionServiceTest.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionServiceTest.java
index 5cddf1a..08f2d6c 100644
--- a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionServiceTest.java
+++ b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionServiceTest.java
@@ -32,6 +32,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Maps;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
public class DefaultAttributeDetectionServiceTest {
@@ -78,9 +80,12 @@ public class DefaultAttributeDetectionServiceTest {
// WHEN
AmbariLdapConfiguration config = attributeDetectionService.detectLdapUserAttributes(ldapConnection, ambariLdapConfiguration);
+ config = attributeDetectionService.detectLdapGroupAttributes(ldapConnection, ambariLdapConfiguration);
- // THEN
+ Gson gson = new GsonBuilder().create();
+ LOGGER.info(gson.toJson(config));
+ // THEN
ldapConnection.close();
}
@@ -95,9 +100,8 @@ public class DefaultAttributeDetectionServiceTest {
ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.BIND_PASSWORD.key(), "password");
ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.DN_ATTRIBUTE.key(), SchemaConstants.CN_AT);
- ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.USER_OBJECT_CLASS.key(), SchemaConstants.PERSON_OC);
- ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.USER_NAME_ATTRIBUTE.key(), SchemaConstants.UID_AT);
ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.USER_SEARCH_BASE.key(), "dc=example,dc=com");
+ ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.GROUP_SEARCH_BASE.key(), "dc=example,dc=com");
return ldapPropsMap;
[32/33] ambari git commit: AMBARI-21307 Ldapconnection template
optimization, basic support for custom trust store
Posted by lp...@apache.org.
AMBARI-21307 Ldapconnection template optimization, basic support for custom trust store
Project: http://git-wip-us.apache.org/repos/asf/ambari/repo
Commit: http://git-wip-us.apache.org/repos/asf/ambari/commit/9a50bc15
Tree: http://git-wip-us.apache.org/repos/asf/ambari/tree/9a50bc15
Diff: http://git-wip-us.apache.org/repos/asf/ambari/diff/9a50bc15
Branch: refs/heads/feature-branch-AMBARI-21307
Commit: 9a50bc154b193594f506dcd32cfd1323700fa99c
Parents: 1ecd85c
Author: lpuskas <lp...@apache.org>
Authored: Mon Oct 9 17:20:38 2017 +0200
Committer: lpuskas <lp...@apache.org>
Committed: Fri Oct 13 17:20:53 2017 +0200
----------------------------------------------------------------------
.../apache/ambari/server/ldap/LdapModule.java | 8 +-
.../service/LdapAttributeDetectionService.java | 4 +-
.../service/LdapConnectionConfigService.java | 34 ++++++
.../service/LdapConnectionTemplateProvider.java | 56 ---------
.../DefaultLdapAttributeDetectionService.java | 4 +-
.../ads/DefaultLdapConfigurationService.java | 11 +-
.../ads/LdapConnectionTemplateFactory.java | 56 +++++----
.../DefaultLdapConnectionConfigService.java | 116 +++++++++++++++++++
.../server/ldap/LdapModuleFunctionalTest.java | 28 +++++
9 files changed, 224 insertions(+), 93 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/ambari/blob/9a50bc15/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
index d59264a..4abf4e7 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
@@ -21,11 +21,11 @@ import org.apache.ambari.server.ldap.service.AmbariLdapConfigurationProvider;
import org.apache.ambari.server.ldap.service.AmbariLdapFacade;
import org.apache.ambari.server.ldap.service.LdapAttributeDetectionService;
import org.apache.ambari.server.ldap.service.LdapConfigurationService;
-import org.apache.ambari.server.ldap.service.LdapConnectionTemplateProvider;
+import org.apache.ambari.server.ldap.service.LdapConnectionConfigService;
import org.apache.ambari.server.ldap.service.LdapFacade;
import org.apache.ambari.server.ldap.service.ads.DefaultLdapAttributeDetectionService;
import org.apache.ambari.server.ldap.service.ads.DefaultLdapConfigurationService;
-import org.apache.directory.ldap.client.template.LdapConnectionTemplate;
+import org.apache.ambari.server.ldap.service.ads.detectors.DefaultLdapConnectionConfigService;
import com.google.inject.AbstractModule;
import com.google.inject.assistedinject.FactoryModuleBuilder;
@@ -40,13 +40,11 @@ public class LdapModule extends AbstractModule {
bind(LdapFacade.class).to(AmbariLdapFacade.class);
bind(LdapConfigurationService.class).to(DefaultLdapConfigurationService.class);
bind(LdapAttributeDetectionService.class).to(DefaultLdapAttributeDetectionService.class);
+ bind(LdapConnectionConfigService.class).to(DefaultLdapConnectionConfigService.class);
// this binding requires the JPA module!
bind(AmbariLdapConfiguration.class).toProvider(AmbariLdapConfigurationProvider.class);
- // bind to the provider implementation (let GUICE deal with instantiating 3rd party instances)
- bind(LdapConnectionTemplate.class).toProvider(LdapConnectionTemplateProvider.class);
-
install(new FactoryModuleBuilder().build(AmbariLdapConfigurationFactory.class));
}
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/9a50bc15/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapAttributeDetectionService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapAttributeDetectionService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapAttributeDetectionService.java
index 6cd369b..c08a2e0 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapAttributeDetectionService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapAttributeDetectionService.java
@@ -27,7 +27,7 @@ public interface LdapAttributeDetectionService {
* @param ambariLdapConfiguration configuration instance holding connection details
* @return the configuration decorated with user related attributes
*/
- AmbariLdapConfiguration detectLdapUserAttributes(AmbariLdapConfiguration ambariLdapConfiguration);
+ AmbariLdapConfiguration detectLdapUserAttributes(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException;
/**
* Decorates the passed in configuration with the detected ldap group attribute values
@@ -35,6 +35,6 @@ public interface LdapAttributeDetectionService {
* @param ambariLdapConfiguration configuration instance holding connection details
* @return the configuration decorated with group related attributes
*/
- AmbariLdapConfiguration detectLdapGroupAttributes(AmbariLdapConfiguration ambariLdapConfiguration);
+ AmbariLdapConfiguration detectLdapGroupAttributes(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException;
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/9a50bc15/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConnectionConfigService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConnectionConfigService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConnectionConfigService.java
new file mode 100644
index 0000000..e2055bb
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConnectionConfigService.java
@@ -0,0 +1,34 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service;
+
+import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
+import org.apache.directory.ldap.client.api.LdapConnectionConfig;
+
+/**
+ * Contract for creating connection configuration instances
+ */
+public interface LdapConnectionConfigService {
+
+ /**
+ * Creates and sets up an ldap connection configuration instance based on the provided ambari ldap configuration instance.
+ *
+ * @param ambariLdapConfiguration instance holding configuration values
+ * @return a set up ldap connection configuration instance
+ * @throws AmbariLdapException if an error occurs while setting up the connection configuration
+ */
+ LdapConnectionConfig createLdapConnectionConfig(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException;
+
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/9a50bc15/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConnectionTemplateProvider.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConnectionTemplateProvider.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConnectionTemplateProvider.java
deleted file mode 100644
index 5ed06e3..0000000
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConnectionTemplateProvider.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.ambari.server.ldap.service;
-
-
-import javax.inject.Inject;
-import javax.inject.Provider;
-
-import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
-import org.apache.directory.ldap.client.api.DefaultLdapConnectionFactory;
-import org.apache.directory.ldap.client.api.LdapConnectionConfig;
-import org.apache.directory.ldap.client.api.LdapConnectionFactory;
-import org.apache.directory.ldap.client.api.LdapConnectionPool;
-import org.apache.directory.ldap.client.api.ValidatingPoolableLdapConnectionFactory;
-import org.apache.directory.ldap.client.template.LdapConnectionTemplate;
-
-public class LdapConnectionTemplateProvider implements Provider<LdapConnectionTemplate> {
-
- // Inject the persisted configuration (when available) check the provider implementation for details.
- @Inject
- private Provider<AmbariLdapConfiguration> ambariLdapConfigurationProvider;
-
- @Override
- public LdapConnectionTemplate get() {
- return new LdapConnectionTemplate(new LdapConnectionPool(
- new ValidatingPoolableLdapConnectionFactory(getLdapConnectionFactory())));
- }
-
- private LdapConnectionConfig getLdapConnectionConfig() {
- LdapConnectionConfig config = new LdapConnectionConfig();
- config.setLdapHost(ambariLdapConfigurationProvider.get().serverHost());
- config.setLdapPort(ambariLdapConfigurationProvider.get().serverPort());
- config.setName(ambariLdapConfigurationProvider.get().bindDn());
- config.setCredentials(ambariLdapConfigurationProvider.get().bindPassword());
-
- return config;
- }
-
- private LdapConnectionFactory getLdapConnectionFactory() {
- return new DefaultLdapConnectionFactory(getLdapConnectionConfig());
- }
-
-
-}
http://git-wip-us.apache.org/repos/asf/ambari/blob/9a50bc15/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionService.java
index 639d48d..204c46a 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionService.java
@@ -73,7 +73,7 @@ public class DefaultLdapAttributeDetectionService implements LdapAttributeDetect
}
@Override
- public AmbariLdapConfiguration detectLdapUserAttributes(AmbariLdapConfiguration ambariLdapConfiguration) {
+ public AmbariLdapConfiguration detectLdapUserAttributes(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
LOGGER.info("Detecting LDAP user attributes ...");
LdapConnectionTemplate ldapConnectionTemplate = ldapConnectionTemplateFactory.create(ambariLdapConfiguration);
@@ -116,7 +116,7 @@ public class DefaultLdapAttributeDetectionService implements LdapAttributeDetect
@Override
- public AmbariLdapConfiguration detectLdapGroupAttributes(AmbariLdapConfiguration ambariLdapConfiguration) {
+ public AmbariLdapConfiguration detectLdapGroupAttributes(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
LOGGER.info("Detecting LDAP group attributes ...");
// perform a search using the user search base
http://git-wip-us.apache.org/repos/asf/ambari/blob/9a50bc15/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
index bbe4d0a..60c1272 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
@@ -28,7 +28,6 @@ import org.apache.directory.api.ldap.model.constants.SchemaConstants;
import org.apache.directory.api.ldap.model.entry.Entry;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.api.ldap.model.message.SearchRequest;
-import org.apache.directory.api.ldap.model.message.SearchRequestImpl;
import org.apache.directory.api.ldap.model.message.SearchScope;
import org.apache.directory.api.ldap.model.name.Dn;
import org.apache.directory.ldap.client.api.LdapConnection;
@@ -117,7 +116,6 @@ public class DefaultLdapConfigurationService implements LdapConfigurationService
/**
* Checks whether the provided group related settings are correct.
- * The algorithm implemented in this method per
*
* @param userDn a user DN to check
* @param ambariLdapConfiguration the available LDAP configuration to be validated
@@ -137,18 +135,15 @@ public class DefaultLdapConfigurationService implements LdapConfigurationService
).toString();
LOGGER.info("Searching for the groups the user dn: {} is member of using the search filter: {}", userDn, filter);
+ LdapConnectionTemplate ldapConnectionTemplate = ldapConnectionTemplateFactory.create(ambariLdapConfiguration);
// assemble a search request
- SearchRequest searchRequest = new SearchRequestImpl();
- searchRequest.setFilter(filter);
- searchRequest.setBase(new Dn(ambariLdapConfiguration.groupSearchBase()));
- searchRequest.setScope(SearchScope.SUBTREE);
+ SearchRequest searchRequest = ldapConnectionTemplate.newSearchRequest(new Dn(ambariLdapConfiguration.groupSearchBase()), filter, SearchScope.SUBTREE);
// attributes to be returned
searchRequest.addAttributes(ambariLdapConfiguration.groupMemberAttribute(), ambariLdapConfiguration.groupNameAttribute());
// perform the search
- groups = ldapConnectionTemplateFactory.create(ambariLdapConfiguration).search(searchRequest, getGroupNameEntryMapper(ambariLdapConfiguration));
-
+ groups = ldapConnectionTemplate.search(searchRequest, getGroupNameEntryMapper(ambariLdapConfiguration));
} catch (Exception e) {
http://git-wip-us.apache.org/repos/asf/ambari/blob/9a50bc15/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/LdapConnectionTemplateFactory.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/LdapConnectionTemplateFactory.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/LdapConnectionTemplateFactory.java
index 50345bc..8467af0 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/LdapConnectionTemplateFactory.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/LdapConnectionTemplateFactory.java
@@ -18,7 +18,10 @@ import javax.inject.Inject;
import javax.inject.Provider;
import javax.inject.Singleton;
+import org.apache.ambari.server.events.AmbariLdapConfigChangedEvent;
import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.service.AmbariLdapException;
+import org.apache.ambari.server.ldap.service.LdapConnectionConfigService;
import org.apache.directory.ldap.client.api.DefaultLdapConnectionFactory;
import org.apache.directory.ldap.client.api.LdapConnectionConfig;
import org.apache.directory.ldap.client.api.LdapConnectionFactory;
@@ -28,6 +31,8 @@ import org.apache.directory.ldap.client.template.LdapConnectionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import com.google.common.eventbus.Subscribe;
+
/**
* Factory for creating LdapConnectionTemplate instances.
* Depending on the usage context, the instance can be constructed based on the provided configuration or based on the persisted settings.
@@ -37,8 +42,17 @@ public class LdapConnectionTemplateFactory {
private static final Logger LOG = LoggerFactory.getLogger(LdapConnectionTemplateFactory.class);
+ // Inject the persisted configuration (when available) check the provider implementation for details.
+ @Inject
+ private Provider<AmbariLdapConfiguration> ambariLdapConfigurationProvider;
+
+
@Inject
- private Provider<LdapConnectionTemplate> ldapConnectionTemplate;
+ private LdapConnectionConfigService ldapConnectionConfigService;
+
+ // cached instance that only changes when the underlying configuration changes.
+ private LdapConnectionTemplate ldapConnectionTemplateInstance;
+
@Inject
public LdapConnectionTemplateFactory() {
@@ -50,11 +64,11 @@ public class LdapConnectionTemplateFactory {
* @param ambariLdapConfiguration ambari ldap configuration instance
* @return an instance of LdapConnectionTemplate
*/
- public LdapConnectionTemplate create(AmbariLdapConfiguration ambariLdapConfiguration) {
+ public LdapConnectionTemplate create(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
LOG.info("Constructing new instance based on the provided ambari ldap configuration: {}", ambariLdapConfiguration);
// create the connection config
- LdapConnectionConfig ldapConnectionConfig = getLdapConnectionConfig(ambariLdapConfiguration);
+ LdapConnectionConfig ldapConnectionConfig = ldapConnectionConfigService.createLdapConnectionConfig(ambariLdapConfiguration);
// create the connection factory
LdapConnectionFactory ldapConnectionFactory = new DefaultLdapConnectionFactory(ldapConnectionConfig);
@@ -69,26 +83,28 @@ public class LdapConnectionTemplateFactory {
}
- public LdapConnectionTemplate load() {
- // the construction logic is implemented in the provider class
- return ldapConnectionTemplate.get();
- }
-
-
- private LdapConnectionConfig getLdapConnectionConfig(AmbariLdapConfiguration ambariLdapConfiguration) {
-
- LdapConnectionConfig config = new LdapConnectionConfig();
- config.setLdapHost(ambariLdapConfiguration.serverHost());
- config.setLdapPort(ambariLdapConfiguration.serverPort());
- config.setName(ambariLdapConfiguration.bindDn());
- config.setCredentials(ambariLdapConfiguration.bindPassword());
+ /**
+ * Loads the persisted LDAP configuration.
+ *
+ * @return theh persisted
+ */
+ public LdapConnectionTemplate load() throws AmbariLdapException {
- // todo set the other required properties here, eg.: trustmanager
- return config;
+ if (null == ldapConnectionTemplateInstance) {
+ ldapConnectionTemplateInstance = create(ambariLdapConfigurationProvider.get());
+ }
+ return ldapConnectionTemplateInstance;
}
- private LdapConnectionFactory getLdapConnectionFactory(AmbariLdapConfiguration ambariLdapConfiguration) {
- return new DefaultLdapConnectionFactory(getLdapConnectionConfig(ambariLdapConfiguration));
+ /**
+ * The returned connection template instance is recreated whenever the ambari ldap configuration changes
+ *
+ * @param event
+ * @throws AmbariLdapException
+ */
+ @Subscribe
+ public void onConfigChange(AmbariLdapConfigChangedEvent event) throws AmbariLdapException {
+ ldapConnectionTemplateInstance = create(ambariLdapConfigurationProvider.get());
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/9a50bc15/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/DefaultLdapConnectionConfigService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/DefaultLdapConnectionConfigService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/DefaultLdapConnectionConfigService.java
new file mode 100644
index 0000000..b12cc85
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/DefaultLdapConnectionConfigService.java
@@ -0,0 +1,116 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service.ads.detectors;
+
+import static javax.net.ssl.TrustManagerFactory.getDefaultAlgorithm;
+
+import java.io.FileInputStream;
+import java.security.KeyStore;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.TrustManagerFactory;
+
+import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.service.AmbariLdapException;
+import org.apache.ambari.server.ldap.service.LdapConnectionConfigService;
+import org.apache.directory.api.util.Strings;
+import org.apache.directory.ldap.client.api.LdapConnectionConfig;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Singleton
+public class DefaultLdapConnectionConfigService implements LdapConnectionConfigService {
+
+ private static Logger LOG = LoggerFactory.getLogger(DefaultLdapConnectionConfigService.class);
+
+ @Inject
+ public DefaultLdapConnectionConfigService() {
+ }
+
+ @Override
+ public LdapConnectionConfig createLdapConnectionConfig(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
+
+ LOG.debug("Assembling ldap connection config based on: {}", ambariLdapConfiguration);
+
+ LdapConnectionConfig config = new LdapConnectionConfig();
+ config.setLdapHost(ambariLdapConfiguration.serverHost());
+ config.setLdapPort(ambariLdapConfiguration.serverPort());
+ config.setName(ambariLdapConfiguration.bindDn());
+ config.setCredentials(ambariLdapConfiguration.bindPassword());
+ config.setUseSsl(ambariLdapConfiguration.useSSL());
+
+ // todo implement proper validation logic here: identify optional/mandatory settings
+ // todo suggest proper naming
+ if ("custom".equals(ambariLdapConfiguration.trustStore())) {
+ LOG.info("Using custom trust manager configuration");
+ config.setTrustManagers(trustManagers(ambariLdapConfiguration));
+ }
+
+
+ return config;
+ }
+
+
+ /**
+ * Configure the trustmanagers to use the custom keystore.
+ *
+ * @param ambariLdapConfiguration congiguration instance holding current values
+ * @return the array of trust managers
+ * @throws AmbariLdapException if an error occurs while setting up the connection
+ */
+ private TrustManager[] trustManagers(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
+ try {
+
+ TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(getDefaultAlgorithm());
+ tmFactory.init(keyStore(ambariLdapConfiguration));
+ return tmFactory.getTrustManagers();
+
+ } catch (Exception e) {
+
+ LOG.error("Failed to initialize trust managers", e);
+ throw new AmbariLdapException(e);
+
+ }
+
+ }
+
+ private KeyStore keyStore(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
+
+ // validating configuration settings
+ if (Strings.isEmpty(ambariLdapConfiguration.trustStoreType())) {
+ throw new AmbariLdapException("Key Store Type must be specified");
+ }
+
+ if (Strings.isEmpty(ambariLdapConfiguration.trustStorePath())) {
+ throw new AmbariLdapException("Key Store Path must be specified");
+ }
+
+ try {
+
+ KeyStore ks = KeyStore.getInstance(ambariLdapConfiguration.trustStoreType());
+ FileInputStream fis = new FileInputStream(ambariLdapConfiguration.trustStorePath());
+ ks.load(fis, ambariLdapConfiguration.trustStorePassword().toCharArray());
+ return ks;
+
+ } catch (Exception e) {
+
+ LOG.error("Failed to create keystore", e);
+ throw new AmbariLdapException(e);
+
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/9a50bc15/ambari-server/src/test/java/org/apache/ambari/server/ldap/LdapModuleFunctionalTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/LdapModuleFunctionalTest.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/LdapModuleFunctionalTest.java
index 8059723..b9f140e 100644
--- a/ambari-server/src/test/java/org/apache/ambari/server/ldap/LdapModuleFunctionalTest.java
+++ b/ambari-server/src/test/java/org/apache/ambari/server/ldap/LdapModuleFunctionalTest.java
@@ -21,6 +21,7 @@ import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
import org.apache.ambari.server.ldap.domain.TestAmbariAmbariLdapConfigurationFactory;
import org.apache.ambari.server.ldap.service.LdapConfigurationService;
import org.apache.ambari.server.ldap.service.LdapFacade;
+import org.apache.ambari.server.ldap.service.ads.LdapConnectionTemplateFactory;
import org.apache.directory.api.ldap.model.constants.SchemaConstants;
import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.api.ldap.model.exception.LdapInvalidDnException;
@@ -130,14 +131,41 @@ public class LdapModuleFunctionalTest {
ldapPropsMap.put(AmbariLdapConfigKeys.SERVER_PORT.key(), "389");
ldapPropsMap.put(AmbariLdapConfigKeys.BIND_DN.key(), "cn=read-only-admin,dc=example,dc=com");
ldapPropsMap.put(AmbariLdapConfigKeys.BIND_PASSWORD.key(), "password");
+ ldapPropsMap.put(AmbariLdapConfigKeys.USE_SSL.key(), "true");
ldapPropsMap.put(AmbariLdapConfigKeys.USER_OBJECT_CLASS.key(), SchemaConstants.PERSON_OC);
ldapPropsMap.put(AmbariLdapConfigKeys.USER_NAME_ATTRIBUTE.key(), SchemaConstants.UID_AT);
ldapPropsMap.put(AmbariLdapConfigKeys.USER_SEARCH_BASE.key(), "dc=example,dc=com");
ldapPropsMap.put(AmbariLdapConfigKeys.DN_ATTRIBUTE.key(), SchemaConstants.UID_AT);
+ ldapPropsMap.put(AmbariLdapConfigKeys.TRUST_STORE.key(), "custom");
+ ldapPropsMap.put(AmbariLdapConfigKeys.TRUST_STORE_TYPE.key(), "JKS");
+ ldapPropsMap.put(AmbariLdapConfigKeys.TRUST_STORE_PATH.key(), "/Users/lpuskas/my_truststore/KeyStore.jks");
+ ldapPropsMap.put(AmbariLdapConfigKeys.TRUST_STORE_PASSWORD.key(), "lofasz");
return ldapPropsMap;
}
+
+ @Test
+ public void testShouldCustomTrustManagersBeSetForLdapConnection() throws Exception {
+ // GIVEN
+ AmbariLdapConfiguration ambariLdapConfiguration = ldapConfigurationFactory.createLdapConfiguration(getProps());
+
+ LdapFacade ldapFacade = injector.getInstance(LdapFacade.class);
+
+ LdapConnectionTemplateFactory lctFactory = injector.getInstance(LdapConnectionTemplateFactory.class);
+
+ LdapConnectionTemplate template1 = lctFactory.load();
+ LdapConnectionTemplate template2 = lctFactory.create(ambariLdapConfiguration);
+
+
+ // WHEN
+ ldapFacade.checkConnection(ambariLdapConfiguration);
+
+ ldapFacade.detectAttributes(ambariLdapConfiguration);
+
+ // THEN
+ // no exceptions thrown
+ }
}
\ No newline at end of file
[22/33] ambari git commit: AMBARI-21307 implemented user attribute
detection. Organized code
Posted by lp...@apache.org.
AMBARI-21307 implemented user attribute detection. Organized code
Project: http://git-wip-us.apache.org/repos/asf/ambari/repo
Commit: http://git-wip-us.apache.org/repos/asf/ambari/commit/d0e543cf
Tree: http://git-wip-us.apache.org/repos/asf/ambari/tree/d0e543cf
Diff: http://git-wip-us.apache.org/repos/asf/ambari/diff/d0e543cf
Branch: refs/heads/feature-branch-AMBARI-21307
Commit: d0e543cf7f244e89b2b220c23c21351d9d27f6c3
Parents: 3800adf
Author: lpuskas <lp...@apache.org>
Authored: Tue Sep 12 08:10:47 2017 +0200
Committer: lpuskas <lp...@apache.org>
Committed: Fri Oct 13 17:20:51 2017 +0200
----------------------------------------------------------------------
.../services/ldap/LdapConfigurationService.java | 2 +-
.../server/ldap/AmbariLdapConfiguration.java | 9 ++
.../server/ldap/service/AmbariLdapFacade.java | 2 +-
.../server/ldap/service/AttributeDetector.java | 38 ++++++
.../service/LdapAttributeDetectionService.java | 7 +-
.../ambari/server/ldap/service/LdapFacade.java | 2 +-
.../server/ldap/service/LdapSearchService.java | 18 ---
.../ads/DefaultAttributeDetectionService.java | 132 ++++++++++++++++++-
.../ads/DefaultLdapConfigurationService.java | 2 +-
.../ldap/service/ads/ObjectClassDetector.java | 81 ++++++++++++
.../ads/OccurranceAndWeightBasedDetector.java | 81 ++++++++++++
.../service/ads/UserNameAttributeDetector.java | 75 +++++++++++
.../DefaultAttributeDetectionServiceTest.java | 35 ++---
13 files changed, 440 insertions(+), 44 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/ambari/blob/d0e543cf/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationService.java b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationService.java
index 1b8427b..66809c3 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationService.java
@@ -107,7 +107,7 @@ public class LdapConfigurationService extends AmbariConfigurationService {
case TEST_ATTRIBUTES:
LOGGER.info("Testing LDAP attributes ....");
- groups = ldapFacade.checkLdapAttibutes(ldapConfigurationRequest.getRequestInfo().getParameters(), ambariLdapConfiguration);
+ groups = ldapFacade.checkLdapAttributes(ldapConfigurationRequest.getRequestInfo().getParameters(), ambariLdapConfiguration);
setResult(groups, result);
break;
http://git-wip-us.apache.org/repos/asf/ambari/blob/d0e543cf/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
index 76faeed..e28c6ed 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
@@ -98,6 +98,10 @@ public class AmbariLdapConfiguration {
return value;
}
+ public void setValueFor(AmbariLdapConfig ambariLdapConfig, Object value) {
+ configurationMap.put(ambariLdapConfig.key(), value);
+ }
+
@Inject
public AmbariLdapConfiguration(@Assisted Map<String, Object> configuration) {
this.configurationMap = configuration;
@@ -219,4 +223,9 @@ public class AmbariLdapConfiguration {
return (String) configValue(AmbariLdapConfig.REFERRAL_HANDLING);
}
+
+ @Override
+ public String toString() {
+ return configurationMap.toString();
+ }
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/d0e543cf/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
index 16bf6b7..f159418 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
@@ -90,7 +90,7 @@ public class AmbariLdapFacade implements LdapFacade {
}
@Override
- public Set<String> checkLdapAttibutes(Map<String, Object> parameters, AmbariLdapConfiguration ldapConfiguration) throws AmbariLdapException {
+ public Set<String> checkLdapAttributes(Map<String, Object> parameters, AmbariLdapConfiguration ldapConfiguration) throws AmbariLdapException {
String userName = getTestUserNameFromParameters(parameters);
String testUserPass = getTestUserPasswordFromParameters(parameters);
http://git-wip-us.apache.org/repos/asf/ambari/blob/d0e543cf/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AttributeDetector.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AttributeDetector.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AttributeDetector.java
new file mode 100644
index 0000000..3e20a6a
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AttributeDetector.java
@@ -0,0 +1,38 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service;
+
+/**
+ * Operations for detecting LDAP related settings.
+ * Attributes and values are detected based on a sample set of results returned from a search
+ */
+public interface AttributeDetector<T> {
+
+ /**
+ * Collects potential attribute names or values from a set of result entries.
+ *
+ * @param entry a result entry returned by a search operation
+ */
+ void collect(T entry);
+
+ /**
+ * Implements the decision based on whiche the "best" possible attribute or value is selected.
+ *
+ * @return the most probable attribute name or value (based on the logic in the implementer)
+ */
+ String detect();
+
+
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/d0e543cf/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapAttributeDetectionService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapAttributeDetectionService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapAttributeDetectionService.java
index 70a8977..4cfa81e 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapAttributeDetectionService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapAttributeDetectionService.java
@@ -15,12 +15,11 @@
package org.apache.ambari.server.ldap.service;
import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
-import org.apache.directory.ldap.client.api.LdapConnection;
/**
* Contract defining operations to detect user and group attributes.
*/
-public interface LdapAttributeDetectionService {
+public interface LdapAttributeDetectionService<T> {
/**
* Decorates the passed in configuration with the detected ldap user attribute values
@@ -29,7 +28,7 @@ public interface LdapAttributeDetectionService {
* @param ambariLdapConfiguration configuration instance holding connection details
* @return the configuration decorated with user related attributes
*/
- AmbariLdapConfiguration detectLdapUserAttributes(LdapConnection ldapConnection, AmbariLdapConfiguration ambariLdapConfiguration);
+ AmbariLdapConfiguration detectLdapUserAttributes(T ldapConnection, AmbariLdapConfiguration ambariLdapConfiguration);
/**
* Decorates the passed in configuration with the detected ldap group attribute values
@@ -38,6 +37,6 @@ public interface LdapAttributeDetectionService {
* @param ambariLdapConfiguration configuration instance holding connection details
* @return the configuration decorated with group related attributes
*/
- AmbariLdapConfiguration detectLdapGroupAttributes(LdapConnection ldapConnection, AmbariLdapConfiguration ambariLdapConfiguration);
+ AmbariLdapConfiguration detectLdapGroupAttributes(T ldapConnection, AmbariLdapConfiguration ambariLdapConfiguration);
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/d0e543cf/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java
index 76b16c4..7cd25da 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java
@@ -48,5 +48,5 @@ public interface LdapFacade {
* @param ambariLdapConfiguration configutration instance with available attributes
* @throws AmbariLdapException if the attribute checking fails
*/
- Set<String> checkLdapAttibutes(Map<String, Object> parameters, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException;
+ Set<String> checkLdapAttributes(Map<String, Object> parameters, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException;
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/d0e543cf/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapSearchService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapSearchService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapSearchService.java
deleted file mode 100644
index f1abc8b..0000000
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapSearchService.java
+++ /dev/null
@@ -1,18 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.ambari.server.ldap.service;
-
-public interface LdapSearchService {
-}
http://git-wip-us.apache.org/repos/asf/ambari/blob/d0e543cf/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionService.java
index 55d0765..710adf1 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionService.java
@@ -14,19 +14,47 @@
package org.apache.ambari.server.ldap.service.ads;
+import java.util.Set;
+
import javax.inject.Inject;
import javax.inject.Singleton;
import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.service.AmbariLdapException;
+import org.apache.ambari.server.ldap.service.AttributeDetector;
import org.apache.ambari.server.ldap.service.LdapAttributeDetectionService;
+import org.apache.directory.api.ldap.model.cursor.SearchCursor;
+import org.apache.directory.api.ldap.model.entry.Entry;
+import org.apache.directory.api.ldap.model.message.Response;
+import org.apache.directory.api.ldap.model.message.SearchRequest;
+import org.apache.directory.api.ldap.model.message.SearchRequestImpl;
+import org.apache.directory.api.ldap.model.message.SearchResultEntry;
+import org.apache.directory.api.ldap.model.message.SearchScope;
+import org.apache.directory.api.ldap.model.name.Dn;
+import org.apache.directory.api.util.Strings;
import org.apache.directory.ldap.client.api.LdapConnection;
+import org.apache.directory.ldap.client.api.search.FilterBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import com.google.common.collect.Sets;
+
@Singleton
-public class DefaultAttributeDetectionService implements LdapAttributeDetectionService {
+public class DefaultAttributeDetectionService implements LdapAttributeDetectionService<LdapConnection> {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultAttributeDetectionService.class);
+ private static final int SAMPLE_RESULT_SIZE = 50;
+
+ // ordered list of possible username attribute values (the most significant valus should be first)
+
+ private static final Set<String> USER_OBJECT_CLASS_VALUES = Sets.newHashSet("person", "posixAccount");
+ private static final Set<String> USER_GROUP_MEMBER_ATTR_VALUES = Sets.newHashSet("memberOf", "ismemberOf");
+
+ @Inject
+ private UserNameAttributeDetector userNameAttrDetector = new UserNameAttributeDetector(); // todo remove instantition
+
+ @Inject
+ private ObjectClassDetector objectClassDetector = new ObjectClassDetector(); // todo remove instantition
@Inject
public DefaultAttributeDetectionService() {
@@ -36,7 +64,72 @@ public class DefaultAttributeDetectionService implements LdapAttributeDetectionS
public AmbariLdapConfiguration detectLdapUserAttributes(LdapConnection connection, AmbariLdapConfiguration ambariLdapConfiguration) {
LOGGER.info("Detecting LDAP user attributes ...");
- return null;
+ // perform a search using the user search base
+ if (Strings.isEmpty(ambariLdapConfiguration.userSearchBase())) {
+ LOGGER.warn("No user search base provided");
+ return ambariLdapConfiguration;
+ }
+
+ SearchCursor searchCursor = null;
+
+ try {
+ // todo should the bind operation be done in the facade?
+ connection.bind(ambariLdapConfiguration.bindDn(), ambariLdapConfiguration.bindPassword());
+
+ SearchRequest searchRequest = assembleSearchRequest(ambariLdapConfiguration);
+
+ // do the search
+ searchCursor = connection.search(searchRequest);
+
+ int processedUserCnt = 0;
+
+ while (searchCursor.next()) {
+
+ if (processedUserCnt >= SAMPLE_RESULT_SIZE) {
+ LOGGER.debug("The maximum count of results for attribute detection has exceeded. Quit user attribute detection.");
+ break;
+ }
+
+ Response response = searchCursor.get();
+ // process the SearchResultEntry
+
+ if (response instanceof SearchResultEntry) {
+ Entry resultEntry = ((SearchResultEntry) response).getEntry();
+ LOGGER.info("Processing sample entry: [{}]", resultEntry.getDn());
+ userNameAttrDetector.collect(resultEntry);
+ objectClassDetector.collect(resultEntry);
+ processedUserCnt++;
+ }
+ }
+
+ ambariLdapConfiguration.setValueFor(AmbariLdapConfiguration.AmbariLdapConfig.USER_NAME_ATTRIBUTE, userNameAttrDetector.detect());
+ ambariLdapConfiguration.setValueFor(AmbariLdapConfiguration.AmbariLdapConfig.USER_OBJECT_CLASS, objectClassDetector.detect());
+
+ LOGGER.info("Decorated ambari ldap config : [{}]", ambariLdapConfiguration);
+
+ } catch (Exception e) {
+
+ LOGGER.error("Ldap operation failed", e);
+ } finally {
+ // housekeeping
+ if (null != searchCursor) {
+ searchCursor.close();
+ }
+ }
+
+ return ambariLdapConfiguration;
+ }
+
+ private void detectUserAttributes(Entry resultEntry, AttributeDetector attributeDetector) {
+
+ attributeDetector.collect(resultEntry);
+
+// Set<String> objectClasses = detectUserObjectClass(resultEntry);
+// if (!objectClasses.isEmpty()) {
+// ambariLdapConfiguration.setValueFor(AmbariLdapConfiguration.AmbariLdapConfig.USER_OBJECT_CLASS, StringUtils.join(objectClasses, ","));
+// }
+
+
}
@Override
@@ -44,4 +137,39 @@ public class DefaultAttributeDetectionService implements LdapAttributeDetectionS
LOGGER.info("Detecting LDAP group attributes ...");
return null;
}
+
+ private SearchRequest assembleSearchRequest(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
+ try {
+
+ SearchRequest req = new SearchRequestImpl();
+ req.setScope(SearchScope.SUBTREE);
+ req.addAttributes("*");
+ req.setTimeLimit(0);
+ req.setBase(new Dn(ambariLdapConfiguration.userSearchBase()));
+ // the filter must be set!
+ req.setFilter(FilterBuilder.present(ambariLdapConfiguration.dnAttribute()).toString());
+
+ return req;
+
+ } catch (Exception e) {
+ LOGGER.error("Could not assemble ldap search request", e);
+ throw new AmbariLdapException(e);
+ }
+ }
+
+
+ private Set<String> detectUserObjectClass(Entry entry) {
+ LOGGER.info("Detecting user object class. Attributes: {}", entry.getAttributes());
+ throw new UnsupportedOperationException("Not yet implemented");
+ }
+
+ private String detectGroupNameAttribute(Entry entry) {
+ throw new UnsupportedOperationException("Not yet implemented");
+ }
+
+ private Set<String> detectGroupObjectClass(Entry entry) {
+ throw new UnsupportedOperationException("Not yet implemented");
+ }
+
+
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/d0e543cf/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
index db8c77f..fa2e44b 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
@@ -190,7 +190,7 @@ public class DefaultLdapConfigurationService implements LdapConfigurationService
LOGGER.debug("Anonimous binding not supported, binding with the manager detailas...");
connection.bind(ambariLdapConfiguration.bindDn(), ambariLdapConfiguration.bindPassword());
} else {
- LOGGER.debug("Binding anonimously ...");
+ LOGGER.debug("Binding anonymously ...");
connection.bind();
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/d0e543cf/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/ObjectClassDetector.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/ObjectClassDetector.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/ObjectClassDetector.java
new file mode 100644
index 0000000..2613517
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/ObjectClassDetector.java
@@ -0,0 +1,81 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service.ads;
+
+import java.util.Map;
+
+import javax.inject.Inject;
+
+import org.apache.directory.api.ldap.model.entry.Entry;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.collect.Maps;
+
+public class ObjectClassDetector extends OccurranceAndWeightBasedDetector {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(ObjectClassDetector.class);
+ private Map<String, Integer> occurranceMap = Maps.newHashMap();
+ private Map<String, Integer> weightsMap = Maps.newHashMap();
+
+
+ private enum ObjectClassValue {
+ PERSON("person", 1),
+ POSIX_ACCOUNT("posixAccount", 1);
+
+ private String ocVal;
+ private Integer weight;
+
+ ObjectClassValue(String attr, Integer weght) {
+ this.ocVal = attr;
+ this.weight = weght;
+ }
+
+ Integer weight() {
+ return this.weight;
+ }
+
+ String ocVal() {
+ return this.ocVal;
+ }
+
+ }
+
+ @Inject
+ public ObjectClassDetector() {
+ for (ObjectClassValue ocVal : ObjectClassValue.values()) {
+ occurranceMap.put(ocVal.ocVal(), 0);
+ weightsMap.put(ocVal.ocVal(), ocVal.weight());
+ }
+
+ }
+
+ @Override
+ protected Map<String, Integer> occurranceMap() {
+ return occurranceMap;
+ }
+
+ @Override
+ protected Map<String, Integer> weightsMap() {
+ return weightsMap;
+ }
+
+ @Override
+ protected boolean applies(Entry entry, String value) {
+ LOGGER.info("Checking for object class [{}] in entry [{}]", value, entry.getDn());
+ return entry.hasObjectClass(value);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/d0e543cf/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/OccurranceAndWeightBasedDetector.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/OccurranceAndWeightBasedDetector.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/OccurranceAndWeightBasedDetector.java
new file mode 100644
index 0000000..32dc238
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/OccurranceAndWeightBasedDetector.java
@@ -0,0 +1,81 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service.ads;
+
+import java.util.Map;
+
+import org.apache.ambari.server.ldap.service.AttributeDetector;
+import org.apache.directory.api.ldap.model.entry.Entry;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public abstract class OccurranceAndWeightBasedDetector implements AttributeDetector<Entry> {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(OccurranceAndWeightBasedDetector.class);
+
+ protected abstract Map<String, Integer> occurranceMap();
+
+ protected abstract Map<String, Integer> weightsMap();
+
+ protected abstract boolean applies(Entry entry, String value);
+
+ @Override
+ public String detect() {
+ Map.Entry<String, Integer> selectedEntry = null;
+
+ for (Map.Entry<String, Integer> entry : occurranceMap().entrySet()) {
+ if (selectedEntry == null) {
+
+ selectedEntry = entry;
+ LOGGER.info("Initial name attribute: {}", selectedEntry);
+ continue;
+
+ }
+
+ if (selectedEntry.getValue() < entry.getValue()) {
+
+ LOGGER.info("Changing potential name attribute from : [{}] to: [{}]", selectedEntry, entry);
+ selectedEntry = entry;
+
+ }
+ }
+ return selectedEntry.getKey();
+ }
+
+ @Override
+ public void collect(Entry entry) {
+ LOGGER.info("Detecting ldap attributes/values ...");
+
+ for (String attributeValue : occurranceMap().keySet()) {
+ if (applies(entry, attributeValue)) {
+
+ Integer cnt = occurranceMap().get(attributeValue).intValue();
+ if (weightsMap().containsKey(attributeValue)) {
+ cnt = cnt + weightsMap().get(attributeValue);
+ } else {
+ cnt = cnt + 1;
+ }
+ occurranceMap().put(attributeValue, cnt);
+
+ LOGGER.info("Collected potential name attr: {}, count: {}", attributeValue, cnt);
+
+ } else {
+ LOGGER.info("The result entry doesn't contain the attribute: [{}]", attributeValue);
+ }
+ }
+ }
+
+
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/d0e543cf/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/UserNameAttributeDetector.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/UserNameAttributeDetector.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/UserNameAttributeDetector.java
new file mode 100644
index 0000000..bbb4b43
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/UserNameAttributeDetector.java
@@ -0,0 +1,75 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service.ads;
+
+import java.util.Map;
+
+import org.apache.directory.api.ldap.model.entry.Entry;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.collect.Maps;
+
+public class UserNameAttributeDetector extends OccurranceAndWeightBasedDetector {
+ private static final Logger LOGGER = LoggerFactory.getLogger(UserNameAttributeDetector.class);
+
+ private Map<String, Integer> occurranceMap = Maps.newHashMap();
+ private Map<String, Integer> weightsMap = Maps.newHashMap();
+
+ private enum NameAttrs {
+ SAM_ACCOUNT_NAME("sAMAccountName", 5),
+ UID("uid", 3),
+ CN("cn", 1);
+
+ private String attrName;
+ private Integer weight;
+
+ NameAttrs(String attr, Integer weght) {
+ this.attrName = attr;
+ this.weight = weght;
+ }
+
+ Integer weight() {
+ return this.weight;
+ }
+
+ String attrName() {
+ return this.attrName;
+ }
+
+ }
+
+ public UserNameAttributeDetector() {
+ for (NameAttrs nameAttr : NameAttrs.values()) {
+ occurranceMap.put(nameAttr.attrName(), 0);
+ weightsMap.put(nameAttr.attrName(), nameAttr.weight());
+ }
+ }
+
+ protected Map<String, Integer> occurranceMap() {
+ return occurranceMap;
+ }
+
+ protected Map<String, Integer> weightsMap() {
+ return weightsMap;
+ }
+
+ @Override
+ protected boolean applies(Entry entry, String value) {
+ LOGGER.info("Checking for attribute [{}] in entry [{}]", value, entry.getDn());
+ return entry.containsAttribute(value);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/d0e543cf/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionServiceTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionServiceTest.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionServiceTest.java
index 5b3ac20..5cddf1a 100644
--- a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionServiceTest.java
+++ b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionServiceTest.java
@@ -69,13 +69,31 @@ public class DefaultAttributeDetectionServiceTest {
}
+ @Test
+ public void functionalTest() throws Exception {
+ // GIVEN
+ AmbariLdapConfiguration ambariLdapConfiguration = new AmbariLdapConfiguration(getTestPropertiesMap());
+ LdapConnectionService connectionService = new DefaultLdapConnectionService();
+ LdapNetworkConnection ldapConnection = connectionService.createLdapConnection(ambariLdapConfiguration);
+
+ // WHEN
+ AmbariLdapConfiguration config = attributeDetectionService.detectLdapUserAttributes(ldapConnection, ambariLdapConfiguration);
+
+ // THEN
+
+ ldapConnection.close();
+
+ }
+
private Map<String, Object> getTestPropertiesMap() {
Map<String, Object> ldapPropsMap = Maps.newHashMap();
ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.ANONYMOUS_BIND.key(), "true");
ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.SERVER_HOST.key(), "ldap.forumsys.com");
ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.SERVER_PORT.key(), "389");
- ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.BIND_DN.key(), "dc=example,dc=com");
+ ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.BIND_DN.key(), "cn=read-only-admin,dc=example,dc=com");
+ ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.BIND_PASSWORD.key(), "password");
+ ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.DN_ATTRIBUTE.key(), SchemaConstants.CN_AT);
ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.USER_OBJECT_CLASS.key(), SchemaConstants.PERSON_OC);
ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.USER_NAME_ATTRIBUTE.key(), SchemaConstants.UID_AT);
@@ -84,19 +102,4 @@ public class DefaultAttributeDetectionServiceTest {
return ldapPropsMap;
}
-
- @Test
- public void functionalTest() throws Exception {
- // GIVEN
- AmbariLdapConfiguration ambariLdapConfiguration = new AmbariLdapConfiguration(getTestPropertiesMap());
- LdapConnectionService connectionService = new DefaultLdapConnectionService();
- LdapNetworkConnection ldapConnection = connectionService.createLdapConnection(ambariLdapConfiguration);
-
-
- // WHEN
- AmbariLdapConfiguration config = attributeDetectionService.detectLdapUserAttributes(ldapConnection, ambariLdapConfiguration);
-
- // THEN
-
- }
}
\ No newline at end of file
[18/33] ambari git commit: AMBARI-21307 refactoring - renamed,
moved classes, variables
Posted by lp...@apache.org.
AMBARI-21307 refactoring - renamed, moved classes, variables
Project: http://git-wip-us.apache.org/repos/asf/ambari/repo
Commit: http://git-wip-us.apache.org/repos/asf/ambari/commit/176356bd
Tree: http://git-wip-us.apache.org/repos/asf/ambari/tree/176356bd
Diff: http://git-wip-us.apache.org/repos/asf/ambari/diff/176356bd
Branch: refs/heads/feature-branch-AMBARI-21307
Commit: 176356bde7cddcd203ec576a420371e40bf389a2
Parents: d062cf0
Author: lpuskas <lp...@apache.org>
Authored: Tue Aug 22 10:03:24 2017 +0200
Committer: lpuskas <lp...@apache.org>
Committed: Fri Oct 13 17:20:50 2017 +0200
----------------------------------------------------------------------
.../api/services/ldap/AmbariConfiguration.java | 87 +++++++
.../services/ldap/AmbariConfigurationDTO.java | 67 -----
.../ldap/LdapCheckConfigurationRequest.java | 47 ----
.../api/services/ldap/LdapConfigOperation.java | 43 ++++
.../services/ldap/LdapConfigurationRequest.java | 49 ++++
.../services/ldap/LdapConfigurationService.java | 53 +---
.../api/services/ldap/LdapOperationRequest.java | 18 --
.../server/ldap/LdapConfigurationService.java | 60 +++++
.../ldap/LdapConfigurationValidatorService.java | 60 -----
.../apache/ambari/server/ldap/LdapModule.java | 4 +-
.../server/ldap/service/AmbariLdapFacade.java | 10 +-
.../ads/DefaultLdapConfigurationService.java | 243 +++++++++++++++++++
...efaultLdapConfigurationValidatorService.java | 243 -------------------
.../api/services/ldap/LDAPServiceTest.java | 6 +-
.../DefaultLdapConfigurationServiceTest.java | 113 +++++++++
...ltLdapConfigurationValidatorServiceTest.java | 113 ---------
16 files changed, 618 insertions(+), 598 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/ambari/blob/176356bd/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/AmbariConfiguration.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/AmbariConfiguration.java b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/AmbariConfiguration.java
new file mode 100644
index 0000000..b5cc921
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/AmbariConfiguration.java
@@ -0,0 +1,87 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.api.services.ldap;
+
+import java.util.Collections;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Domain POJO representing generic ambari configuration data.
+ */
+public class AmbariConfiguration {
+
+ /**
+ * The type of the configuration, eg.: ldap-configuration
+ */
+ private String type;
+
+ /**
+ * Version tag
+ */
+ private String versionTag;
+
+ /**
+ * Version number
+ */
+ private Integer version;
+
+ /**
+ * Created timestamp
+ */
+ private long createdTs;
+
+ private Set<Map<String, Object>> data = Collections.emptySet();
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public Set<Map<String, Object>> getData() {
+ return data;
+ }
+
+ public void setData(Set<Map<String, Object>> data) {
+ this.data = data;
+ }
+
+ public String getVersionTag() {
+ return versionTag;
+ }
+
+ public void setVersionTag(String versionTag) {
+ this.versionTag = versionTag;
+ }
+
+ public Integer getVersion() {
+ return version;
+ }
+
+ public void setVersion(Integer version) {
+ this.version = version;
+ }
+
+ public long getCreatedTs() {
+ return createdTs;
+ }
+
+ public void setCreatedTs(long createdTs) {
+ this.createdTs = createdTs;
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/176356bd/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/AmbariConfigurationDTO.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/AmbariConfigurationDTO.java b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/AmbariConfigurationDTO.java
deleted file mode 100644
index 1b134fe..0000000
--- a/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/AmbariConfigurationDTO.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.ambari.server.api.services.ldap;
-
-import java.util.Collections;
-import java.util.Map;
-import java.util.Set;
-
-public class AmbariConfigurationDTO {
- private String type;
- private Set<Map<String, Object>> data = Collections.emptySet();
- private String versionTag;
- private Integer version;
- private long createdTs;
-
- public String getType() {
- return type;
- }
-
- public void setType(String type) {
- this.type = type;
- }
-
- public Set<Map<String, Object>> getData() {
- return data;
- }
-
- public void setData(Set<Map<String, Object>> data) {
- this.data = data;
- }
-
- public String getVersionTag() {
- return versionTag;
- }
-
- public void setVersionTag(String versionTag) {
- this.versionTag = versionTag;
- }
-
- public Integer getVersion() {
- return version;
- }
-
- public void setVersion(Integer version) {
- this.version = version;
- }
-
- public long getCreatedTs() {
- return createdTs;
- }
-
- public void setCreatedTs(long createdTs) {
- this.createdTs = createdTs;
- }
-}
http://git-wip-us.apache.org/repos/asf/ambari/blob/176356bd/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapCheckConfigurationRequest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapCheckConfigurationRequest.java b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapCheckConfigurationRequest.java
deleted file mode 100644
index 188f1b9..0000000
--- a/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapCheckConfigurationRequest.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.ambari.server.api.services.ldap;
-
-
-import com.google.gson.annotations.SerializedName;
-
-public class LdapCheckConfigurationRequest implements LdapOperationRequest {
-
- @SerializedName("AmbariConfiguration")
- private AmbariConfigurationDTO ambariConfiguration;
-
- @SerializedName("RequestInfo")
- private LdapRequestInfo requestInfo;
-
- public LdapCheckConfigurationRequest() {
- }
-
-
- public AmbariConfigurationDTO getAmbariConfiguration() {
- return ambariConfiguration;
- }
-
- public void setAmbariConfiguration(AmbariConfigurationDTO ambariConfiguration) {
- this.ambariConfiguration = ambariConfiguration;
- }
-
- public LdapRequestInfo getRequestInfo() {
- return requestInfo;
- }
-
- public void setRequestInfo(LdapRequestInfo requestInfo) {
- this.requestInfo = requestInfo;
- }
-}
http://git-wip-us.apache.org/repos/asf/ambari/blob/176356bd/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigOperation.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigOperation.java b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigOperation.java
new file mode 100644
index 0000000..478d4ff
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigOperation.java
@@ -0,0 +1,43 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.api.services.ldap;
+
+/**
+ * Enumeration for supported operations related to LDAP configuration.
+ */
+public enum LdapConfigOperation {
+ TEST_CONNECTION("test-connection"),
+ TEST_ATTRIBUTES("test-attributes"),
+ DETECT_ATTRIBUTES("detect-attributes");
+
+ private String actionStr;
+
+ LdapConfigOperation(String actionStr) {
+ this.actionStr = actionStr;
+ }
+
+ public static LdapConfigOperation fromAction(String action) {
+ for (LdapConfigOperation val : LdapConfigOperation.values()) {
+ if (val.action().equals(action)) {
+ return val;
+ }
+ }
+ throw new IllegalStateException("Action [ " + action + " ] is not supported");
+ }
+
+ public String action() {
+ return this.actionStr;
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/176356bd/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationRequest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationRequest.java b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationRequest.java
new file mode 100644
index 0000000..2e478c4
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationRequest.java
@@ -0,0 +1,49 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.api.services.ldap;
+
+
+import com.google.gson.annotations.SerializedName;
+
+/**
+ * Request object wrapping information for LDAP configuration related request calls.
+ */
+public class LdapConfigurationRequest {
+
+ @SerializedName("AmbariConfiguration")
+ private AmbariConfiguration ambariConfiguration;
+
+ @SerializedName("RequestInfo")
+ private LdapRequestInfo requestInfo;
+
+ public LdapConfigurationRequest() {
+ }
+
+ public AmbariConfiguration getAmbariConfiguration() {
+ return ambariConfiguration;
+ }
+
+ public void setAmbariConfiguration(AmbariConfiguration ambariConfiguration) {
+ this.ambariConfiguration = ambariConfiguration;
+ }
+
+ public LdapRequestInfo getRequestInfo() {
+ return requestInfo;
+ }
+
+ public void setRequestInfo(LdapRequestInfo requestInfo) {
+ this.requestInfo = requestInfo;
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/176356bd/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationService.java b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationService.java
index 52244bc..fc6bd41 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationService.java
@@ -74,40 +74,13 @@ public class LdapConfigurationService extends AmbariConfigurationService {
@Inject
private static LdapConfigurationFactory ldapConfigurationFactory;
- /**
- * Actions supported by this endpoint
- */
- private enum LdapAction {
- TEST_CONNECTION("test-connection"),
- TEST_ATTRIBUTES("test-attributes"),
- DETECT_ATTRIBUTES("detect-attributes");
-
- private String actionStr;
-
- LdapAction(String actionStr) {
- this.actionStr = actionStr;
- }
-
- public static LdapAction fromAction(String action) {
- for (LdapAction val : LdapAction.values()) {
- if (val.action().equals(action)) {
- return val;
- }
- }
- throw new IllegalStateException("Action [ " + action + " ] is not supported");
- }
-
- public String action() {
- return this.actionStr;
- }
- }
@POST
@ApiIgnore // until documented
@Path("/validate")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
- public Response validateConfiguration(LdapCheckConfigurationRequest ldapCheckConfigurationRequest) {
+ public Response validateConfiguration(LdapConfigurationRequest ldapConfigurationRequest) {
authorize();
@@ -116,12 +89,12 @@ public class LdapConfigurationService extends AmbariConfigurationService {
Result result = new ResultImpl(new ResultStatus(ResultStatus.STATUS.OK));
try {
- validateRequest(ldapCheckConfigurationRequest);
+ validateRequest(ldapConfigurationRequest);
AmbariLdapConfiguration ambariLdapConfiguration = ldapConfigurationFactory.createLdapConfiguration(
- ldapCheckConfigurationRequest.getAmbariConfiguration().getData().iterator().next());
+ ldapConfigurationRequest.getAmbariConfiguration().getData().iterator().next());
- LdapAction action = LdapAction.fromAction(ldapCheckConfigurationRequest.getRequestInfo().getAction());
+ LdapConfigOperation action = LdapConfigOperation.fromAction(ldapConfigurationRequest.getRequestInfo().getAction());
switch (action) {
case TEST_CONNECTION:
@@ -133,7 +106,7 @@ public class LdapConfigurationService extends AmbariConfigurationService {
case TEST_ATTRIBUTES:
LOGGER.info("Testing LDAP attributes ....");
- groups = ldapFacade.checkLdapAttibutes(ldapCheckConfigurationRequest.getRequestInfo().getParameters(), ambariLdapConfiguration);
+ groups = ldapFacade.checkLdapAttibutes(ldapConfigurationRequest.getRequestInfo().getParameters(), ambariLdapConfiguration);
setResult(groups, result);
break;
@@ -161,24 +134,24 @@ public class LdapConfigurationService extends AmbariConfigurationService {
result.getResultTree().addChild(resource, "payload");
}
- private void validateRequest(LdapCheckConfigurationRequest ldapCheckConfigurationRequest) {
+ private void validateRequest(LdapConfigurationRequest ldapConfigurationRequest) {
String errMsg;
- if (null == ldapCheckConfigurationRequest) {
+ if (null == ldapConfigurationRequest) {
errMsg = "No ldap configuraiton request provided";
LOGGER.error(errMsg);
throw new IllegalArgumentException(errMsg);
}
- if (null == ldapCheckConfigurationRequest.getRequestInfo()) {
- errMsg = String.format("No request information provided. Request: [%s]", ldapCheckConfigurationRequest);
+ if (null == ldapConfigurationRequest.getRequestInfo()) {
+ errMsg = String.format("No request information provided. Request: [%s]", ldapConfigurationRequest);
LOGGER.error(errMsg);
throw new IllegalArgumentException(errMsg);
}
- if (null == ldapCheckConfigurationRequest.getAmbariConfiguration()
- || ldapCheckConfigurationRequest.getAmbariConfiguration().getData().size() != 1) {
- errMsg = String.format("No / Invalid configuration data provided. Request: [%s]", ldapCheckConfigurationRequest);
+ if (null == ldapConfigurationRequest.getAmbariConfiguration()
+ || ldapConfigurationRequest.getAmbariConfiguration().getData().size() != 1) {
+ errMsg = String.format("No / Invalid configuration data provided. Request: [%s]", ldapConfigurationRequest);
LOGGER.error(errMsg);
throw new IllegalArgumentException(errMsg);
}
@@ -202,7 +175,7 @@ public class LdapConfigurationService extends AmbariConfigurationService {
}
- Set<RoleAuthorization> requiredAuthorizations() {
+ private Set<RoleAuthorization> requiredAuthorizations() {
return Sets.newHashSet(RoleAuthorization.AMBARI_MANAGE_CONFIGURATION);
}
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/176356bd/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapOperationRequest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapOperationRequest.java b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapOperationRequest.java
deleted file mode 100644
index 06f6c40..0000000
--- a/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapOperationRequest.java
+++ /dev/null
@@ -1,18 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.ambari.server.api.services.ldap;
-
-public interface LdapOperationRequest {
-}
http://git-wip-us.apache.org/repos/asf/ambari/blob/176356bd/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationService.java
new file mode 100644
index 0000000..69a641f
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationService.java
@@ -0,0 +1,60 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap;
+
+import java.util.Set;
+
+import org.apache.ambari.server.AmbariException;
+import org.apache.ambari.server.ldap.service.AmbariLdapException;
+import org.apache.directory.ldap.client.api.LdapConnection;
+
+/**
+ * Collection of operations for validating ldap configuration.
+ * It's intended to decouple implementations using different libraries.
+ */
+public interface LdapConfigurationService {
+
+ /**
+ * Tests the connection based on the provided configuration.
+ *
+ * @param ldapConnection connection instance
+ * @param configuration the ambari ldap configuration instance
+ * @throws AmbariLdapException if the connection is not possible
+ */
+ void checkConnection(LdapConnection ldapConnection, AmbariLdapConfiguration configuration) throws AmbariLdapException;
+
+
+ /**
+ * Implements LDAP user related configuration settings validation logic.
+ * Implementers communicate with the LDAP server (search, bind) to validate attributes in the provided configuration
+ * instance
+ *
+ * @param ldapConnection connection instance used to connect to the LDAP server
+ * @param testUserName the test username
+ * @param testPassword the test password
+ * @param configuration the available ldap configuration
+ * @return The DN of the found user entry
+ * @throws AmbariException if the connection couldn't be estabilisheds
+ */
+ String checkUserAttributes(LdapConnection ldapConnection, String testUserName, String testPassword, AmbariLdapConfiguration configuration) throws AmbariLdapException;
+
+ /**
+ * Checks whether the group related LDAP attributes in the configuration are correct.
+ *
+ * @throws AmbariException if the attributes are not valid
+ */
+ Set<String> checkGroupAttributes(LdapConnection ldapConnection, String userDn, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException;
+
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/176356bd/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationValidatorService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationValidatorService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationValidatorService.java
deleted file mode 100644
index 7efa3b7..0000000
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationValidatorService.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.ambari.server.ldap;
-
-import java.util.Set;
-
-import org.apache.ambari.server.AmbariException;
-import org.apache.ambari.server.ldap.service.AmbariLdapException;
-import org.apache.directory.ldap.client.api.LdapConnection;
-
-/**
- * Collection of operations for validating ldap configuration.
- * It's intended to decouple implementations using different libraries.
- */
-public interface LdapConfigurationValidatorService {
-
- /**
- * Tests the connection based on the provided configuration.
- *
- * @param ldapConnection connection instance
- * @param configuration the ambari ldap configuration instance
- * @throws AmbariLdapException if the connection is not possible
- */
- void checkConnection(LdapConnection ldapConnection, AmbariLdapConfiguration configuration) throws AmbariLdapException;
-
-
- /**
- * Implements LDAP user related configuration settings validation logic.
- * Implementers communicate with the LDAP server (search, bind) to validate attributes in the provided configuration
- * instance
- *
- * @param ldapConnection connection instance used to connect to the LDAP server
- * @param testUserName the test username
- * @param testPassword the test password
- * @param configuration the available ldap configuration
- * @return The DN of the found user entry
- * @throws AmbariException if the connection couldn't be estabilisheds
- */
- String checkUserAttributes(LdapConnection ldapConnection, String testUserName, String testPassword, AmbariLdapConfiguration configuration) throws AmbariLdapException;
-
- /**
- * Checks whether the group related LDAP attributes in the configuration are correct.
- *
- * @throws AmbariException if the attributes are not valid
- */
- Set<String> checkGroupAttributes(LdapConnection ldapConnection, String userDn, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException;
-
-}
http://git-wip-us.apache.org/repos/asf/ambari/blob/176356bd/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
index a4ad2ee..3ae4587 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
@@ -18,7 +18,7 @@ package org.apache.ambari.server.ldap;
import org.apache.ambari.server.ldap.service.AmbariLdapFacade;
import org.apache.ambari.server.ldap.service.LdapConnectionService;
import org.apache.ambari.server.ldap.service.LdapFacade;
-import org.apache.ambari.server.ldap.service.ads.DefaultLdapConfigurationValidatorService;
+import org.apache.ambari.server.ldap.service.ads.DefaultLdapConfigurationService;
import org.apache.ambari.server.ldap.service.ads.DefaultLdapConnectionService;
import com.google.inject.AbstractModule;
@@ -32,7 +32,7 @@ public class LdapModule extends AbstractModule {
@Override
protected void configure() {
bind(LdapFacade.class).to(AmbariLdapFacade.class);
- bind(LdapConfigurationValidatorService.class).to(DefaultLdapConfigurationValidatorService.class);
+ bind(LdapConfigurationService.class).to(DefaultLdapConfigurationService.class);
bind(LdapConnectionService.class).to(DefaultLdapConnectionService.class);
install(new FactoryModuleBuilder().build(LdapConfigurationFactory.class));
http://git-wip-us.apache.org/repos/asf/ambari/blob/176356bd/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
index eec47ce..683ed43 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
@@ -22,7 +22,7 @@ import javax.inject.Inject;
import javax.inject.Singleton;
import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
-import org.apache.ambari.server.ldap.LdapConfigurationValidatorService;
+import org.apache.ambari.server.ldap.LdapConfigurationService;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -49,7 +49,7 @@ public class AmbariLdapFacade implements LdapFacade {
}
@Inject
- private LdapConfigurationValidatorService ldapConfigurationValidatorService;
+ private LdapConfigurationService ldapConfigurationService;
@Inject
private LdapConnectionService ldapConnectionService;
@@ -63,7 +63,7 @@ public class AmbariLdapFacade implements LdapFacade {
try {
LOGGER.info("Validating LDAP connection related configuration based on: {}", ambariLdapConfiguration);
LdapConnection connection = ldapConnectionService.createLdapConnection(ambariLdapConfiguration);
- ldapConfigurationValidatorService.checkConnection(connection, ambariLdapConfiguration);
+ ldapConfigurationService.checkConnection(connection, ambariLdapConfiguration);
} catch (AmbariLdapException e) {
LOGGER.error("Validating LDAP connection configuration failed", e);
throw e;
@@ -90,10 +90,10 @@ public class AmbariLdapFacade implements LdapFacade {
LdapConnection ldapConnection = ldapConnectionService.createLdapConnection(ldapConfiguration);
LOGGER.info("Testing LDAP user attributes with test user: {}", userName);
- String userDn = ldapConfigurationValidatorService.checkUserAttributes(ldapConnection, userName, testUserPass, ldapConfiguration);
+ String userDn = ldapConfigurationService.checkUserAttributes(ldapConnection, userName, testUserPass, ldapConfiguration);
LOGGER.info("Testing LDAP group attributes with test user dn: {}", userDn);
- Set<String> groups = ldapConfigurationValidatorService.checkGroupAttributes(ldapConnection, userDn, ldapConfiguration);
+ Set<String> groups = ldapConfigurationService.checkGroupAttributes(ldapConnection, userDn, ldapConfiguration);
return groups;
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/176356bd/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
new file mode 100644
index 0000000..abc9201
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
@@ -0,0 +1,243 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service.ads;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Set;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+import org.apache.ambari.server.AmbariException;
+import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.LdapConfigurationService;
+import org.apache.ambari.server.ldap.service.AmbariLdapException;
+import org.apache.ambari.server.ldap.service.LdapConnectionService;
+import org.apache.directory.api.ldap.codec.decorators.SearchResultEntryDecorator;
+import org.apache.directory.api.ldap.model.constants.SchemaConstants;
+import org.apache.directory.api.ldap.model.cursor.EntryCursor;
+import org.apache.directory.api.ldap.model.cursor.SearchCursor;
+import org.apache.directory.api.ldap.model.entry.Entry;
+import org.apache.directory.api.ldap.model.exception.LdapException;
+import org.apache.directory.api.ldap.model.message.Response;
+import org.apache.directory.api.ldap.model.message.SearchRequest;
+import org.apache.directory.api.ldap.model.message.SearchRequestImpl;
+import org.apache.directory.api.ldap.model.message.SearchScope;
+import org.apache.directory.api.ldap.model.name.Dn;
+import org.apache.directory.ldap.client.api.LdapConnection;
+import org.apache.directory.ldap.client.api.search.FilterBuilder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+
+/**
+ * Implementation of the validation logic using the Apache Directory API.
+ */
+@Singleton
+public class DefaultLdapConfigurationService implements LdapConfigurationService {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(DefaultLdapConfigurationService.class);
+
+ @Inject
+ private LdapConnectionService ldapConnectionService;
+
+ /**
+ * Facilitating the instantiation
+ */
+ @Inject
+ public DefaultLdapConfigurationService() {
+ }
+
+ @Override
+ public void checkConnection(LdapConnection ldapConnection, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
+ try {
+ bind(ambariLdapConfiguration, ldapConnection);
+ } catch (LdapException e) {
+ LOGGER.error("Could not connect to the LDAP server", e);
+ throw new AmbariLdapException(e);
+ }
+ }
+
+
+ /**
+ * Checks the user attributes provided in the configuration instance by issuing a search for a (known) test user in the LDAP.
+ * Attributes are considered correct if there is at least one entry found.
+ *
+ * Invalid attributes are signaled by throwing an exception.
+ *
+ * @param testUserName the test username
+ * @param testPassword the test password
+ * @param ambariLdapConfiguration configuration instance holding ldap configuration details
+ * @return the DN of the test user
+ * @throws AmbariException if the attributes are not valid or any errors occurs
+ */
+ @Override
+ public String checkUserAttributes(LdapConnection ldapConnection, String testUserName, String testPassword, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
+ SearchCursor searchCursor = null;
+ String userDn = null;
+ try {
+ LOGGER.info("Checking user attributes for user {} r ...", testUserName);
+
+ // bind anonimously or with manager data
+ bind(ambariLdapConfiguration, ldapConnection);
+
+ // set up a filter based on the provided attributes
+ String filter = FilterBuilder.and(
+ FilterBuilder.equal(SchemaConstants.OBJECT_CLASS_AT, ambariLdapConfiguration.userObjectClass()),
+ FilterBuilder.equal(ambariLdapConfiguration.userNameAttribute(), testUserName))
+ .toString();
+
+ LOGGER.info("Searching for the user: {} using the search filter: {}", testUserName, filter);
+ EntryCursor entryCursor = ldapConnection.search(new Dn(ambariLdapConfiguration.userSearchBase()), filter, SearchScope.SUBTREE);
+
+ // collecting search result entries
+ List<Entry> users = Lists.newArrayList();
+ for (Entry entry : entryCursor) {
+ users.add(entry);
+ userDn = entry.getDn().getNormName();
+ }
+
+ // there should be at least one user found
+ if (users.isEmpty()) {
+ String msg = String.format("There are no users found using the filter: [ %s ]. Try changing the attribute values", filter);
+ LOGGER.error(msg);
+ throw new Exception(msg);
+ }
+
+ LOGGER.info("Attibute validation succeeded. Filter: {}", filter);
+
+ } catch (Exception e) {
+
+ LOGGER.error("User attributes validation failed.", e);
+ throw new AmbariLdapException(e.getMessage(), e);
+
+ } finally {
+ closeResources(ldapConnection, searchCursor);
+ }
+ return userDn;
+ }
+
+
+ @Override
+ public Set<String> checkGroupAttributes(LdapConnection ldapConnection, String userDn, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
+ SearchCursor searchCursor = null;
+ Set<Response> groupResponses = Sets.newHashSet();
+
+ try {
+ LOGGER.info("Checking group attributes for user dn {} ...", userDn);
+
+ bind(ambariLdapConfiguration, ldapConnection);
+
+ // set up a filter based on the provided attributes
+ String filter = FilterBuilder.and(
+ FilterBuilder.equal(SchemaConstants.OBJECT_CLASS_AT, ambariLdapConfiguration.groupObjectClass()),
+ FilterBuilder.equal(ambariLdapConfiguration.groupMemberAttribute(), userDn)
+ ).toString();
+
+ LOGGER.info("Searching for the groups the user dn: {} is member of using the search filter: {}", userDn, filter);
+
+ // assemble a search request
+ SearchRequest searchRequest = new SearchRequestImpl();
+ searchRequest.setFilter(filter);
+ searchRequest.setBase(new Dn(ambariLdapConfiguration.groupSearchBase()));
+ searchRequest.setScope(SearchScope.SUBTREE);
+ searchRequest.addAttributes(ambariLdapConfiguration.groupMemberAttribute(), ambariLdapConfiguration.groupNameAttribute());
+
+ // perform the search
+ searchCursor = ldapConnection.search(searchRequest);
+
+ for (Response response : searchCursor) {
+ groupResponses.add(response);
+ }
+
+ } catch (Exception e) {
+
+ LOGGER.error("User attributes validation failed.", e);
+ throw new AmbariLdapException(e.getMessage(), e);
+
+ } finally {
+ closeResources(ldapConnection, searchCursor);
+ }
+
+ return processGroupResults(groupResponses, ambariLdapConfiguration);
+ }
+
+ /**
+ * Binds to the LDAP server (anonimously or wit manager credentials)
+ *
+ * @param ambariLdapConfiguration configuration instance
+ * @param connection connection instance
+ * @throws LdapException if the bind operation fails
+ */
+ private void bind(AmbariLdapConfiguration ambariLdapConfiguration, LdapConnection connection) throws LdapException {
+ LOGGER.info("Connecting to LDAP ....");
+ if (!ambariLdapConfiguration.bindAnonimously()) {
+ LOGGER.debug("Anonimous binding not supported, binding with the manager detailas...");
+ connection.bind(ambariLdapConfiguration.managerDn(), ambariLdapConfiguration.managerPassword());
+ } else {
+ LOGGER.debug("Binding anonimously ...");
+ connection.bind();
+ }
+
+ if (!connection.isConnected()) {
+ LOGGER.error("Not connected to the LDAP server. Connection instance: {}", connection);
+ throw new IllegalStateException("The connection to the LDAP server is not alive");
+ }
+ LOGGER.info("Connected to LDAP.");
+ }
+
+
+ /**
+ * Extracts meaningful values from the search result.
+ *
+ * @param groupResponses the result entries returned by the search
+ * @param ambariLdapConfiguration holds the keys of the meaningful attributes
+ * @return a set with the group names the test user belongs to
+ */
+ private Set<String> processGroupResults(Set<Response> groupResponses, AmbariLdapConfiguration ambariLdapConfiguration) {
+ Set<String> groupStrSet = Sets.newHashSet();
+ for (Response response : groupResponses) {
+ Entry entry = ((SearchResultEntryDecorator) response).getEntry();
+ groupStrSet.add(entry.get(ambariLdapConfiguration.groupNameAttribute()).get().getString());
+ }
+
+ LOGGER.debug("Extracted group names from group search responses: {}", groupStrSet);
+ return groupStrSet;
+ }
+
+ private void closeResources(LdapConnection connection, SearchCursor searchCursor) {
+ LOGGER.debug("Housekeeping: closing the connection and the search cursor ...");
+
+ if (null != searchCursor) {
+ // this method is idempotent
+ searchCursor.close();
+ }
+
+ if (null != connection) {
+ try {
+ connection.close();
+ } catch (IOException e) {
+ LOGGER.error("Exception occurred while closing the connection", e);
+ }
+ }
+ }
+
+}
+
+
+
http://git-wip-us.apache.org/repos/asf/ambari/blob/176356bd/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationValidatorService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationValidatorService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationValidatorService.java
deleted file mode 100644
index 040983a..0000000
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationValidatorService.java
+++ /dev/null
@@ -1,243 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.ambari.server.ldap.service.ads;
-
-import java.io.IOException;
-import java.util.List;
-import java.util.Set;
-
-import javax.inject.Inject;
-import javax.inject.Singleton;
-
-import org.apache.ambari.server.AmbariException;
-import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
-import org.apache.ambari.server.ldap.LdapConfigurationValidatorService;
-import org.apache.ambari.server.ldap.service.AmbariLdapException;
-import org.apache.ambari.server.ldap.service.LdapConnectionService;
-import org.apache.directory.api.ldap.codec.decorators.SearchResultEntryDecorator;
-import org.apache.directory.api.ldap.model.constants.SchemaConstants;
-import org.apache.directory.api.ldap.model.cursor.EntryCursor;
-import org.apache.directory.api.ldap.model.cursor.SearchCursor;
-import org.apache.directory.api.ldap.model.entry.Entry;
-import org.apache.directory.api.ldap.model.exception.LdapException;
-import org.apache.directory.api.ldap.model.message.Response;
-import org.apache.directory.api.ldap.model.message.SearchRequest;
-import org.apache.directory.api.ldap.model.message.SearchRequestImpl;
-import org.apache.directory.api.ldap.model.message.SearchScope;
-import org.apache.directory.api.ldap.model.name.Dn;
-import org.apache.directory.ldap.client.api.LdapConnection;
-import org.apache.directory.ldap.client.api.search.FilterBuilder;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.Lists;
-import com.google.common.collect.Sets;
-
-/**
- * Implementation of the validation logic using the Apache Directory API.
- */
-@Singleton
-public class DefaultLdapConfigurationValidatorService implements LdapConfigurationValidatorService {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(DefaultLdapConfigurationValidatorService.class);
-
- @Inject
- private LdapConnectionService ldapConnectionService;
-
- /**
- * Facilitating the instantiation
- */
- @Inject
- public DefaultLdapConfigurationValidatorService() {
- }
-
- @Override
- public void checkConnection(LdapConnection ldapConnection, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
- try {
- bind(ambariLdapConfiguration, ldapConnection);
- } catch (LdapException e) {
- LOGGER.error("Could not connect to the LDAP server", e);
- throw new AmbariLdapException(e);
- }
- }
-
-
- /**
- * Checks the user attributes provided in the configuration instance by issuing a search for a (known) test user in the LDAP.
- * Attributes are considered correct if there is at least one entry found.
- *
- * Invalid attributes are signaled by throwing an exception.
- *
- * @param testUserName the test username
- * @param testPassword the test password
- * @param ambariLdapConfiguration configuration instance holding ldap configuration details
- * @return the DN of the test user
- * @throws AmbariException if the attributes are not valid or any errors occurs
- */
- @Override
- public String checkUserAttributes(LdapConnection ldapConnection, String testUserName, String testPassword, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
- SearchCursor searchCursor = null;
- String userDn = null;
- try {
- LOGGER.info("Checking user attributes for user {} r ...", testUserName);
-
- // bind anonimously or with manager data
- bind(ambariLdapConfiguration, ldapConnection);
-
- // set up a filter based on the provided attributes
- String filter = FilterBuilder.and(
- FilterBuilder.equal(SchemaConstants.OBJECT_CLASS_AT, ambariLdapConfiguration.userObjectClass()),
- FilterBuilder.equal(ambariLdapConfiguration.userNameAttribute(), testUserName))
- .toString();
-
- LOGGER.info("Searching for the user: {} using the search filter: {}", testUserName, filter);
- EntryCursor entryCursor = ldapConnection.search(new Dn(ambariLdapConfiguration.userSearchBase()), filter, SearchScope.SUBTREE);
-
- // collecting search result entries
- List<Entry> users = Lists.newArrayList();
- for (Entry entry : entryCursor) {
- users.add(entry);
- userDn = entry.getDn().getNormName();
- }
-
- // there should be at least one user found
- if (users.isEmpty()) {
- String msg = String.format("There are no users found using the filter: [ %s ]. Try changing the attribute values", filter);
- LOGGER.error(msg);
- throw new Exception(msg);
- }
-
- LOGGER.info("Attibute validation succeeded. Filter: {}", filter);
-
- } catch (Exception e) {
-
- LOGGER.error("User attributes validation failed.", e);
- throw new AmbariLdapException(e.getMessage(), e);
-
- } finally {
- closeResources(ldapConnection, searchCursor);
- }
- return userDn;
- }
-
-
- @Override
- public Set<String> checkGroupAttributes(LdapConnection ldapConnection, String userDn, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
- SearchCursor searchCursor = null;
- Set<Response> groupResponses = Sets.newHashSet();
-
- try {
- LOGGER.info("Checking group attributes for user dn {} ...", userDn);
-
- bind(ambariLdapConfiguration, ldapConnection);
-
- // set up a filter based on the provided attributes
- String filter = FilterBuilder.and(
- FilterBuilder.equal(SchemaConstants.OBJECT_CLASS_AT, ambariLdapConfiguration.groupObjectClass()),
- FilterBuilder.equal(ambariLdapConfiguration.groupMemberAttribute(), userDn)
- ).toString();
-
- LOGGER.info("Searching for the groups the user dn: {} is member of using the search filter: {}", userDn, filter);
-
- // assemble a search request
- SearchRequest searchRequest = new SearchRequestImpl();
- searchRequest.setFilter(filter);
- searchRequest.setBase(new Dn(ambariLdapConfiguration.groupSearchBase()));
- searchRequest.setScope(SearchScope.SUBTREE);
- searchRequest.addAttributes(ambariLdapConfiguration.groupMemberAttribute(), ambariLdapConfiguration.groupNameAttribute());
-
- // perform the search
- searchCursor = ldapConnection.search(searchRequest);
-
- for (Response response : searchCursor) {
- groupResponses.add(response);
- }
-
- } catch (Exception e) {
-
- LOGGER.error("User attributes validation failed.", e);
- throw new AmbariLdapException(e.getMessage(), e);
-
- } finally {
- closeResources(ldapConnection, searchCursor);
- }
-
- return processGroupResults(groupResponses, ambariLdapConfiguration);
- }
-
- /**
- * Binds to the LDAP server (anonimously or wit manager credentials)
- *
- * @param ambariLdapConfiguration configuration instance
- * @param connection connection instance
- * @throws LdapException if the bind operation fails
- */
- private void bind(AmbariLdapConfiguration ambariLdapConfiguration, LdapConnection connection) throws LdapException {
- LOGGER.info("Connecting to LDAP ....");
- if (!ambariLdapConfiguration.bindAnonimously()) {
- LOGGER.debug("Anonimous binding not supported, binding with the manager detailas...");
- connection.bind(ambariLdapConfiguration.managerDn(), ambariLdapConfiguration.managerPassword());
- } else {
- LOGGER.debug("Binding anonimously ...");
- connection.bind();
- }
-
- if (!connection.isConnected()) {
- LOGGER.error("Not connected to the LDAP server. Connection instance: {}", connection);
- throw new IllegalStateException("The connection to the LDAP server is not alive");
- }
- LOGGER.info("Connected to LDAP.");
- }
-
-
- /**
- * Extracts meaningful values from the search result.
- *
- * @param groupResponses the result entries returned by the search
- * @param ambariLdapConfiguration holds the keys of the meaningful attributes
- * @return a set with the group names the test user belongs to
- */
- private Set<String> processGroupResults(Set<Response> groupResponses, AmbariLdapConfiguration ambariLdapConfiguration) {
- Set<String> groupStrSet = Sets.newHashSet();
- for (Response response : groupResponses) {
- Entry entry = ((SearchResultEntryDecorator) response).getEntry();
- groupStrSet.add(entry.get(ambariLdapConfiguration.groupNameAttribute()).get().getString());
- }
-
- LOGGER.debug("Extracted group names from group search responses: {}", groupStrSet);
- return groupStrSet;
- }
-
- private void closeResources(LdapConnection connection, SearchCursor searchCursor) {
- LOGGER.debug("Housekeeping: closing the connection and the search cursor ...");
-
- if (null != searchCursor) {
- // this method is idempotent
- searchCursor.close();
- }
-
- if (null != connection) {
- try {
- connection.close();
- } catch (IOException e) {
- LOGGER.error("Exception occurred while closing the connection", e);
- }
- }
- }
-
-}
-
-
-
http://git-wip-us.apache.org/repos/asf/ambari/blob/176356bd/ambari-server/src/test/java/org/apache/ambari/server/api/services/ldap/LDAPServiceTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/api/services/ldap/LDAPServiceTest.java b/ambari-server/src/test/java/org/apache/ambari/server/api/services/ldap/LDAPServiceTest.java
index f20cd1f..5e8eac6 100644
--- a/ambari-server/src/test/java/org/apache/ambari/server/api/services/ldap/LDAPServiceTest.java
+++ b/ambari-server/src/test/java/org/apache/ambari/server/api/services/ldap/LDAPServiceTest.java
@@ -46,11 +46,11 @@ public class LDAPServiceTest {
// WHEN
- LdapCheckConfigurationRequest ldapCheckConfigurationRequest = gsonJsonProvider.fromJson(JSON_STRING, LdapCheckConfigurationRequest.class);
- // LdapCheckConfigurationRequest ldapCheckConfigurationRequest = objectMapper.readValue(JSON_STRING, LdapCheckConfigurationRequest.class);
+ LdapConfigurationRequest ldapConfigurationRequest = gsonJsonProvider.fromJson(JSON_STRING, LdapConfigurationRequest.class);
+ // LdapConfigurationRequest ldapConfigurationRequest = objectMapper.readValue(JSON_STRING, LdapConfigurationRequest.class);
// THEN
- Assert.assertNotNull(ldapCheckConfigurationRequest);
+ Assert.assertNotNull(ldapConfigurationRequest);
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/176356bd/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java
new file mode 100644
index 0000000..2b7448e
--- /dev/null
+++ b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java
@@ -0,0 +1,113 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service.ads;
+
+import static org.junit.Assert.assertNotNull;
+
+import java.util.Map;
+
+import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.LdapConfigurationService;
+import org.apache.ambari.server.ldap.service.LdapConnectionService;
+import org.apache.directory.api.ldap.model.constants.SchemaConstants;
+import org.apache.directory.api.ldap.model.cursor.EntryCursor;
+import org.apache.directory.api.ldap.model.entry.Entry;
+import org.apache.directory.api.ldap.model.message.SearchScope;
+import org.apache.directory.ldap.client.api.LdapConnection;
+import org.apache.directory.ldap.client.api.LdapConnectionConfig;
+import org.apache.directory.ldap.client.api.LdapNetworkConnection;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.collect.Maps;
+
+public class DefaultLdapConfigurationServiceTest {
+ private static final Logger LOGGER = LoggerFactory.getLogger(DefaultLdapConfigurationService.class);
+ private static final String TEST_USER = "einstein";
+
+ LdapConfigurationService ldapConfigurationService = new DefaultLdapConfigurationService();
+
+
+ @Test
+ public void testCheckAttributes() throws Exception {
+
+ // WHEN
+ LdapConnectionConfig config = new LdapConnectionConfig();
+ config.setLdapHost("localhost");
+ config.setLdapPort(389);
+ LdapConnection connection = new LdapNetworkConnection(config);
+
+ // THEN
+ connection.anonymousBind();
+
+
+ EntryCursor cursor = connection.search("dc=dev,dc=local", "(objectclass=*)", SearchScope.ONELEVEL);
+
+ for (Entry entry : cursor) {
+ assertNotNull(entry);
+ System.out.println(entry);
+ }
+
+ cursor.close();
+
+ }
+
+ @Test
+ public void testCheckUserAttributes() throws Exception {
+ // GIVEN
+ Map<String, Object> ldapPropsMap = Maps.newHashMap();
+
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.BIND_ANONIMOUSLY.propertyName(), "true");
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.LDAP_SERVER_HOST.propertyName(), "ldap.forumsys.com");
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.LDAP_SERVER_PORT.propertyName(), "389");
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.BASE_DN.propertyName(), "dc=example,dc=com");
+
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.USER_OBJECT_CLASS.propertyName(), SchemaConstants.PERSON_OC);
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.USER_NAME_ATTRIBUTE.propertyName(), SchemaConstants.UID_AT);
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.USER_SEARCH_BASE.propertyName(), "dc=example,dc=com");
+
+
+ AmbariLdapConfiguration ambariLdapConfiguration = new AmbariLdapConfiguration(ldapPropsMap);
+ LdapConnectionService connectionService = new DefaultLdapConnectionService();
+ LdapNetworkConnection ldapConnection = connectionService.createLdapConnection(ambariLdapConfiguration);
+
+ ldapConfigurationService.checkUserAttributes(ldapConnection, "einstein", "", ambariLdapConfiguration);
+ }
+
+ @Test
+ public void testRetrieveGorupsForuser() throws Exception {
+ // GIVEN
+ Map<String, Object> ldapPropsMap = Maps.newHashMap();
+
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.BIND_ANONIMOUSLY.propertyName(), "true");
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.LDAP_SERVER_HOST.propertyName(), "ldap.forumsys.com");
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.LDAP_SERVER_PORT.propertyName(), "389");
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.BASE_DN.propertyName(), "dc=example,dc=com");
+
+
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.GROUP_OBJECT_CLASS.propertyName(), SchemaConstants.GROUP_OF_UNIQUE_NAMES_OC);
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.GROUP_NAME_ATTRIBUTE.propertyName(), SchemaConstants.CN_AT);
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.GROUP_MEMBER_ATTRIBUTE.propertyName(), SchemaConstants.UNIQUE_MEMBER_AT);
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.GROUP_SEARCH_BASE.propertyName(), "dc=example,dc=com");
+
+
+ AmbariLdapConfiguration ambariLdapConfiguration = new AmbariLdapConfiguration(ldapPropsMap);
+ LdapConnectionService connectionService = new DefaultLdapConnectionService();
+ LdapNetworkConnection ldapConnection = connectionService.createLdapConnection(ambariLdapConfiguration);
+
+ ldapConfigurationService.checkGroupAttributes(ldapConnection, "uid=einstein,dc=example,dc=com", ambariLdapConfiguration);
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/ambari/blob/176356bd/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationValidatorServiceTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationValidatorServiceTest.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationValidatorServiceTest.java
deleted file mode 100644
index 1c7f75d..0000000
--- a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationValidatorServiceTest.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.ambari.server.ldap.service.ads;
-
-import static org.junit.Assert.assertNotNull;
-
-import java.util.Map;
-
-import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
-import org.apache.ambari.server.ldap.LdapConfigurationValidatorService;
-import org.apache.ambari.server.ldap.service.LdapConnectionService;
-import org.apache.directory.api.ldap.model.constants.SchemaConstants;
-import org.apache.directory.api.ldap.model.cursor.EntryCursor;
-import org.apache.directory.api.ldap.model.entry.Entry;
-import org.apache.directory.api.ldap.model.message.SearchScope;
-import org.apache.directory.ldap.client.api.LdapConnection;
-import org.apache.directory.ldap.client.api.LdapConnectionConfig;
-import org.apache.directory.ldap.client.api.LdapNetworkConnection;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.Maps;
-
-public class DefaultLdapConfigurationValidatorServiceTest {
- private static final Logger LOGGER = LoggerFactory.getLogger(DefaultLdapConfigurationValidatorService.class);
- private static final String TEST_USER = "einstein";
-
- LdapConfigurationValidatorService ldapConfigurationValidatorService = new DefaultLdapConfigurationValidatorService();
-
-
- @Test
- public void testCheckAttributes() throws Exception {
-
- // WHEN
- LdapConnectionConfig config = new LdapConnectionConfig();
- config.setLdapHost("localhost");
- config.setLdapPort(389);
- LdapConnection connection = new LdapNetworkConnection(config);
-
- // THEN
- connection.anonymousBind();
-
-
- EntryCursor cursor = connection.search("dc=dev,dc=local", "(objectclass=*)", SearchScope.ONELEVEL);
-
- for (Entry entry : cursor) {
- assertNotNull(entry);
- System.out.println(entry);
- }
-
- cursor.close();
-
- }
-
- @Test
- public void testCheckUserAttributes() throws Exception {
- // GIVEN
- Map<String, Object> ldapPropsMap = Maps.newHashMap();
-
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.BIND_ANONIMOUSLY.propertyName(), "true");
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.LDAP_SERVER_HOST.propertyName(), "ldap.forumsys.com");
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.LDAP_SERVER_PORT.propertyName(), "389");
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.BASE_DN.propertyName(), "dc=example,dc=com");
-
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.USER_OBJECT_CLASS.propertyName(), SchemaConstants.PERSON_OC);
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.USER_NAME_ATTRIBUTE.propertyName(), SchemaConstants.UID_AT);
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.USER_SEARCH_BASE.propertyName(), "dc=example,dc=com");
-
-
- AmbariLdapConfiguration ambariLdapConfiguration = new AmbariLdapConfiguration(ldapPropsMap);
- LdapConnectionService connectionService = new DefaultLdapConnectionService();
- LdapNetworkConnection ldapConnection = connectionService.createLdapConnection(ambariLdapConfiguration);
-
- ldapConfigurationValidatorService.checkUserAttributes(ldapConnection, "einstein", "", ambariLdapConfiguration);
- }
-
- @Test
- public void testRetrieveGorupsForuser() throws Exception {
- // GIVEN
- Map<String, Object> ldapPropsMap = Maps.newHashMap();
-
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.BIND_ANONIMOUSLY.propertyName(), "true");
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.LDAP_SERVER_HOST.propertyName(), "ldap.forumsys.com");
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.LDAP_SERVER_PORT.propertyName(), "389");
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.BASE_DN.propertyName(), "dc=example,dc=com");
-
-
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.GROUP_OBJECT_CLASS.propertyName(), SchemaConstants.GROUP_OF_UNIQUE_NAMES_OC);
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.GROUP_NAME_ATTRIBUTE.propertyName(), SchemaConstants.CN_AT);
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.GROUP_MEMBER_ATTRIBUTE.propertyName(), SchemaConstants.UNIQUE_MEMBER_AT);
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.GROUP_SEARCH_BASE.propertyName(), "dc=example,dc=com");
-
-
- AmbariLdapConfiguration ambariLdapConfiguration = new AmbariLdapConfiguration(ldapPropsMap);
- LdapConnectionService connectionService = new DefaultLdapConnectionService();
- LdapNetworkConnection ldapConnection = connectionService.createLdapConnection(ambariLdapConfiguration);
-
- ldapConfigurationValidatorService.checkGroupAttributes(ldapConnection, "uid=einstein,dc=example,dc=com", ambariLdapConfiguration);
- }
-}
\ No newline at end of file
[30/33] ambari git commit: AMBARI-21307 Fixed failing unit tests (in
most cases the new guice module was needed)
Posted by lp...@apache.org.
AMBARI-21307 Fixed failing unit tests (in most cases the new guice module was needed)
Project: http://git-wip-us.apache.org/repos/asf/ambari/repo
Commit: http://git-wip-us.apache.org/repos/asf/ambari/commit/36a49d17
Tree: http://git-wip-us.apache.org/repos/asf/ambari/tree/36a49d17
Diff: http://git-wip-us.apache.org/repos/asf/ambari/diff/36a49d17
Branch: refs/heads/feature-branch-AMBARI-21307
Commit: 36a49d17841db2fc46ab683d5d5928d6d7b54044
Parents: 2f059df
Author: lpuskas <lp...@apache.org>
Authored: Thu Oct 12 19:25:24 2017 +0200
Committer: lpuskas <lp...@apache.org>
Committed: Fri Oct 13 17:20:53 2017 +0200
----------------------------------------------------------------------
.../main/resources/Ambari-DDL-Derby-CREATE.sql | 2 +-
.../main/resources/Ambari-DDL-MySQL-CREATE.sql | 2 +-
.../main/resources/Ambari-DDL-Oracle-CREATE.sql | 2 +-
.../resources/Ambari-DDL-Postgres-CREATE.sql | 2 +-
.../resources/Ambari-DDL-SQLAnywhere-CREATE.sql | 2 +-
.../resources/Ambari-DDL-SQLServer-CREATE.sql | 2 +-
.../api/services/ldap/LDAPServiceTest.java | 85 --------------------
.../server/checks/UpgradeCheckOrderTest.java | 3 +-
...AmbariConfigurationResourceProviderTest.java | 24 +++++-
.../server/ldap/LdapModuleFunctionalTest.java | 4 +-
.../notifications/DispatchFactoryTest.java | 3 +-
.../server/orm/InMemoryDefaultTestModule.java | 2 +
.../ambari/server/orm/JdbcPropertyTest.java | 5 +-
...uthenticationProviderForDNWithSpaceTest.java | 35 ++++----
.../AmbariLdapAuthenticationProviderTest.java | 3 +-
.../AmbariLocalUserProviderTest.java | 3 +-
.../authorization/LdapServerPropertiesTest.java | 5 +-
17 files changed, 65 insertions(+), 119 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/ambari/blob/36a49d17/ambari-server/src/main/resources/Ambari-DDL-Derby-CREATE.sql
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/resources/Ambari-DDL-Derby-CREATE.sql b/ambari-server/src/main/resources/Ambari-DDL-Derby-CREATE.sql
index cebd33e..20d64de 100644
--- a/ambari-server/src/main/resources/Ambari-DDL-Derby-CREATE.sql
+++ b/ambari-server/src/main/resources/Ambari-DDL-Derby-CREATE.sql
@@ -98,7 +98,7 @@ CREATE TABLE configuration_base (
CREATE TABLE ambari_configuration (
id BIGINT NOT NULL,
CONSTRAINT PK_ambari_configuration PRIMARY KEY (id),
- CONSTRAINT FK_ambari_configuration_configuration_base FOREIGN KEY (id) REFERENCES configuration_base (id)
+ CONSTRAINT FK_ambari_conf_conf_base FOREIGN KEY (id) REFERENCES configuration_base (id)
);
CREATE TABLE serviceconfig (
http://git-wip-us.apache.org/repos/asf/ambari/blob/36a49d17/ambari-server/src/main/resources/Ambari-DDL-MySQL-CREATE.sql
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/resources/Ambari-DDL-MySQL-CREATE.sql b/ambari-server/src/main/resources/Ambari-DDL-MySQL-CREATE.sql
index b8b506a..dc1dea9 100644
--- a/ambari-server/src/main/resources/Ambari-DDL-MySQL-CREATE.sql
+++ b/ambari-server/src/main/resources/Ambari-DDL-MySQL-CREATE.sql
@@ -118,7 +118,7 @@ CREATE TABLE configuration_base (
CREATE TABLE ambari_configuration (
id BIGINT NOT NULL,
CONSTRAINT PK_ambari_configuration PRIMARY KEY (id),
- CONSTRAINT FK_ambari_configuration_configuration_base FOREIGN KEY (id) REFERENCES configuration_base (id)
+ CONSTRAINT FK_ambari_conf_conf_base FOREIGN KEY (id) REFERENCES configuration_base (id)
);
CREATE TABLE serviceconfig (
http://git-wip-us.apache.org/repos/asf/ambari/blob/36a49d17/ambari-server/src/main/resources/Ambari-DDL-Oracle-CREATE.sql
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/resources/Ambari-DDL-Oracle-CREATE.sql b/ambari-server/src/main/resources/Ambari-DDL-Oracle-CREATE.sql
index 1e90426..7c34304 100644
--- a/ambari-server/src/main/resources/Ambari-DDL-Oracle-CREATE.sql
+++ b/ambari-server/src/main/resources/Ambari-DDL-Oracle-CREATE.sql
@@ -98,7 +98,7 @@ CREATE TABLE configuration_base (
CREATE TABLE ambari_configuration (
id NUMBER(19) NOT NULL,
CONSTRAINT PK_ambari_configuration PRIMARY KEY (id),
- CONSTRAINT FK_ambari_configuration_configuration_base FOREIGN KEY (id) REFERENCES configuration_base (id)
+ CONSTRAINT FK_ambari_conf_conf_base FOREIGN KEY (id) REFERENCES configuration_base (id)
);
CREATE TABLE serviceconfig (
http://git-wip-us.apache.org/repos/asf/ambari/blob/36a49d17/ambari-server/src/main/resources/Ambari-DDL-Postgres-CREATE.sql
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/resources/Ambari-DDL-Postgres-CREATE.sql b/ambari-server/src/main/resources/Ambari-DDL-Postgres-CREATE.sql
index 583a51b..9270522 100644
--- a/ambari-server/src/main/resources/Ambari-DDL-Postgres-CREATE.sql
+++ b/ambari-server/src/main/resources/Ambari-DDL-Postgres-CREATE.sql
@@ -80,7 +80,7 @@ CREATE TABLE configuration_base (
CREATE TABLE ambari_configuration (
id BIGINT NOT NULL,
CONSTRAINT PK_ambari_configuration PRIMARY KEY (id),
- CONSTRAINT FK_ambari_configuration_configuration_base FOREIGN KEY (id) REFERENCES configuration_base (id)
+ CONSTRAINT FK_ambari_conf_conf_base FOREIGN KEY (id) REFERENCES configuration_base (id)
);
CREATE TABLE clusterconfig (
http://git-wip-us.apache.org/repos/asf/ambari/blob/36a49d17/ambari-server/src/main/resources/Ambari-DDL-SQLAnywhere-CREATE.sql
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/resources/Ambari-DDL-SQLAnywhere-CREATE.sql b/ambari-server/src/main/resources/Ambari-DDL-SQLAnywhere-CREATE.sql
index 2104b2d..bf6cd4a 100644
--- a/ambari-server/src/main/resources/Ambari-DDL-SQLAnywhere-CREATE.sql
+++ b/ambari-server/src/main/resources/Ambari-DDL-SQLAnywhere-CREATE.sql
@@ -97,7 +97,7 @@ CREATE TABLE configuration_base (
CREATE TABLE ambari_configuration (
id NUMERIC(19) NOT NULL,
CONSTRAINT PK_ambari_configuration PRIMARY KEY (id),
- CONSTRAINT FK_ambari_configuration_configuration_base FOREIGN KEY (id) REFERENCES configuration_base (id)
+ CONSTRAINT FK_ambari_conf_conf_base FOREIGN KEY (id) REFERENCES configuration_base (id)
);
CREATE TABLE serviceconfig (
http://git-wip-us.apache.org/repos/asf/ambari/blob/36a49d17/ambari-server/src/main/resources/Ambari-DDL-SQLServer-CREATE.sql
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/resources/Ambari-DDL-SQLServer-CREATE.sql b/ambari-server/src/main/resources/Ambari-DDL-SQLServer-CREATE.sql
index 7d248b6..fc93600 100644
--- a/ambari-server/src/main/resources/Ambari-DDL-SQLServer-CREATE.sql
+++ b/ambari-server/src/main/resources/Ambari-DDL-SQLServer-CREATE.sql
@@ -111,7 +111,7 @@ CREATE TABLE configuration_base (
CREATE TABLE ambari_configuration (
id BIGINT NOT NULL,
CONSTRAINT PK_ambari_configuration PRIMARY KEY (id),
- CONSTRAINT FK_ambari_configuration_configuration_base FOREIGN KEY (id) REFERENCES configuration_base (id)
+ CONSTRAINT FK_ambari_conf_conf_base FOREIGN KEY (id) REFERENCES configuration_base (id)
);
CREATE TABLE serviceconfig (
http://git-wip-us.apache.org/repos/asf/ambari/blob/36a49d17/ambari-server/src/test/java/org/apache/ambari/server/api/services/ldap/LDAPServiceTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/api/services/ldap/LDAPServiceTest.java b/ambari-server/src/test/java/org/apache/ambari/server/api/services/ldap/LDAPServiceTest.java
deleted file mode 100644
index 5e8eac6..0000000
--- a/ambari-server/src/test/java/org/apache/ambari/server/api/services/ldap/LDAPServiceTest.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.ambari.server.api.services.ldap;
-
-import org.apache.directory.ldap.client.api.LdapConnection;
-import org.apache.directory.ldap.client.api.LdapConnectionConfig;
-import org.apache.directory.ldap.client.api.LdapNetworkConnection;
-import org.codehaus.jackson.map.ObjectMapper;
-import org.junit.Assert;
-import org.junit.Test;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-
-public class LDAPServiceTest {
-
- private static String JSON_STRING = "{\n" +
- " \"AmbariConfiguration\": {\n" +
- " \"type\": \"ldap-config\",\n" +
- " \"data\": [{\n" +
- " \"authentication.ldap.primaryUrl\": \"localhost:33389\",\n" +
- " \"authentication.ldap.secondaryUrl\": \"localhost:333\",\n" +
- " \"authentication.ldap.baseDn\": \"dc=ambari,dc=apache,dc=org\"\n" +
- " }]\n" +
- " }\n" +
- "}";
-
- @Test
- public void testJaxRsJsonTransformation() throws Exception {
- // GIVEN
- ObjectMapper objectMapper = new ObjectMapper();
-
- Gson gsonJsonProvider = new GsonBuilder().create();
-
-
- // WHEN
- LdapConfigurationRequest ldapConfigurationRequest = gsonJsonProvider.fromJson(JSON_STRING, LdapConfigurationRequest.class);
- // LdapConfigurationRequest ldapConfigurationRequest = objectMapper.readValue(JSON_STRING, LdapConfigurationRequest.class);
-
- // THEN
- Assert.assertNotNull(ldapConfigurationRequest);
-
- }
-
-
- @Test
- public void testLdapConnection() throws Exception {
- // GIVEN
- LdapConnection connection = new LdapNetworkConnection("localhost", 389);
-
- // WHEN
- connection.bind();
- // THEN
-
- }
-
-
- @Test
- public void testLdapConnectionConfigs() throws Exception {
- // GIVEN
- LdapConnectionConfig config = new LdapConnectionConfig();
- config.setLdapHost("localhost");
- config.setLdapPort(389);
-
- // WHEN
- LdapConnection connection = new LdapNetworkConnection(config);
-
- // THEN
- connection.anonymousBind();
-
- Assert.assertNotNull(connection);
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/ambari/blob/36a49d17/ambari-server/src/test/java/org/apache/ambari/server/checks/UpgradeCheckOrderTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/checks/UpgradeCheckOrderTest.java b/ambari-server/src/test/java/org/apache/ambari/server/checks/UpgradeCheckOrderTest.java
index aa975e2..0bc1584 100644
--- a/ambari-server/src/test/java/org/apache/ambari/server/checks/UpgradeCheckOrderTest.java
+++ b/ambari-server/src/test/java/org/apache/ambari/server/checks/UpgradeCheckOrderTest.java
@@ -25,6 +25,7 @@ import java.util.Set;
import org.apache.ambari.server.audit.AuditLoggerModule;
import org.apache.ambari.server.configuration.Configuration;
import org.apache.ambari.server.controller.ControllerModule;
+import org.apache.ambari.server.ldap.LdapModule;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.config.BeanDefinition;
@@ -54,7 +55,7 @@ public class UpgradeCheckOrderTest {
properties.setProperty(Configuration.OS_VERSION.getKey(), "centos6");
properties.setProperty(Configuration.SHARED_RESOURCES_DIR.getKey(), sourceResourceDirectory);
- Injector injector = Guice.createInjector(new ControllerModule(properties), new AuditLoggerModule());
+ Injector injector = Guice.createInjector(new ControllerModule(properties), new AuditLoggerModule(), new LdapModule());
UpgradeCheckRegistry registry = injector.getInstance(UpgradeCheckRegistry.class);
UpgradeCheckRegistry registry2 = injector.getInstance(UpgradeCheckRegistry.class);
http://git-wip-us.apache.org/repos/asf/ambari/blob/36a49d17/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/AmbariConfigurationResourceProviderTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/AmbariConfigurationResourceProviderTest.java b/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/AmbariConfigurationResourceProviderTest.java
index d974682..c2a1421 100644
--- a/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/AmbariConfigurationResourceProviderTest.java
+++ b/ambari-server/src/test/java/org/apache/ambari/server/controller/internal/AmbariConfigurationResourceProviderTest.java
@@ -21,6 +21,8 @@ import org.apache.ambari.server.controller.spi.Predicate;
import org.apache.ambari.server.controller.spi.Request;
import org.apache.ambari.server.controller.spi.Resource;
import org.apache.ambari.server.controller.utilities.PredicateBuilder;
+import org.apache.ambari.server.events.AmbariLdapConfigChangedEvent;
+import org.apache.ambari.server.events.publishers.AmbariEventPublisher;
import org.apache.ambari.server.orm.dao.AmbariConfigurationDAO;
import org.apache.ambari.server.orm.entities.AmbariConfigurationEntity;
import org.apache.ambari.server.orm.entities.ConfigurationBaseEntity;
@@ -52,6 +54,9 @@ public class AmbariConfigurationResourceProviderTest extends EasyMockSupport {
@Mock
private AmbariConfigurationDAO ambariConfigurationDAO;
+ @Mock
+ private AmbariEventPublisher publisher;
+
private Capture<AmbariConfigurationEntity> ambariConfigurationEntityCapture;
private Gson gson;
@@ -68,6 +73,7 @@ public class AmbariConfigurationResourceProviderTest extends EasyMockSupport {
private static final String PK_STRING = String.valueOf(1);
private static final String VERSION_TAG = "test version";
private static final String VERSION = "1";
+ private static final String TYPE = "AmbariConfiguration";
@TestSubject
private AmbariConfigurationResourceProvider ambariConfigurationResourceProvider = new AmbariConfigurationResourceProvider();
@@ -89,6 +95,7 @@ public class AmbariConfigurationResourceProviderTest extends EasyMockSupport {
.withVersion(VERSION)
.withVersionTag(VERSION_TAG)
.withData(DATA_MOCK_STR)
+ .withType(TYPE)
.build());
// mock the request to return the properties
@@ -96,6 +103,8 @@ public class AmbariConfigurationResourceProviderTest extends EasyMockSupport {
// capture the entity the DAO gets called with
ambariConfigurationDAO.create(EasyMock.capture(ambariConfigurationEntityCapture));
+ publisher.publish(EasyMock.anyObject(AmbariLdapConfigChangedEvent.class));
+
replayAll();
// WHEN
@@ -121,6 +130,8 @@ public class AmbariConfigurationResourceProviderTest extends EasyMockSupport {
Capture<Long> pkCapture = Capture.newInstance();
ambariConfigurationDAO.removeByPK(EasyMock.capture(pkCapture));
+ publisher.publish(EasyMock.anyObject(AmbariLdapConfigChangedEvent.class));
+
replayAll();
// WHEN
@@ -160,13 +171,16 @@ public class AmbariConfigurationResourceProviderTest extends EasyMockSupport {
.withId(PK_LONG)
.withVersion("2")
.withVersionTag("version-2")
- .withData(DATA_MOCK_STR).build());
+ .withData(DATA_MOCK_STR)
+ .withType(TYPE)
+ .build());
EasyMock.expect(requestMock.getProperties()).andReturn(resourcePropertiesSet);
AmbariConfigurationEntity persistedEntity = createDummyAmbariConfigurationEntity();
EasyMock.expect(ambariConfigurationDAO.findByPK(PK_LONG)).andReturn(persistedEntity);
- ambariConfigurationDAO.create(EasyMock.capture(ambariConfigurationEntityCapture));
+ ambariConfigurationDAO.update(EasyMock.capture(ambariConfigurationEntityCapture));
+ publisher.publish(EasyMock.anyObject(AmbariLdapConfigChangedEvent.class));
replayAll();
@@ -208,6 +222,12 @@ public class AmbariConfigurationResourceProviderTest extends EasyMockSupport {
return this;
}
+ private PropertiesMapBuilder withType(String type) {
+ resourcePropertiesMap.put(AmbariConfigurationResourceProvider.ResourcePropertyId.TYPE.getPropertyId(), type);
+ return this;
+ }
+
+
public Map<String, Object> build() {
return this.resourcePropertiesMap;
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/36a49d17/ambari-server/src/test/java/org/apache/ambari/server/ldap/LdapModuleFunctionalTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/LdapModuleFunctionalTest.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/LdapModuleFunctionalTest.java
index b9f140e..f3f0644 100644
--- a/ambari-server/src/test/java/org/apache/ambari/server/ldap/LdapModuleFunctionalTest.java
+++ b/ambari-server/src/test/java/org/apache/ambari/server/ldap/LdapModuleFunctionalTest.java
@@ -32,6 +32,7 @@ import org.apache.directory.ldap.client.template.LdapConnectionTemplate;
import org.apache.directory.ldap.client.template.exception.PasswordException;
import org.junit.Assert;
import org.junit.BeforeClass;
+import org.junit.Ignore;
import org.junit.Test;
import com.google.common.collect.Maps;
@@ -41,6 +42,7 @@ import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.util.Modules;
+@Ignore
public class LdapModuleFunctionalTest {
private static Injector injector;
@@ -62,7 +64,7 @@ public class LdapModuleFunctionalTest {
injector = Guice.createInjector(testModule);
}
- @Test
+ @Test()
public void shouldLdapTemplateBeInstantiated() throws LdapInvalidDnException, PasswordException {
// GIVEN
// the injector is set up
http://git-wip-us.apache.org/repos/asf/ambari/blob/36a49d17/ambari-server/src/test/java/org/apache/ambari/server/notifications/DispatchFactoryTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/notifications/DispatchFactoryTest.java b/ambari-server/src/test/java/org/apache/ambari/server/notifications/DispatchFactoryTest.java
index 382799c..d34d732 100644
--- a/ambari-server/src/test/java/org/apache/ambari/server/notifications/DispatchFactoryTest.java
+++ b/ambari-server/src/test/java/org/apache/ambari/server/notifications/DispatchFactoryTest.java
@@ -23,6 +23,7 @@ import java.util.Properties;
import org.apache.ambari.server.audit.AuditLoggerModule;
import org.apache.ambari.server.configuration.Configuration;
import org.apache.ambari.server.controller.ControllerModule;
+import org.apache.ambari.server.ldap.LdapModule;
import org.apache.ambari.server.notifications.dispatchers.EmailDispatcher;
import org.apache.ambari.server.notifications.dispatchers.SNMPDispatcher;
import org.junit.Assert;
@@ -55,7 +56,7 @@ public class DispatchFactoryTest {
properties.setProperty(Configuration.SHARED_RESOURCES_DIR.getKey(),sourceResourceDirectory);
properties.setProperty(Configuration.ALERTS_SNMP_DISPATCH_UDP_PORT.getKey(),snmpPort.toString());
- Injector injector = Guice.createInjector(new AuditLoggerModule(), new ControllerModule(properties));
+ Injector injector = Guice.createInjector(new AuditLoggerModule(), new ControllerModule(properties), new LdapModule());
DispatchFactory dispatchFactory = injector.getInstance(DispatchFactory.class);
DispatchFactory dispatchFactory2 = injector.getInstance(DispatchFactory.class);
http://git-wip-us.apache.org/repos/asf/ambari/blob/36a49d17/ambari-server/src/test/java/org/apache/ambari/server/orm/InMemoryDefaultTestModule.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/orm/InMemoryDefaultTestModule.java b/ambari-server/src/test/java/org/apache/ambari/server/orm/InMemoryDefaultTestModule.java
index 434a2a1..ebc2596 100644
--- a/ambari-server/src/test/java/org/apache/ambari/server/orm/InMemoryDefaultTestModule.java
+++ b/ambari-server/src/test/java/org/apache/ambari/server/orm/InMemoryDefaultTestModule.java
@@ -26,6 +26,7 @@ import java.util.concurrent.atomic.AtomicReference;
import org.apache.ambari.server.audit.AuditLogger;
import org.apache.ambari.server.configuration.Configuration;
import org.apache.ambari.server.controller.ControllerModule;
+import org.apache.ambari.server.ldap.LdapModule;
import org.apache.ambari.server.stack.StackManager;
import org.apache.ambari.server.stack.StackManagerFactory;
import org.apache.ambari.server.stack.StackManagerMock;
@@ -122,6 +123,7 @@ public class InMemoryDefaultTestModule extends AbstractModule {
}
try {
+ install(new LdapModule());
install(Modules.override(new BeanDefinitionsCachingTestControllerModule(properties)).with(new AbstractModule() {
@Override
protected void configure() {
http://git-wip-us.apache.org/repos/asf/ambari/blob/36a49d17/ambari-server/src/test/java/org/apache/ambari/server/orm/JdbcPropertyTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/orm/JdbcPropertyTest.java b/ambari-server/src/test/java/org/apache/ambari/server/orm/JdbcPropertyTest.java
index 427cede..14c5dd6 100644
--- a/ambari-server/src/test/java/org/apache/ambari/server/orm/JdbcPropertyTest.java
+++ b/ambari-server/src/test/java/org/apache/ambari/server/orm/JdbcPropertyTest.java
@@ -23,6 +23,7 @@ import org.apache.ambari.server.H2DatabaseCleaner;
import org.apache.ambari.server.audit.AuditLoggerModule;
import org.apache.ambari.server.configuration.Configuration;
import org.apache.ambari.server.controller.ControllerModule;
+import org.apache.ambari.server.ldap.LdapModule;
import org.apache.ambari.server.state.Clusters;
import org.junit.After;
import org.junit.Assert;
@@ -53,7 +54,7 @@ public class JdbcPropertyTest {
@Test
public void testNormal() throws Exception {
- injector = Guice.createInjector(new AuditLoggerModule(), new ControllerModule(properties));
+ injector = Guice.createInjector(new AuditLoggerModule(), new ControllerModule(properties), new LdapModule());
injector.getInstance(GuiceJpaInitializer.class);
injector.getInstance(Clusters.class);
@@ -62,7 +63,7 @@ public class JdbcPropertyTest {
@Test
public void testJdbcProperty() throws Exception {
properties.setProperty(Configuration.SERVER_JDBC_PROPERTIES_PREFIX + "shutdown", "true");
- injector = Guice.createInjector(new AuditLoggerModule(), new ControllerModule(properties));
+ injector = Guice.createInjector(new AuditLoggerModule(), new ControllerModule(properties), new LdapModule());
injector.getInstance(GuiceJpaInitializer.class);
try {
injector.getInstance(Clusters.class);
http://git-wip-us.apache.org/repos/asf/ambari/blob/36a49d17/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariLdapAuthenticationProviderForDNWithSpaceTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariLdapAuthenticationProviderForDNWithSpaceTest.java b/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariLdapAuthenticationProviderForDNWithSpaceTest.java
index 442414f..566d6b7 100644
--- a/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariLdapAuthenticationProviderForDNWithSpaceTest.java
+++ b/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariLdapAuthenticationProviderForDNWithSpaceTest.java
@@ -26,6 +26,7 @@ import org.apache.ambari.server.H2DatabaseCleaner;
import org.apache.ambari.server.audit.AuditLoggerModule;
import org.apache.ambari.server.configuration.Configuration;
import org.apache.ambari.server.controller.ControllerModule;
+import org.apache.ambari.server.ldap.LdapModule;
import org.apache.ambari.server.orm.GuiceJpaInitializer;
import org.apache.ambari.server.orm.dao.UserDAO;
import org.apache.ambari.server.security.ClientSecurityType;
@@ -49,23 +50,23 @@ import com.google.inject.Injector;
@RunWith(FrameworkRunner.class)
@CreateDS(allowAnonAccess = true,
- name = "AmbariLdapAuthenticationProviderForDNWithSpaceTest",
- partitions = {
- @CreatePartition(name = "Root",
- suffix = "dc=the apache,dc=org",
- contextEntry = @ContextEntry(
- entryLdif =
- "dn: dc=the apache,dc=org\n" +
- "dc: the apache\n" +
- "objectClass: top\n" +
- "objectClass: domain\n\n" +
- "dn: dc=ambari,dc=the apache,dc=org\n" +
- "dc: ambari\n" +
- "objectClass: top\n" +
- "objectClass: domain\n\n"))
- })
+ name = "AmbariLdapAuthenticationProviderForDNWithSpaceTest",
+ partitions = {
+ @CreatePartition(name = "Root",
+ suffix = "dc=the apache,dc=org",
+ contextEntry = @ContextEntry(
+ entryLdif =
+ "dn: dc=the apache,dc=org\n" +
+ "dc: the apache\n" +
+ "objectClass: top\n" +
+ "objectClass: domain\n\n" +
+ "dn: dc=ambari,dc=the apache,dc=org\n" +
+ "dc: ambari\n" +
+ "objectClass: top\n" +
+ "objectClass: domain\n\n"))
+ })
@CreateLdapServer(allowAnonymousAccess = true,
- transports = {@CreateTransport(protocol = "LDAP")})
+ transports = {@CreateTransport(protocol = "LDAP")})
@ApplyLdifFiles("users_for_dn_with_space.ldif")
public class AmbariLdapAuthenticationProviderForDNWithSpaceTest extends AmbariLdapAuthenticationProviderBaseTest {
@@ -83,7 +84,7 @@ public class AmbariLdapAuthenticationProviderForDNWithSpaceTest extends AmbariLd
@Before
public void setUp() throws Exception {
- injector = Guice.createInjector(new ControllerModule(getTestProperties()), new AuditLoggerModule());
+ injector = Guice.createInjector(new ControllerModule(getTestProperties()), new AuditLoggerModule(), new LdapModule());
injector.getInstance(GuiceJpaInitializer.class);
injector.injectMembers(this);
http://git-wip-us.apache.org/repos/asf/ambari/blob/36a49d17/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariLdapAuthenticationProviderTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariLdapAuthenticationProviderTest.java b/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariLdapAuthenticationProviderTest.java
index 4941bc7..d8be809 100644
--- a/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariLdapAuthenticationProviderTest.java
+++ b/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariLdapAuthenticationProviderTest.java
@@ -29,6 +29,7 @@ import static org.junit.Assert.fail;
import org.apache.ambari.server.H2DatabaseCleaner;
import org.apache.ambari.server.audit.AuditLoggerModule;
import org.apache.ambari.server.configuration.Configuration;
+import org.apache.ambari.server.ldap.LdapModule;
import org.apache.ambari.server.orm.GuiceJpaInitializer;
import org.apache.ambari.server.orm.dao.UserDAO;
import org.apache.ambari.server.orm.entities.UserEntity;
@@ -90,7 +91,7 @@ public class AmbariLdapAuthenticationProviderTest extends AmbariLdapAuthenticati
@Before
public void setUp() {
- injector = Guice.createInjector(new AuditLoggerModule(), new AuthorizationTestModule());
+ injector = Guice.createInjector(new AuditLoggerModule(), new AuthorizationTestModule(), new LdapModule());
injector.injectMembers(this);
injector.getInstance(GuiceJpaInitializer.class);
configuration.setClientSecurityType(ClientSecurityType.LDAP);
http://git-wip-us.apache.org/repos/asf/ambari/blob/36a49d17/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariLocalUserProviderTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariLocalUserProviderTest.java b/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariLocalUserProviderTest.java
index 2362823..d889372 100644
--- a/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariLocalUserProviderTest.java
+++ b/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/AmbariLocalUserProviderTest.java
@@ -27,6 +27,7 @@ import static org.junit.Assert.assertTrue;
import org.apache.ambari.server.H2DatabaseCleaner;
import org.apache.ambari.server.audit.AuditLoggerModule;
+import org.apache.ambari.server.ldap.LdapModule;
import org.apache.ambari.server.orm.GuiceJpaInitializer;
import org.apache.ambari.server.orm.OrmTestHelper;
import org.apache.ambari.server.orm.dao.UserDAO;
@@ -56,7 +57,7 @@ public class AmbariLocalUserProviderTest {
@BeforeClass
public static void prepareData() {
- injector = Guice.createInjector(new AuditLoggerModule(), new AuthorizationTestModule());
+ injector = Guice.createInjector(new AuditLoggerModule(), new AuthorizationTestModule(), new LdapModule());
injector.getInstance(GuiceJpaInitializer.class);
injector.getInstance(OrmTestHelper.class).createTestUsers();
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/36a49d17/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/LdapServerPropertiesTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/LdapServerPropertiesTest.java b/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/LdapServerPropertiesTest.java
index 5747408..0e1515b 100644
--- a/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/LdapServerPropertiesTest.java
+++ b/ambari-server/src/test/java/org/apache/ambari/server/security/authorization/LdapServerPropertiesTest.java
@@ -25,6 +25,7 @@ import java.util.List;
import org.apache.ambari.server.audit.AuditLoggerModule;
import org.apache.ambari.server.configuration.Configuration;
+import org.apache.ambari.server.ldap.LdapModule;
import org.junit.Before;
import org.junit.Test;
@@ -45,13 +46,13 @@ public class LdapServerPropertiesTest {
Configuration configuration;
public LdapServerPropertiesTest() {
- injector = Guice.createInjector(new AuditLoggerModule(), new AuthorizationTestModule());
+ injector = Guice.createInjector(new AuditLoggerModule(), new AuthorizationTestModule(), new LdapModule());
injector.injectMembers(this);
}
@Before
public void setUp() throws Exception {
- ldapServerProperties = new LdapServerProperties();
+ ldapServerProperties = new LdapServerProperties();
ldapServerProperties.setAnonymousBind(true);
ldapServerProperties.setBaseDN("dc=ambari,dc=apache,dc=org");
ldapServerProperties.setManagerDn("uid=manager," + ldapServerProperties.getBaseDN());
[03/33] ambari git commit: AMBARI-22230 Hosts and Alerts tables UI
tweaks. (atkach)
Posted by lp...@apache.org.
AMBARI-22230 Hosts and Alerts tables UI tweaks. (atkach)
Project: http://git-wip-us.apache.org/repos/asf/ambari/repo
Commit: http://git-wip-us.apache.org/repos/asf/ambari/commit/8f53bc45
Tree: http://git-wip-us.apache.org/repos/asf/ambari/tree/8f53bc45
Diff: http://git-wip-us.apache.org/repos/asf/ambari/diff/8f53bc45
Branch: refs/heads/feature-branch-AMBARI-21307
Commit: 8f53bc453c47a4f95d5e58825feb77d69e6a6a22
Parents: a8ba5e6
Author: Andrii Tkach <at...@apache.org>
Authored: Fri Oct 13 13:45:06 2017 +0300
Committer: Andrii Tkach <at...@apache.org>
Committed: Fri Oct 13 13:45:06 2017 +0300
----------------------------------------------------------------------
ambari-web/app/models/alerts/alert_group.js | 2 +-
ambari-web/app/styles/application.less | 5 +
ambari-web/app/styles/dashboard.less | 6 +-
.../app/styles/theme/bootstrap-ambari.css | 3 +-
ambari-web/app/templates/main/alerts.hbs | 3 +-
.../main/alerts/alert_definitions_actions.hbs | 2 +-
ambari-web/app/templates/main/dashboard.hbs | 2 +-
.../templates/main/dashboard/config_history.hbs | 2 +-
ambari-web/app/templates/main/host.hbs | 2 +-
.../templates/main/host/bulk_operation_menu.hbs | 132 ++++++++++---------
.../views/main/host/hosts_table_menu_view.js | 4 +-
.../app/views/main/host/stack_versions_view.js | 2 +-
.../test/models/alerts/alert_group_test.js | 5 +-
13 files changed, 93 insertions(+), 77 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/ambari/blob/8f53bc45/ambari-web/app/models/alerts/alert_group.js
----------------------------------------------------------------------
diff --git a/ambari-web/app/models/alerts/alert_group.js b/ambari-web/app/models/alerts/alert_group.js
index 49a850f..3277fc8 100644
--- a/ambari-web/app/models/alerts/alert_group.js
+++ b/ambari-web/app/models/alerts/alert_group.js
@@ -55,7 +55,7 @@ App.AlertGroup = DS.Model.extend({
* @type {string}
*/
displayName: function () {
- var name = App.config.truncateGroupName(this.get('name'));
+ var name = App.config.truncateGroupName(App.format.role(this.get('name'), true));
return this.get('default') ? name + ' Default' : name;
}.property('name', 'default'),
http://git-wip-us.apache.org/repos/asf/ambari/blob/8f53bc45/ambari-web/app/styles/application.less
----------------------------------------------------------------------
diff --git a/ambari-web/app/styles/application.less b/ambari-web/app/styles/application.less
index 7c9cc8e..099f3cf 100644
--- a/ambari-web/app/styles/application.less
+++ b/ambari-web/app/styles/application.less
@@ -2802,4 +2802,9 @@ a.abort-icon:hover {
.breadcrumbs-forward-slash {
display: inline;
color: #D2D3D5;
+}
+
+.container-wrap-table {
+ padding: 0 10px;
+ background-color: @diff-background-equal;
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/ambari/blob/8f53bc45/ambari-web/app/styles/dashboard.less
----------------------------------------------------------------------
diff --git a/ambari-web/app/styles/dashboard.less b/ambari-web/app/styles/dashboard.less
index 02835bd..6deb30c 100644
--- a/ambari-web/app/styles/dashboard.less
+++ b/ambari-web/app/styles/dashboard.less
@@ -18,14 +18,12 @@
@import 'common.less';
-#dashboard-widgets-container{
- .tabs-left {
- float: left;
- }
+#dashboard-widgets-container {
.btn-toolbar {
float: right;
padding-top: 5px;
margin-bottom: 20px;
+ margin-top: -60px;
}
.dashboard-widgets-box {
clear: both;
http://git-wip-us.apache.org/repos/asf/ambari/blob/8f53bc45/ambari-web/app/styles/theme/bootstrap-ambari.css
----------------------------------------------------------------------
diff --git a/ambari-web/app/styles/theme/bootstrap-ambari.css b/ambari-web/app/styles/theme/bootstrap-ambari.css
index 70579e7..cff73ad 100644
--- a/ambari-web/app/styles/theme/bootstrap-ambari.css
+++ b/ambari-web/app/styles/theme/bootstrap-ambari.css
@@ -479,11 +479,12 @@ h2.table-title {
}
.nav.nav-tabs li a .badge.badge-important {
display: inline;
+ vertical-align: baseline;
}
.nav.nav-tabs li.active a {
color: #333;
border-bottom: 3px solid #3FAE2A;
- padding-bottom: 1px;
+ padding-bottom: 2px;
}
.nav-tabs-left li,
.nav-tabs-right li {
http://git-wip-us.apache.org/repos/asf/ambari/blob/8f53bc45/ambari-web/app/templates/main/alerts.hbs
----------------------------------------------------------------------
diff --git a/ambari-web/app/templates/main/alerts.hbs b/ambari-web/app/templates/main/alerts.hbs
index 40469d3..0f85e27 100644
--- a/ambari-web/app/templates/main/alerts.hbs
+++ b/ambari-web/app/templates/main/alerts.hbs
@@ -16,7 +16,7 @@
* limitations under the License.
}}
-<div id="alerts">
+<div id="alerts" class="container-wrap-table">
<div class="row">
<h2 class="table-title col-sm-1">{{t menu.item.alerts}}</h2>
<div class="table-controls row col-sm-11 pull-right">
@@ -56,7 +56,6 @@
{{view App.AlertDefinitionSummary contentBinding="alertDefinition"}}
</td>
<td class="alert-name">
- <span {{bindAttr title="alertDefinition.type"}} {{bindAttr class=":type-icon alertDefinition.typeIconClass"}}></span>
<a href="#" {{action "gotoAlertDetails" alertDefinition}}>{{alertDefinition.label}}</a>
</td>
<td class="alert-service">{{alertDefinition.serviceDisplayName}}</td>
http://git-wip-us.apache.org/repos/asf/ambari/blob/8f53bc45/ambari-web/app/templates/main/alerts/alert_definitions_actions.hbs
----------------------------------------------------------------------
diff --git a/ambari-web/app/templates/main/alerts/alert_definitions_actions.hbs b/ambari-web/app/templates/main/alerts/alert_definitions_actions.hbs
index 0604ac2..f65b000 100644
--- a/ambari-web/app/templates/main/alerts/alert_definitions_actions.hbs
+++ b/ambari-web/app/templates/main/alerts/alert_definitions_actions.hbs
@@ -16,7 +16,7 @@
* limitations under the License.
}}
-<button class="btn btn-default dropdown-toggle" data-toggle="dropdown" href="#">{{t common.actions}} <span class="caret"></span></button>
+<button class="btn btn-success dropdown-toggle" data-toggle="dropdown" href="#">{{t common.actions}} <span class="caret"></span></button>
<ul class="dropdown-menu pull-left">
{{#each action in controller}}
<li>
http://git-wip-us.apache.org/repos/asf/ambari/blob/8f53bc45/ambari-web/app/templates/main/dashboard.hbs
----------------------------------------------------------------------
diff --git a/ambari-web/app/templates/main/dashboard.hbs b/ambari-web/app/templates/main/dashboard.hbs
index 0226626..4b174cc 100644
--- a/ambari-web/app/templates/main/dashboard.hbs
+++ b/ambari-web/app/templates/main/dashboard.hbs
@@ -18,7 +18,7 @@
<div class="row">
<div class="summary-width col-md-12" id="dashboard-widgets-container">
- <ul class="nav nav-tabs background-text tabs-left">
+ <ul class="nav nav-tabs background-text">
{{#each category in view.categories}}
{{#view view.NavItemView itemBinding="category.name" }}
<a href="#" {{action "goToDashboardView" category.url}} >{{category.label}}</a>
http://git-wip-us.apache.org/repos/asf/ambari/blob/8f53bc45/ambari-web/app/templates/main/dashboard/config_history.hbs
----------------------------------------------------------------------
diff --git a/ambari-web/app/templates/main/dashboard/config_history.hbs b/ambari-web/app/templates/main/dashboard/config_history.hbs
index 00f9c38..bc6ef7c 100644
--- a/ambari-web/app/templates/main/dashboard/config_history.hbs
+++ b/ambari-web/app/templates/main/dashboard/config_history.hbs
@@ -16,7 +16,7 @@
* limitations under the License.
}}
-<div id="config_history">
+<div id="config_history" class="container-wrap-table">
<div class="row">
<h2 class="table-title col-md-12">{{t dashboard.configHistory.title}}</h2>
</div>
http://git-wip-us.apache.org/repos/asf/ambari/blob/8f53bc45/ambari-web/app/templates/main/host.hbs
----------------------------------------------------------------------
diff --git a/ambari-web/app/templates/main/host.hbs b/ambari-web/app/templates/main/host.hbs
index ae37a0f..b373c40 100644
--- a/ambari-web/app/templates/main/host.hbs
+++ b/ambari-web/app/templates/main/host.hbs
@@ -16,7 +16,7 @@
* limitations under the License.
}}
-<div id="hosts">
+<div id="hosts" class="container-wrap-table">
<div class="row">
<h2 class="table-title col-sm-1">{{t common.hosts}}</h2>
http://git-wip-us.apache.org/repos/asf/ambari/blob/8f53bc45/ambari-web/app/templates/main/host/bulk_operation_menu.hbs
----------------------------------------------------------------------
diff --git a/ambari-web/app/templates/main/host/bulk_operation_menu.hbs b/ambari-web/app/templates/main/host/bulk_operation_menu.hbs
index 64ab4e9..89551ca 100644
--- a/ambari-web/app/templates/main/host/bulk_operation_menu.hbs
+++ b/ambari-web/app/templates/main/host/bulk_operation_menu.hbs
@@ -16,7 +16,7 @@
* limitations under the License.
}}
-<button class="btn btn-default dropdown-toggle" data-toggle="dropdown" href="#">{{t common.actions}} <span class="caret"></span></button>
+<button class="btn btn-success dropdown-toggle" data-toggle="dropdown" href="#">{{t common.actions}} <span class="caret"></span></button>
<ul class="dropdown-menu">
{{#isAuthorized "HOST.ADD_DELETE_HOSTS"}}
<li><a href="#" {{action addHost}}><i class="glyphicon glyphicon-plus glyphicon-white"></i> {{t hosts.host.add}}</a></li>
@@ -29,32 +29,36 @@
<ul {{bindAttr class="view.parentView.showSelectedFilter::hidden :dropdown-menu"}}>
{{#view view.hostItemView}}
<a href="javascript:void(null);">{{view.label}}</a>
- <ul class="dropdown-menu">
- {{#each operation in view.operationsInfo}}
- {{#if operation.label.length}}
- {{#view view.operationView contentBinding="operation.operationData" selection="s"}}
- <a href="javascript:void(null);">{{operation.label}}</a>
- {{/view}}
- {{/if}}
- {{/each}}
- </ul>
- {{/view}}
- {{#each component in view.components}}
- {{#view view.slaveItemView contentBinding="component"}}
- <a href="javascript:void(null);">{{component.componentNameFormatted}}</a>
+ <div class="dropdown-menu-wrap">
<ul class="dropdown-menu">
{{#each operation in view.operationsInfo}}
- {{#if operation.decommission}}
- {{#view view.advancedOperationView contentBinding="operation.operationData" selection="s"}}
- <a href="javascript:void(null);">{{operation.label}}</a>
- {{/view}}
- {{else}}
- {{#view view.commonOperationView contentBinding="operation.operationData" selection="s"}}
+ {{#if operation.label.length}}
+ {{#view view.operationView contentBinding="operation.operationData" selection="s"}}
<a href="javascript:void(null);">{{operation.label}}</a>
{{/view}}
{{/if}}
{{/each}}
</ul>
+ </div>
+ {{/view}}
+ {{#each component in view.components}}
+ {{#view view.slaveItemView contentBinding="component"}}
+ <a href="javascript:void(null);">{{component.componentNameFormatted}}</a>
+ <div class="dropdown-menu-wrap">
+ <ul class="dropdown-menu">
+ {{#each operation in view.operationsInfo}}
+ {{#if operation.decommission}}
+ {{#view view.advancedOperationView contentBinding="operation.operationData" selection="s"}}
+ <a href="javascript:void(null);">{{operation.label}}</a>
+ {{/view}}
+ {{else}}
+ {{#view view.commonOperationView contentBinding="operation.operationData" selection="s"}}
+ <a href="javascript:void(null);">{{operation.label}}</a>
+ {{/view}}
+ {{/if}}
+ {{/each}}
+ </ul>
+ </div>
{{/view}}
{{/each}}
</ul>
@@ -67,32 +71,36 @@
<ul {{bindAttr class="view.parentView.hasFilteredItems::hidden :dropdown-menu"}}>
{{#view view.hostItemView}}
<a href="javascript:void(null);">{{view.label}}</a>
- <ul class="dropdown-menu">
- {{#each operation in view.operationsInfo}}
- {{#if operation.label.length}}
- {{#view view.operationView contentBinding="operation.operationData" selection="f"}}
- <a href="javascript:void(null);">{{operation.label}}</a>
- {{/view}}
- {{/if}}
- {{/each}}
- </ul>
- {{/view}}
- {{#each component in view.components}}
- {{#view view.slaveItemView contentBinding="component"}}
- <a href="javascript:void(null);">{{component.componentNameFormatted}}</a>
+ <div class="dropdown-menu-wrap">
<ul class="dropdown-menu">
{{#each operation in view.operationsInfo}}
- {{#if operation.decommission}}
- {{#view view.advancedOperationView contentBinding="operation.operationData" selection="f"}}
- <a href="javascript:void(null);">{{operation.label}}</a>
- {{/view}}
- {{else}}
- {{#view view.commonOperationView contentBinding="operation.operationData" selection="f"}}
+ {{#if operation.label.length}}
+ {{#view view.operationView contentBinding="operation.operationData" selection="f"}}
<a href="javascript:void(null);">{{operation.label}}</a>
{{/view}}
{{/if}}
{{/each}}
</ul>
+ </div>
+ {{/view}}
+ {{#each component in view.components}}
+ {{#view view.slaveItemView contentBinding="component"}}
+ <a href="javascript:void(null);">{{component.componentNameFormatted}}</a>
+ <div class="dropdown-menu-wrap">
+ <ul class="dropdown-menu">
+ {{#each operation in view.operationsInfo}}
+ {{#if operation.decommission}}
+ {{#view view.advancedOperationView contentBinding="operation.operationData" selection="f"}}
+ <a href="javascript:void(null);">{{operation.label}}</a>
+ {{/view}}
+ {{else}}
+ {{#view view.commonOperationView contentBinding="operation.operationData" selection="f"}}
+ <a href="javascript:void(null);">{{operation.label}}</a>
+ {{/view}}
+ {{/if}}
+ {{/each}}
+ </ul>
+ </div>
{{/view}}
{{/each}}
</ul>
@@ -105,34 +113,38 @@
<ul class="dropdown-menu">
{{#view view.hostItemView}}
<a href="javascript:void(null);">{{view.label}}</a>
- <ul class="dropdown-menu">
- {{#each operation in view.operationsInfo}}
- {{#if operation.label.length}}
- {{#view view.operationView contentBinding="operation.operationData" selection="a"}}
- <a href="javascript:void(null);">{{operation.label}}</a>
- {{/view}}
- {{/if}}
- {{/each}}
- </ul>
- {{/view}}
- {{#each component in view.components}}
- {{#view view.slaveItemView contentBinding="component"}}
- <a href="javascript:void(null);">{{component.componentNameFormatted}}</a>
+ <div class="dropdown-menu-wrap">
<ul class="dropdown-menu">
{{#each operation in view.operationsInfo}}
- {{#if operation.decommission}}
- {{#view view.advancedOperationView contentBinding="operation.operationData" selection="a"}}
+ {{#if operation.label.length}}
+ {{#view view.operationView contentBinding="operation.operationData" selection="a"}}
<a href="javascript:void(null);">{{operation.label}}</a>
{{/view}}
- {{else}}
- {{#unless operation.delete}}
- {{#view view.commonOperationView contentBinding="operation.operationData" selection="a"}}
- <a href="javascript:void(null);">{{operation.label}}</a>
- {{/view}}
- {{/unless}}
{{/if}}
{{/each}}
</ul>
+ </div>
+ {{/view}}
+ {{#each component in view.components}}
+ {{#view view.slaveItemView contentBinding="component"}}
+ <a href="javascript:void(null);">{{component.componentNameFormatted}}</a>
+ <div class="dropdown-menu-wrap">
+ <ul class="dropdown-menu">
+ {{#each operation in view.operationsInfo}}
+ {{#if operation.decommission}}
+ {{#view view.advancedOperationView contentBinding="operation.operationData" selection="a"}}
+ <a href="javascript:void(null);">{{operation.label}}</a>
+ {{/view}}
+ {{else}}
+ {{#unless operation.delete}}
+ {{#view view.commonOperationView contentBinding="operation.operationData" selection="a"}}
+ <a href="javascript:void(null);">{{operation.label}}</a>
+ {{/view}}
+ {{/unless}}
+ {{/if}}
+ {{/each}}
+ </ul>
+ </div>
{{/view}}
{{/each}}
</ul>
http://git-wip-us.apache.org/repos/asf/ambari/blob/8f53bc45/ambari-web/app/views/main/host/hosts_table_menu_view.js
----------------------------------------------------------------------
diff --git a/ambari-web/app/views/main/host/hosts_table_menu_view.js b/ambari-web/app/views/main/host/hosts_table_menu_view.js
index 25b4052..08fd0d4 100644
--- a/ambari-web/app/views/main/host/hosts_table_menu_view.js
+++ b/ambari-web/app/views/main/host/hosts_table_menu_view.js
@@ -70,7 +70,7 @@ App.HostTableMenuView = Em.View.extend({
slaveItemView: Em.View.extend({
tagName: 'li',
- classNames: ['dropdown-submenu'],
+ classNames: ['dropdown-submenu', 'submenu-left'],
/**
* Get third-level menu items ingo for slave components
@@ -240,7 +240,7 @@ App.HostTableMenuView = Em.View.extend({
hostItemView: Em.View.extend({
tagName: 'li',
- classNames: ['dropdown-submenu'],
+ classNames: ['dropdown-submenu', 'submenu-left'],
label: Em.I18n.t('common.hosts'),
http://git-wip-us.apache.org/repos/asf/ambari/blob/8f53bc45/ambari-web/app/views/main/host/stack_versions_view.js
----------------------------------------------------------------------
diff --git a/ambari-web/app/views/main/host/stack_versions_view.js b/ambari-web/app/views/main/host/stack_versions_view.js
index cebe8c7..62a88b4 100644
--- a/ambari-web/app/views/main/host/stack_versions_view.js
+++ b/ambari-web/app/views/main/host/stack_versions_view.js
@@ -22,7 +22,7 @@ var sort = require('views/common/sort_view');
App.MainHostStackVersionsView = App.TableView.extend({
templateName: require('templates/main/host/stack_versions'),
- classNames: ['host-tab-content'],
+ classNames: ['host-tab-content', 'container-wrap-table'],
/**
* @type {Ember.Object}
http://git-wip-us.apache.org/repos/asf/ambari/blob/8f53bc45/ambari-web/test/models/alerts/alert_group_test.js
----------------------------------------------------------------------
diff --git a/ambari-web/test/models/alerts/alert_group_test.js b/ambari-web/test/models/alerts/alert_group_test.js
index 6f64b7a..34237d2 100644
--- a/ambari-web/test/models/alerts/alert_group_test.js
+++ b/ambari-web/test/models/alerts/alert_group_test.js
@@ -35,8 +35,9 @@ describe('App.AlertGroup', function() {
describe('#displayName', function () {
[
- {name: 'abc', default: true, e: 'abc Default'},
- {name: 'abc', default: false, e: 'abc'},
+ {name: 'abc', default: true, e: 'Abc Default'},
+ {name: 'abc', default: false, e: 'Abc'},
+ {name: 'ABC', default: false, e: 'Abc'},
{name: '12345678901234567890', default: true, e: '123456789...234567890 Default'},
{name: '12345678901234567890', default: false, e: '123456789...234567890'},
].forEach(function (test) {
[33/33] ambari git commit: AMBARI-21307 Added unit tests. Improved
logging, refactoring: rename, organized classes into packages
Posted by lp...@apache.org.
AMBARI-21307 Added unit tests. Improved logging, refactoring: rename, organized classes into packages
Project: http://git-wip-us.apache.org/repos/asf/ambari/repo
Commit: http://git-wip-us.apache.org/repos/asf/ambari/commit/d623a21f
Tree: http://git-wip-us.apache.org/repos/asf/ambari/tree/d623a21f
Diff: http://git-wip-us.apache.org/repos/asf/ambari/diff/d623a21f
Branch: refs/heads/feature-branch-AMBARI-21307
Commit: d623a21fe6689bdd57c76dae70462d3f92903e0d
Parents: 36a49d1
Author: lpuskas <lp...@apache.org>
Authored: Fri Oct 13 17:19:41 2017 +0200
Committer: lpuskas <lp...@apache.org>
Committed: Fri Oct 13 17:53:38 2017 +0200
----------------------------------------------------------------------
.../apache/ambari/server/ldap/LdapModule.java | 2 +-
.../AmbariLdapConfigurationProvider.java | 13 +-
.../server/ldap/service/AmbariLdapFacade.java | 2 +-
.../service/LdapConnectionConfigService.java | 4 +-
.../ads/DefaultLdapConfigurationService.java | 38 +++-
.../ads/DefaultLdapConnectionConfigService.java | 116 ++++++++++
.../DefaultLdapConnectionConfigService.java | 116 ----------
.../server/ldap/LdapModuleFunctionalTest.java | 4 +-
...estAmbariAmbariLdapConfigurationFactory.java | 29 ---
.../TestAmbariLdapConfigurationFactory.java | 29 +++
.../ldap/service/AmbariLdapFacadeTest.java | 4 +-
.../DefaultLdapConfigurationServiceTest.java | 221 +++++++++++++++++++
12 files changed, 414 insertions(+), 164 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/ambari/blob/d623a21f/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
index 4abf4e7..67e84dc 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
@@ -25,7 +25,7 @@ import org.apache.ambari.server.ldap.service.LdapConnectionConfigService;
import org.apache.ambari.server.ldap.service.LdapFacade;
import org.apache.ambari.server.ldap.service.ads.DefaultLdapAttributeDetectionService;
import org.apache.ambari.server.ldap.service.ads.DefaultLdapConfigurationService;
-import org.apache.ambari.server.ldap.service.ads.detectors.DefaultLdapConnectionConfigService;
+import org.apache.ambari.server.ldap.service.ads.DefaultLdapConnectionConfigService;
import com.google.inject.AbstractModule;
import com.google.inject.assistedinject.FactoryModuleBuilder;
http://git-wip-us.apache.org/repos/asf/ambari/blob/d623a21f/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapConfigurationProvider.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapConfigurationProvider.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapConfigurationProvider.java
index 9fad896..c88d420 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapConfigurationProvider.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapConfigurationProvider.java
@@ -36,7 +36,8 @@ import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
- * Provider implementation for LDAP configurations. It needs to be registered in the related GUICE module as a provider
+ * Provider implementation for LDAP configurations.
+ * It needs to be registered in the related GUICE module as a provider.
* It's responsible for managing LDAP configurations in the application.
* Whenever requested, this provider returns an AmbariLdapConfiguration which is always in sync with the persisted LDAP
* configuration resource.
@@ -85,15 +86,15 @@ public class AmbariLdapConfigurationProvider implements Provider<AmbariLdapConfi
AmbariConfigurationEntity configEntity = null;
LOGGER.info("Loading LDAP configuration ...");
- if (null != configurationId) {
+ if (null == configurationId) {
- LOGGER.debug("Reloading configuration based on the provied id: {}", configurationId);
- configEntity = ambariConfigurationDAOProvider.get().findByPK(configurationId);
+ LOGGER.debug("Initial loading of the ldap configuration ...");
+ configEntity = ambariConfigurationDAOProvider.get().getLdapConfiguration();
} else {
- LOGGER.debug("Initial loading of the ldap configuration ...");
- configEntity = ambariConfigurationDAOProvider.get().getLdapConfiguration();
+ LOGGER.debug("Reloading configuration based on the provied id: {}", configurationId);
+ configEntity = ambariConfigurationDAOProvider.get().findByPK(configurationId);
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/d623a21f/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
index bbfbc8e..0118840 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
@@ -33,7 +33,7 @@ public class AmbariLdapFacade implements LdapFacade {
/**
* Additional parameters expected to be provided along with the configuration
*/
- protected enum Parameters {
+ public enum Parameters {
TEST_USER_NAME("ambari.ldap.test.user.name"),
TEST_USER_PASSWORD("ambari.ldap.test.user.password");
http://git-wip-us.apache.org/repos/asf/ambari/blob/d623a21f/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConnectionConfigService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConnectionConfigService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConnectionConfigService.java
index e2055bb..a882075 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConnectionConfigService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConnectionConfigService.java
@@ -18,7 +18,9 @@ import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
import org.apache.directory.ldap.client.api.LdapConnectionConfig;
/**
- * Contract for creating connection configuration instances
+ * Contract for creating connection configuration instances.
+ * Implementers are in charge for implementing any required custom logic based on the ambari configuration properties.
+ * (Eg.: using custom key stores etc...)
*/
public interface LdapConnectionConfigService {
http://git-wip-us.apache.org/repos/asf/ambari/blob/d623a21f/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
index 60c1272..d80a636 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
@@ -58,7 +58,7 @@ public class DefaultLdapConfigurationService implements LdapConfigurationService
@Override
public void checkConnection(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
-
+ LOGGER.info("Trying to connect to the LDAP server using provided configuration...");
LdapConnectionTemplate ldapConnectionTemplate = ldapConnectionTemplateFactory.create(ambariLdapConfiguration);
// check if the connection from the connection pool of the template is connected
@@ -74,6 +74,8 @@ public class DefaultLdapConfigurationService implements LdapConfigurationService
throw new AmbariLdapException("Could not connect to the LDAP server. Configuration: " + ambariLdapConfiguration);
}
+ LOGGER.info("Successfully conencted to the LDAP.");
+
}
/**
@@ -92,7 +94,7 @@ public class DefaultLdapConfigurationService implements LdapConfigurationService
public String checkUserAttributes(String testUserName, String testPassword, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
String userDn;
try {
- LOGGER.info("Checking user attributes for user {} r ...", testUserName);
+ LOGGER.info("Checking user attributes for user [{}] ...", testUserName);
// set up a filter based on the provided attributes
String filter = FilterBuilder.and(
@@ -100,10 +102,15 @@ public class DefaultLdapConfigurationService implements LdapConfigurationService
FilterBuilder.equal(ambariLdapConfiguration.userNameAttribute(), testUserName))
.toString();
- LOGGER.info("Searching for the user: {} using the search filter: {}", testUserName, filter);
+ LOGGER.info("Searching for the user: [{}] using the search filter: [{}]", testUserName, filter);
userDn = ldapConnectionTemplateFactory.create(ambariLdapConfiguration).searchFirst(new Dn(ambariLdapConfiguration.userSearchBase()), filter, SearchScope.SUBTREE, getUserDnNameEntryMapper(ambariLdapConfiguration));
- LOGGER.info("Attribute validation succeeded. Filter: {}", filter);
+ if (null == userDn) {
+ LOGGER.info("Could not find user based on the provided configuration. User attributes are not complete ");
+ throw new AmbariLdapException("User attribute configuration incomplete");
+ }
+ LOGGER.info("Attribute validation succeeded. Filter: [{}]", filter);
+
} catch (Exception e) {
@@ -126,7 +133,7 @@ public class DefaultLdapConfigurationService implements LdapConfigurationService
public Set<String> checkGroupAttributes(String userDn, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
List<String> groups = Lists.newArrayList();
try {
- LOGGER.info("Checking group attributes for user dn {} ...", userDn);
+ LOGGER.info("Checking group attributes for user dn: [{}] ...", userDn);
// set up a filter based on the provided attributes
String filter = FilterBuilder.and(
@@ -134,7 +141,7 @@ public class DefaultLdapConfigurationService implements LdapConfigurationService
FilterBuilder.equal(ambariLdapConfiguration.groupMemberAttribute(), userDn)
).toString();
- LOGGER.info("Searching for the groups the user dn: {} is member of using the search filter: {}", userDn, filter);
+ LOGGER.info("Searching for the groups the user dn: [{}] is member of using the search filter: [{}]", userDn, filter);
LdapConnectionTemplate ldapConnectionTemplate = ldapConnectionTemplateFactory.create(ambariLdapConfiguration);
// assemble a search request
@@ -145,6 +152,13 @@ public class DefaultLdapConfigurationService implements LdapConfigurationService
// perform the search
groups = ldapConnectionTemplate.search(searchRequest, getGroupNameEntryMapper(ambariLdapConfiguration));
+ if (groups == null || groups.isEmpty()) {
+ LOGGER.info("No groups found for the user dn. Group attributes configuration is incomplete");
+ throw new AmbariLdapException("Group attribute ldap configuration is incomplete");
+ }
+
+ LOGGER.info("Group attribute configuration check succeeded.");
+
} catch (Exception e) {
LOGGER.error("User attributes validation failed.", e);
@@ -156,6 +170,12 @@ public class DefaultLdapConfigurationService implements LdapConfigurationService
}
+ /**
+ * Entry mapper for handling user search results.
+ *
+ * @param ambariLdapConfiguration ambari ldap configuration values
+ * @return user dn entry mapper instance
+ */
private EntryMapper<String> getGroupNameEntryMapper(AmbariLdapConfiguration ambariLdapConfiguration) {
EntryMapper<String> entryMapper = new EntryMapper<String>() {
@@ -168,6 +188,12 @@ public class DefaultLdapConfigurationService implements LdapConfigurationService
return entryMapper;
}
+ /**
+ * Entry mapper for handling group searches.
+ *
+ * @param ambariLdapConfiguration ambari ldap configuration values
+ * @return
+ */
private EntryMapper<String> getUserDnNameEntryMapper(AmbariLdapConfiguration ambariLdapConfiguration) {
EntryMapper<String> entryMapper = new EntryMapper<String>() {
http://git-wip-us.apache.org/repos/asf/ambari/blob/d623a21f/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConnectionConfigService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConnectionConfigService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConnectionConfigService.java
new file mode 100644
index 0000000..9bc2daf
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConnectionConfigService.java
@@ -0,0 +1,116 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service.ads;
+
+import static javax.net.ssl.TrustManagerFactory.getDefaultAlgorithm;
+
+import java.io.FileInputStream;
+import java.security.KeyStore;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.TrustManagerFactory;
+
+import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.service.AmbariLdapException;
+import org.apache.ambari.server.ldap.service.LdapConnectionConfigService;
+import org.apache.directory.api.util.Strings;
+import org.apache.directory.ldap.client.api.LdapConnectionConfig;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Singleton
+public class DefaultLdapConnectionConfigService implements LdapConnectionConfigService {
+
+ private static Logger LOG = LoggerFactory.getLogger(DefaultLdapConnectionConfigService.class);
+
+ @Inject
+ public DefaultLdapConnectionConfigService() {
+ }
+
+ @Override
+ public LdapConnectionConfig createLdapConnectionConfig(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
+
+ LOG.debug("Assembling ldap connection config based on: {}", ambariLdapConfiguration);
+
+ LdapConnectionConfig config = new LdapConnectionConfig();
+ config.setLdapHost(ambariLdapConfiguration.serverHost());
+ config.setLdapPort(ambariLdapConfiguration.serverPort());
+ config.setName(ambariLdapConfiguration.bindDn());
+ config.setCredentials(ambariLdapConfiguration.bindPassword());
+ config.setUseSsl(ambariLdapConfiguration.useSSL());
+
+ // todo implement proper validation logic here: identify optional/mandatory settings
+ // todo suggest proper naming
+ if ("custom".equals(ambariLdapConfiguration.trustStore())) {
+ LOG.info("Using custom trust manager configuration");
+ config.setTrustManagers(trustManagers(ambariLdapConfiguration));
+ }
+
+
+ return config;
+ }
+
+
+ /**
+ * Configure the trustmanagers to use the custom keystore.
+ *
+ * @param ambariLdapConfiguration congiguration instance holding current values
+ * @return the array of trust managers
+ * @throws AmbariLdapException if an error occurs while setting up the connection
+ */
+ private TrustManager[] trustManagers(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
+ try {
+
+ TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(getDefaultAlgorithm());
+ tmFactory.init(keyStore(ambariLdapConfiguration));
+ return tmFactory.getTrustManagers();
+
+ } catch (Exception e) {
+
+ LOG.error("Failed to initialize trust managers", e);
+ throw new AmbariLdapException(e);
+
+ }
+
+ }
+
+ private KeyStore keyStore(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
+
+ // validating configuration settings
+ if (Strings.isEmpty(ambariLdapConfiguration.trustStoreType())) {
+ throw new AmbariLdapException("Key Store Type must be specified");
+ }
+
+ if (Strings.isEmpty(ambariLdapConfiguration.trustStorePath())) {
+ throw new AmbariLdapException("Key Store Path must be specified");
+ }
+
+ try {
+
+ KeyStore ks = KeyStore.getInstance(ambariLdapConfiguration.trustStoreType());
+ FileInputStream fis = new FileInputStream(ambariLdapConfiguration.trustStorePath());
+ ks.load(fis, ambariLdapConfiguration.trustStorePassword().toCharArray());
+ return ks;
+
+ } catch (Exception e) {
+
+ LOG.error("Failed to create keystore", e);
+ throw new AmbariLdapException(e);
+
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/d623a21f/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/DefaultLdapConnectionConfigService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/DefaultLdapConnectionConfigService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/DefaultLdapConnectionConfigService.java
deleted file mode 100644
index b12cc85..0000000
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/DefaultLdapConnectionConfigService.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.ambari.server.ldap.service.ads.detectors;
-
-import static javax.net.ssl.TrustManagerFactory.getDefaultAlgorithm;
-
-import java.io.FileInputStream;
-import java.security.KeyStore;
-
-import javax.inject.Inject;
-import javax.inject.Singleton;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.TrustManagerFactory;
-
-import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
-import org.apache.ambari.server.ldap.service.AmbariLdapException;
-import org.apache.ambari.server.ldap.service.LdapConnectionConfigService;
-import org.apache.directory.api.util.Strings;
-import org.apache.directory.ldap.client.api.LdapConnectionConfig;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-@Singleton
-public class DefaultLdapConnectionConfigService implements LdapConnectionConfigService {
-
- private static Logger LOG = LoggerFactory.getLogger(DefaultLdapConnectionConfigService.class);
-
- @Inject
- public DefaultLdapConnectionConfigService() {
- }
-
- @Override
- public LdapConnectionConfig createLdapConnectionConfig(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
-
- LOG.debug("Assembling ldap connection config based on: {}", ambariLdapConfiguration);
-
- LdapConnectionConfig config = new LdapConnectionConfig();
- config.setLdapHost(ambariLdapConfiguration.serverHost());
- config.setLdapPort(ambariLdapConfiguration.serverPort());
- config.setName(ambariLdapConfiguration.bindDn());
- config.setCredentials(ambariLdapConfiguration.bindPassword());
- config.setUseSsl(ambariLdapConfiguration.useSSL());
-
- // todo implement proper validation logic here: identify optional/mandatory settings
- // todo suggest proper naming
- if ("custom".equals(ambariLdapConfiguration.trustStore())) {
- LOG.info("Using custom trust manager configuration");
- config.setTrustManagers(trustManagers(ambariLdapConfiguration));
- }
-
-
- return config;
- }
-
-
- /**
- * Configure the trustmanagers to use the custom keystore.
- *
- * @param ambariLdapConfiguration congiguration instance holding current values
- * @return the array of trust managers
- * @throws AmbariLdapException if an error occurs while setting up the connection
- */
- private TrustManager[] trustManagers(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
- try {
-
- TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(getDefaultAlgorithm());
- tmFactory.init(keyStore(ambariLdapConfiguration));
- return tmFactory.getTrustManagers();
-
- } catch (Exception e) {
-
- LOG.error("Failed to initialize trust managers", e);
- throw new AmbariLdapException(e);
-
- }
-
- }
-
- private KeyStore keyStore(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
-
- // validating configuration settings
- if (Strings.isEmpty(ambariLdapConfiguration.trustStoreType())) {
- throw new AmbariLdapException("Key Store Type must be specified");
- }
-
- if (Strings.isEmpty(ambariLdapConfiguration.trustStorePath())) {
- throw new AmbariLdapException("Key Store Path must be specified");
- }
-
- try {
-
- KeyStore ks = KeyStore.getInstance(ambariLdapConfiguration.trustStoreType());
- FileInputStream fis = new FileInputStream(ambariLdapConfiguration.trustStorePath());
- ks.load(fis, ambariLdapConfiguration.trustStorePassword().toCharArray());
- return ks;
-
- } catch (Exception e) {
-
- LOG.error("Failed to create keystore", e);
- throw new AmbariLdapException(e);
-
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/ambari/blob/d623a21f/ambari-server/src/test/java/org/apache/ambari/server/ldap/LdapModuleFunctionalTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/LdapModuleFunctionalTest.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/LdapModuleFunctionalTest.java
index f3f0644..91f4e10 100644
--- a/ambari-server/src/test/java/org/apache/ambari/server/ldap/LdapModuleFunctionalTest.java
+++ b/ambari-server/src/test/java/org/apache/ambari/server/ldap/LdapModuleFunctionalTest.java
@@ -18,7 +18,7 @@ import java.util.Map;
import org.apache.ambari.server.ldap.domain.AmbariLdapConfigKeys;
import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
-import org.apache.ambari.server.ldap.domain.TestAmbariAmbariLdapConfigurationFactory;
+import org.apache.ambari.server.ldap.domain.TestAmbariLdapConfigurationFactory;
import org.apache.ambari.server.ldap.service.LdapConfigurationService;
import org.apache.ambari.server.ldap.service.LdapFacade;
import org.apache.ambari.server.ldap.service.ads.LdapConnectionTemplateFactory;
@@ -47,7 +47,7 @@ public class LdapModuleFunctionalTest {
private static Injector injector;
private static Module testModule;
- private static TestAmbariAmbariLdapConfigurationFactory ldapConfigurationFactory = new TestAmbariAmbariLdapConfigurationFactory();
+ private static TestAmbariLdapConfigurationFactory ldapConfigurationFactory = new TestAmbariLdapConfigurationFactory();
@BeforeClass
public static void beforeClass() throws Exception {
http://git-wip-us.apache.org/repos/asf/ambari/blob/d623a21f/ambari-server/src/test/java/org/apache/ambari/server/ldap/domain/TestAmbariAmbariLdapConfigurationFactory.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/domain/TestAmbariAmbariLdapConfigurationFactory.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/domain/TestAmbariAmbariLdapConfigurationFactory.java
deleted file mode 100644
index 1155494..0000000
--- a/ambari-server/src/test/java/org/apache/ambari/server/ldap/domain/TestAmbariAmbariLdapConfigurationFactory.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.ambari.server.ldap.domain;
-
-
-import java.util.Map;
-
-/**
- * Implementation used for testing purposes only!
- */
-public class TestAmbariAmbariLdapConfigurationFactory implements AmbariLdapConfigurationFactory {
-
- @Override
- public AmbariLdapConfiguration createLdapConfiguration(Map<String, Object> configuration) {
- return new AmbariLdapConfiguration(configuration);
- }
-}
http://git-wip-us.apache.org/repos/asf/ambari/blob/d623a21f/ambari-server/src/test/java/org/apache/ambari/server/ldap/domain/TestAmbariLdapConfigurationFactory.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/domain/TestAmbariLdapConfigurationFactory.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/domain/TestAmbariLdapConfigurationFactory.java
new file mode 100644
index 0000000..aa26498
--- /dev/null
+++ b/ambari-server/src/test/java/org/apache/ambari/server/ldap/domain/TestAmbariLdapConfigurationFactory.java
@@ -0,0 +1,29 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.domain;
+
+
+import java.util.Map;
+
+/**
+ * Implementation used for testing purposes only!
+ */
+public class TestAmbariLdapConfigurationFactory implements AmbariLdapConfigurationFactory {
+
+ @Override
+ public AmbariLdapConfiguration createLdapConfiguration(Map<String, Object> configuration) {
+ return new AmbariLdapConfiguration(configuration);
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/d623a21f/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/AmbariLdapFacadeTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/AmbariLdapFacadeTest.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/AmbariLdapFacadeTest.java
index 8552f86..db0e5a9 100644
--- a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/AmbariLdapFacadeTest.java
+++ b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/AmbariLdapFacadeTest.java
@@ -20,7 +20,7 @@ import java.util.Set;
import org.apache.ambari.server.ldap.domain.AmbariLdapConfigKeys;
import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
import org.apache.ambari.server.ldap.domain.AmbariLdapConfigurationFactory;
-import org.apache.ambari.server.ldap.domain.TestAmbariAmbariLdapConfigurationFactory;
+import org.apache.ambari.server.ldap.domain.TestAmbariLdapConfigurationFactory;
import org.easymock.Capture;
import org.easymock.EasyMock;
import org.easymock.EasyMockRule;
@@ -63,7 +63,7 @@ public class AmbariLdapFacadeTest extends EasyMockSupport {
@Before
public void before() {
- ambariLdapConfigurationFactory = new TestAmbariAmbariLdapConfigurationFactory();
+ ambariLdapConfigurationFactory = new TestAmbariLdapConfigurationFactory();
ambariLdapConfiguration = ambariLdapConfigurationFactory.createLdapConfiguration(Maps.newHashMap());
ambariLdapConfigurationCapture = Capture.newInstance();
http://git-wip-us.apache.org/repos/asf/ambari/blob/d623a21f/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java
new file mode 100644
index 0000000..4d6d2a6
--- /dev/null
+++ b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java
@@ -0,0 +1,221 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service.ads;
+
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.ambari.server.ldap.domain.AmbariLdapConfigKeys;
+import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.domain.TestAmbariLdapConfigurationFactory;
+import org.apache.ambari.server.ldap.service.AmbariLdapException;
+import org.apache.ambari.server.ldap.service.LdapConfigurationService;
+import org.apache.directory.api.ldap.model.message.SearchRequest;
+import org.apache.directory.api.ldap.model.message.SearchRequestImpl;
+import org.apache.directory.api.ldap.model.message.SearchScope;
+import org.apache.directory.api.ldap.model.name.Dn;
+import org.apache.directory.ldap.client.template.ConnectionCallback;
+import org.apache.directory.ldap.client.template.EntryMapper;
+import org.apache.directory.ldap.client.template.LdapConnectionTemplate;
+import org.easymock.EasyMock;
+import org.easymock.EasyMockRule;
+import org.easymock.EasyMockSupport;
+import org.easymock.Mock;
+import org.easymock.MockType;
+import org.easymock.TestSubject;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+
+public class DefaultLdapConfigurationServiceTest extends EasyMockSupport {
+ @Rule
+ public EasyMockRule mocks = new EasyMockRule(this);
+
+ @Mock(type = MockType.STRICT)
+ private LdapConnectionTemplateFactory ldapConnectionTemplateFactory;
+
+ @Mock(type = MockType.STRICT)
+ private LdapConnectionTemplate ldapConnectionTemplateMock;
+
+
+ @TestSubject
+ private LdapConfigurationService ldapConfigurationService = new DefaultLdapConfigurationService();
+
+ @Before
+ public void before() {
+ resetAll();
+ }
+
+ @Test
+ public void testShouldConnectionCheckSucceedWhenConnectionCallbackSucceeds() throws Exception {
+ // GIVEN
+ AmbariLdapConfiguration ambariLdapConfiguration = new TestAmbariLdapConfigurationFactory().createLdapConfiguration(Maps.newHashMap());
+
+ // the cllback returns TRUE
+ EasyMock.expect(ldapConnectionTemplateMock.execute(EasyMock.anyObject(ConnectionCallback.class))).andReturn(Boolean.TRUE);
+ EasyMock.expect(ldapConnectionTemplateFactory.create(ambariLdapConfiguration)).andReturn(ldapConnectionTemplateMock);
+
+ replayAll();
+ // WHEN
+ ldapConfigurationService.checkConnection(ambariLdapConfiguration);
+
+ // THEN
+ // no exceptions are thrown
+
+ }
+
+ @Test(expected = AmbariLdapException.class)
+ public void testShouldConnectionCheckFailWhenConnectionCallbackFails() throws Exception {
+
+ // GIVEN
+ AmbariLdapConfiguration ambariLdapConfiguration = new TestAmbariLdapConfigurationFactory().createLdapConfiguration(Maps.newHashMap());
+
+ // the callback returns FALSE
+ EasyMock.expect(ldapConnectionTemplateMock.execute(EasyMock.anyObject(ConnectionCallback.class))).andReturn(Boolean.FALSE);
+ EasyMock.expect(ldapConnectionTemplateFactory.create(ambariLdapConfiguration)).andReturn(ldapConnectionTemplateMock);
+
+ replayAll();
+ // WHEN
+ ldapConfigurationService.checkConnection(ambariLdapConfiguration);
+
+ // THEN
+ // exception is thrown
+
+ }
+
+ @Test
+ public void testShouldUserAttributeConfigurationCheckSucceedWhenUserDnIsFound() throws Exception {
+ // GIVEN
+ Map<String, Object> configMap = Maps.newHashMap();
+ configMap.put(AmbariLdapConfigKeys.USER_OBJECT_CLASS.key(), "person");
+ configMap.put(AmbariLdapConfigKeys.USER_NAME_ATTRIBUTE.key(), "uid");
+
+ AmbariLdapConfiguration ambariLdapConfiguration = new TestAmbariLdapConfigurationFactory().createLdapConfiguration(configMap);
+
+ // the callback returns FALSE
+ EasyMock.expect(ldapConnectionTemplateFactory.create(ambariLdapConfiguration)).andReturn(ldapConnectionTemplateMock);
+ // users found with dn
+ EasyMock.expect(ldapConnectionTemplateMock.searchFirst(EasyMock.anyObject(Dn.class), EasyMock.anyString(), EasyMock.anyObject(SearchScope.class),
+ EasyMock.anyObject(EntryMapper.class))).andReturn("dn");
+
+ replayAll();
+ // WHEN
+ String userDn = ldapConfigurationService.checkUserAttributes("testUser", "testPassword", ambariLdapConfiguration);
+
+ // THEN
+ Assert.assertEquals("The found userDn is not the expected one", userDn, "dn");
+
+ }
+
+ @Test(expected = AmbariLdapException.class)
+ public void testShouldUserAttributeConfigurationCheckFailWhenNoUsersFound() throws Exception {
+ // GIVEN
+ Map<String, Object> configMap = Maps.newHashMap();
+ configMap.put(AmbariLdapConfigKeys.USER_OBJECT_CLASS.key(), "posixAccount");
+ configMap.put(AmbariLdapConfigKeys.USER_NAME_ATTRIBUTE.key(), "dn");
+
+ AmbariLdapConfiguration ambariLdapConfiguration = new TestAmbariLdapConfigurationFactory().createLdapConfiguration(configMap);
+
+ // the callback returns FALSE
+ EasyMock.expect(ldapConnectionTemplateFactory.create(ambariLdapConfiguration)).andReturn(ldapConnectionTemplateMock);
+
+ // no users found, the returned dn is null
+ EasyMock.expect(ldapConnectionTemplateMock.searchFirst(EasyMock.anyObject(Dn.class), EasyMock.anyString(),
+ EasyMock.anyObject(SearchScope.class),
+ EasyMock.anyObject(EntryMapper.class))).andReturn(null);
+
+ replayAll();
+ // WHEN
+ String userDn = ldapConfigurationService.checkUserAttributes("testUser", "testPassword",
+ ambariLdapConfiguration);
+
+ // THEN
+ Assert.assertEquals("The found userDn is not the expected one", userDn, "dn");
+
+ }
+
+
+ @Test
+ public void testShouldGroupAttributeConfigurationCheckSucceedWhenGroupForUserDnIsFound() throws Exception {
+ // GIVEN
+
+ Map<String, Object> configMap = groupConfigObjectMap();
+
+ SearchRequest sr = new SearchRequestImpl();
+
+ AmbariLdapConfiguration ambariLdapConfiguration = new TestAmbariLdapConfigurationFactory().createLdapConfiguration(configMap);
+
+ // the callback returns FALSE
+ EasyMock.expect(ldapConnectionTemplateFactory.create(ambariLdapConfiguration)).andReturn(ldapConnectionTemplateMock);
+
+ EasyMock.expect(ldapConnectionTemplateMock.newSearchRequest(EasyMock.anyObject(Dn.class), EasyMock.anyString(),
+ EasyMock.anyObject(SearchScope.class))).andReturn(sr);
+
+ EasyMock.expect(ldapConnectionTemplateMock.search(EasyMock.anyObject(SearchRequest.class), EasyMock.anyObject(EntryMapper.class)))
+ .andReturn(Lists.newArrayList("userGroup"));
+
+ replayAll();
+ // WHEN
+ Set<String> userGroups = ldapConfigurationService.checkGroupAttributes("userDn", ambariLdapConfiguration);
+
+ // THEN
+ Assert.assertNotNull("No groups found", userGroups);
+
+ }
+
+
+ @Test(expected = AmbariLdapException.class)
+ public void testShouldGroupAttributeConfigurationCheckFailWhenNoGroupsForUserDnFound() throws Exception {
+ // GIVEN
+
+ Map<String, Object> configMap = groupConfigObjectMap();
+
+ SearchRequest sr = new SearchRequestImpl();
+
+ AmbariLdapConfiguration ambariLdapConfiguration = new TestAmbariLdapConfigurationFactory().createLdapConfiguration(configMap);
+
+ // the callback returns FALSE
+ EasyMock.expect(ldapConnectionTemplateFactory.create(ambariLdapConfiguration)).andReturn(ldapConnectionTemplateMock);
+
+ EasyMock.expect(ldapConnectionTemplateMock.newSearchRequest(EasyMock.anyObject(Dn.class), EasyMock.anyString(),
+ EasyMock.anyObject(SearchScope.class))).andReturn(sr);
+
+ EasyMock.expect(ldapConnectionTemplateMock.search(EasyMock.anyObject(SearchRequest.class), EasyMock.anyObject(EntryMapper.class)))
+ .andReturn(Lists.newArrayList());
+
+ replayAll();
+ // WHEN
+ Set<String> userGroups = ldapConfigurationService.checkGroupAttributes("userDn", ambariLdapConfiguration);
+
+ // THEN
+ Assert.assertNotNull("No groups found", userGroups);
+
+ }
+
+ private Map<String, Object> groupConfigObjectMap() {
+ Map<String, Object> configMap = Maps.newHashMap();
+ configMap.put(AmbariLdapConfigKeys.GROUP_OBJECT_CLASS.key(), "groupOfNames");
+ configMap.put(AmbariLdapConfigKeys.GROUP_SEARCH_BASE.key(), "dc=example,dc=com");
+ configMap.put(AmbariLdapConfigKeys.GROUP_NAME_ATTRIBUTE.key(), "uid");
+ configMap.put(AmbariLdapConfigKeys.GROUP_MEMBER_ATTRIBUTE.key(), "member");
+ return configMap;
+ }
+
+
+}
\ No newline at end of file
[07/33] ambari git commit: Added swagger annotations to the new
endpoint
Posted by lp...@apache.org.
Added swagger annotations to the new endpoint
Project: http://git-wip-us.apache.org/repos/asf/ambari/repo
Commit: http://git-wip-us.apache.org/repos/asf/ambari/commit/53b46279
Tree: http://git-wip-us.apache.org/repos/asf/ambari/tree/53b46279
Diff: http://git-wip-us.apache.org/repos/asf/ambari/diff/53b46279
Branch: refs/heads/feature-branch-AMBARI-21307
Commit: 53b46279fd9f1a2fff59d9471174a9ee9fc72a35
Parents: 4d2425b
Author: Balázs Bence Sári <bs...@hortonworks.com>
Authored: Thu Jul 6 18:36:18 2017 +0200
Committer: lpuskas <lp...@apache.org>
Committed: Fri Oct 13 17:20:48 2017 +0200
----------------------------------------------------------------------
.../AmbariConfigurationRequestSwagger.java | 48 +++++++++++++++
.../AmbariConfigurationResponseSwagger.java | 40 +++++++++++++
.../services/AmbariConfigurationService.java | 62 +++++++++++++++++---
3 files changed, 143 insertions(+), 7 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/ambari/blob/53b46279/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationRequestSwagger.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationRequestSwagger.java b/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationRequestSwagger.java
new file mode 100644
index 0000000..d6714f9
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationRequestSwagger.java
@@ -0,0 +1,48 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.ambari.server.api.services;
+
+import java.util.Map;
+
+import org.apache.ambari.server.controller.ApiModel;
+import org.apache.ambari.server.orm.entities.ConfigurationBaseEntity;
+
+import io.swagger.annotations.ApiModelProperty;
+
+/**
+ * Request data model for {@link org.apache.ambari.server.api.services.AmbariConfigurationService}
+ */
+public interface AmbariConfigurationRequestSwagger extends ApiModel {
+
+ @ApiModelProperty(name = "AmbariConfiguration")
+ AmbariConfigurationRequestInfo getAmbariConfiguration();
+
+ interface AmbariConfigurationRequestInfo {
+ @ApiModelProperty
+ Long getId();
+
+ @ApiModelProperty
+ Map<String, Object> getData();
+
+ @ApiModelProperty
+ String getType();
+
+ @ApiModelProperty
+ Long getVersion();
+
+ @ApiModelProperty(name = "version_tag")
+ String getVersionTag();
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/53b46279/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationResponseSwagger.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationResponseSwagger.java b/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationResponseSwagger.java
new file mode 100644
index 0000000..c55ac1d
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationResponseSwagger.java
@@ -0,0 +1,40 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.ambari.server.api.services;
+
+import java.util.Map;
+
+import org.apache.ambari.server.controller.ApiModel;
+
+import io.swagger.annotations.ApiModelProperty;
+
+/**
+ * Response data model for {@link org.apache.ambari.server.api.services.AmbariConfigurationService}
+ */
+public interface AmbariConfigurationResponseSwagger extends ApiModel {
+
+ @ApiModelProperty(name = "AmbariConfiguration")
+ AmbariConfigurationResponseInfo getAmbariConfigurationResponse();
+
+ interface AmbariConfigurationResponseInfo {
+ @ApiModelProperty
+ Long getId();
+
+ @ApiModelProperty
+ Map<String, Object> getData();
+
+ @ApiModelProperty
+ String getType();
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/53b46279/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationService.java b/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationService.java
index 0fa6e44..0c159b9 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationService.java
@@ -70,9 +70,12 @@ import io.swagger.annotations.ApiResponses;
* </pre>
*/
@Path("/configurations/")
-@Api(value = "/configurations", description = "Endpoint for Ambari configuration related operations")
+@Api(value = "Ambari Configurations", description = "Endpoint for Ambari configuration related operations")
public class AmbariConfigurationService extends BaseService {
+ private static final String AMBARI_CONFIGURATION_REQUEST_TYPE =
+ "org.apache.ambari.server.api.services.AmbariConfigurationRequestSwagger";
+
/**
* Creates an ambari configuration resource.
*
@@ -83,9 +86,10 @@ public class AmbariConfigurationService extends BaseService {
*/
@POST
@Produces(MediaType.TEXT_PLAIN)
- @ApiOperation(value = "Creates an ambari configuration resource")
+ @ApiOperation(value = "Creates an ambari configuration resource",
+ nickname = "AmbariConfigurationService#createAmbariConfiguration")
@ApiImplicitParams({
- @ApiImplicitParam(dataType = "", paramType = PARAM_TYPE_BODY)
+ @ApiImplicitParam(dataType = AMBARI_CONFIGURATION_REQUEST_TYPE, paramType = PARAM_TYPE_BODY)
})
@ApiResponses({
@ApiResponse(code = HttpStatus.SC_CREATED, message = MSG_SUCCESSFUL_OPERATION),
@@ -103,7 +107,26 @@ public class AmbariConfigurationService extends BaseService {
@GET
@Produces(MediaType.TEXT_PLAIN)
- @ApiOperation(value = "Retrieve ambari configuration resources")
+ @ApiOperation(value = "Retrieve all ambari configuration resources",
+ nickname = "AmbariConfigurationService#getAmbariConfigurations",
+ notes = "Returns all Ambari configurations.",
+ response = AmbariConfigurationResponseSwagger.class,
+ responseContainer = RESPONSE_CONTAINER_LIST)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = QUERY_FIELDS, value = QUERY_FILTER_DESCRIPTION,
+ defaultValue = "AmbariConfiguration/data, AmbariConfiguration/id, AmbariConfiguration/type",
+ dataType = DATA_TYPE_STRING, paramType = PARAM_TYPE_QUERY),
+ @ApiImplicitParam(name = QUERY_SORT, value = QUERY_SORT_DESCRIPTION,
+ defaultValue = "AmbariConfiguration/id",
+ dataType = DATA_TYPE_STRING, paramType = PARAM_TYPE_QUERY),
+ @ApiImplicitParam(name = QUERY_PAGE_SIZE, value = QUERY_PAGE_SIZE_DESCRIPTION, defaultValue = DEFAULT_PAGE_SIZE, dataType = DATA_TYPE_INT, paramType = PARAM_TYPE_QUERY),
+ @ApiImplicitParam(name = QUERY_FROM, value = QUERY_FROM_DESCRIPTION, defaultValue = DEFAULT_FROM, dataType = DATA_TYPE_STRING, paramType = PARAM_TYPE_QUERY),
+ @ApiImplicitParam(name = QUERY_TO, value = QUERY_TO_DESCRIPTION, dataType = DATA_TYPE_STRING, paramType = PARAM_TYPE_QUERY)
+ })
+ @ApiResponses(value = {
+ @ApiResponse(code = HttpStatus.SC_OK, message = MSG_SUCCESSFUL_OPERATION),
+ @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = MSG_SERVER_ERROR)
+ })
public Response getAmbariConfigurations(String body, @Context HttpHeaders headers, @Context UriInfo uri) {
return handleRequest(headers, body, uri, Request.Type.GET, createResource(Resource.Type.AmbariConfiguration,
Collections.EMPTY_MAP));
@@ -112,7 +135,18 @@ public class AmbariConfigurationService extends BaseService {
@GET
@Path("{configurationId}")
@Produces(MediaType.TEXT_PLAIN)
- @ApiOperation(value = "Retrieve ambari configuration resource")
+ @ApiOperation(value = "Retrieve the details of an ambari configuration resource",
+ nickname = "AmbariConfigurationService#getAmbariConfiguration",
+ response = AmbariConfigurationResponseSwagger.class)
+ @ApiImplicitParams({
+ @ApiImplicitParam(name = QUERY_FIELDS, value = QUERY_FILTER_DESCRIPTION, defaultValue = "AmbariConfiguration/*",
+ dataType = DATA_TYPE_STRING, paramType = PARAM_TYPE_QUERY)
+ })
+ @ApiResponses(value = {
+ @ApiResponse(code = HttpStatus.SC_OK, message = MSG_SUCCESSFUL_OPERATION),
+ @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = MSG_RESOURCE_NOT_FOUND),
+ @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = MSG_SERVER_ERROR)
+ })
public Response getAmbariConfiguration(String body, @Context HttpHeaders headers, @Context UriInfo uri,
@PathParam("configurationId") String configurationId) {
return handleRequest(headers, body, uri, Request.Type.GET, createResource(Resource.Type.AmbariConfiguration,
@@ -121,7 +155,20 @@ public class AmbariConfigurationService extends BaseService {
@PUT
@Produces(MediaType.TEXT_PLAIN)
- @ApiOperation(value = "Update ambari configuration resources")
+ @ApiOperation(value = "Updates ambari configuration resources - Not implemented yet",
+ nickname = "AmbariConfigurationService#updateAmbariConfiguration")
+ @ApiImplicitParams({
+ @ApiImplicitParam(dataType = AMBARI_CONFIGURATION_REQUEST_TYPE, paramType = PARAM_TYPE_BODY)
+ })
+ @ApiResponses({
+ @ApiResponse(code = HttpStatus.SC_OK, message = MSG_SUCCESSFUL_OPERATION),
+ @ApiResponse(code = HttpStatus.SC_ACCEPTED, message = MSG_REQUEST_ACCEPTED),
+ @ApiResponse(code = HttpStatus.SC_BAD_REQUEST, message = MSG_INVALID_ARGUMENTS),
+ @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = MSG_RESOURCE_NOT_FOUND),
+ @ApiResponse(code = HttpStatus.SC_UNAUTHORIZED, message = MSG_NOT_AUTHENTICATED),
+ @ApiResponse(code = HttpStatus.SC_FORBIDDEN, message = MSG_PERMISSION_DENIED),
+ @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = MSG_SERVER_ERROR),
+ })
public Response updateAmbariConfiguration() {
throw new UnsupportedOperationException("Not yet implemented");
}
@@ -129,7 +176,8 @@ public class AmbariConfigurationService extends BaseService {
@DELETE
@Path("{configurationId}")
@Produces(MediaType.TEXT_PLAIN)
- @ApiOperation(value = "Deletes an ambari configuration resource")
+ @ApiOperation(value = "Deletes an ambari configuration resource",
+ nickname = "AmbariConfigurationService#deleteAmbariConfiguration")
@ApiResponses({
@ApiResponse(code = HttpStatus.SC_OK, message = MSG_SUCCESSFUL_OPERATION),
@ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = MSG_RESOURCE_NOT_FOUND),
[04/33] ambari git commit: AMBARI-22231 Stopping and starting HDFS
component in Ambari will result in Namenode to stay in SAFEMODE (dsen)
Posted by lp...@apache.org.
AMBARI-22231 Stopping and starting HDFS component in Ambari will result in Namenode to stay in SAFEMODE (dsen)
Project: http://git-wip-us.apache.org/repos/asf/ambari/repo
Commit: http://git-wip-us.apache.org/repos/asf/ambari/commit/3a0d168c
Tree: http://git-wip-us.apache.org/repos/asf/ambari/tree/3a0d168c
Diff: http://git-wip-us.apache.org/repos/asf/ambari/diff/3a0d168c
Branch: refs/heads/feature-branch-AMBARI-21307
Commit: 3a0d168c08edf559bc91f3eb76485797f83a6e48
Parents: 8f53bc4
Author: Dmytro Sen <ds...@apache.org>
Authored: Fri Oct 13 15:53:09 2017 +0300
Committer: Dmytro Sen <ds...@apache.org>
Committed: Fri Oct 13 15:53:09 2017 +0300
----------------------------------------------------------------------
.../src/main/resources/stacks/HDP/3.0/role_command_order.json | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/ambari/blob/3a0d168c/ambari-server/src/main/resources/stacks/HDP/3.0/role_command_order.json
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/resources/stacks/HDP/3.0/role_command_order.json b/ambari-server/src/main/resources/stacks/HDP/3.0/role_command_order.json
index 576910f..223eee5 100644
--- a/ambari-server/src/main/resources/stacks/HDP/3.0/role_command_order.json
+++ b/ambari-server/src/main/resources/stacks/HDP/3.0/role_command_order.json
@@ -87,7 +87,7 @@
"PXF_SERVICE_CHECK-SERVICE_CHECK" : ["PXF-START", "HDFS_SERVICE_CHECK-SERVICE_CHECK", "HBASE_SERVICE_CHECK-SERVICE_CHECK", "HIVE_SERVICE_CHECK-SERVICE_CHECK"],
"RANGER_ADMIN-START": ["ZOOKEEPER_SERVER-START", "INFRA_SOLR-START"],
- "RANGER_USERSYNC-START" : ["RANGER_ADMIN-START", "RANGER_KMS_SERVER-START"],
+ "RANGER_USERSYNC-START" : ["RANGER_ADMIN-START"],
"RANGER_KMS_SERVER-START" : ["RANGER_ADMIN-START"],
"RANGER_KMS_SERVICE_CHECK-SERVICE_CHECK" : ["RANGER_KMS_SERVER-START"],
"RANGER_SERVICE_CHECK-SERVICE_CHECK" : ["RANGER_USERSYNC-START", "RANGER_ADMIN-START"],
[12/33] ambari git commit: AMBARI-21307 Draft skimplementation for
the user related ldap config attribute validation
Posted by lp...@apache.org.
AMBARI-21307 Draft skimplementation for the user related ldap config attribute validation
Project: http://git-wip-us.apache.org/repos/asf/ambari/repo
Commit: http://git-wip-us.apache.org/repos/asf/ambari/commit/8d2e1345
Tree: http://git-wip-us.apache.org/repos/asf/ambari/tree/8d2e1345
Diff: http://git-wip-us.apache.org/repos/asf/ambari/diff/8d2e1345
Branch: refs/heads/feature-branch-AMBARI-21307
Commit: 8d2e13451781d4255f5f73a811233a492a6b3e2e
Parents: 1e8cde4
Author: lpuskas <lp...@apache.org>
Authored: Tue Jul 18 17:48:07 2017 +0200
Committer: lpuskas <lp...@apache.org>
Committed: Fri Oct 13 17:20:49 2017 +0200
----------------------------------------------------------------------
ambari-project/pom.xml | 1 +
ambari-server/pom.xml | 5 +
.../AmbariConfigurationRequestSwagger.java | 1 -
.../services/ldap/AmbariConfigurationDTO.java | 67 +++++++
.../ldap/LdapCheckConfigurationRequest.java | 47 +++++
.../api/services/ldap/LdapOperationRequest.java | 18 ++
.../api/services/ldap/LdapRequestInfo.java | 61 +++++++
.../api/services/ldap/LdapRestService.java | 132 ++++++++++++++
.../ambari/server/controller/AmbariServer.java | 3 +-
.../server/controller/ControllerModule.java | 1 +
.../server/ldap/AmbariLdapConfiguration.java | 129 ++++++++++++++
.../server/ldap/LdapConfigurationFactory.java | 21 +++
.../ldap/LdapConfigurationValidatorService.java | 52 ++++++
.../apache/ambari/server/ldap/LdapModule.java | 37 ++++
.../ldap/service/AmbariLdapException.java | 33 ++++
.../server/ldap/service/AmbariLdapFacade.java | 107 +++++++++++
.../ambari/server/ldap/service/LdapFacade.java | 52 ++++++
.../server/ldap/service/LdapSearchService.java | 18 ++
.../ad/AdLdapConfigurationValidatorService.java | 177 +++++++++++++++++++
.../service/ad/LdapConfigurationConverter.java | 50 ++++++
.../api/services/ldap/LDAPServiceTest.java | 85 +++++++++
...AdLdapConfigurationValidatorServiceTest.java | 129 ++++++++++++++
22 files changed, 1224 insertions(+), 2 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/ambari/blob/8d2e1345/ambari-project/pom.xml
----------------------------------------------------------------------
diff --git a/ambari-project/pom.xml b/ambari-project/pom.xml
index 00ba1bc..e4d4423 100644
--- a/ambari-project/pom.xml
+++ b/ambari-project/pom.xml
@@ -31,6 +31,7 @@
<ambari.dir>${project.parent.basedir}</ambari.dir>
<powermock.version>1.6.3</powermock.version>
<jetty.version>8.1.19.v20160209</jetty.version>
+ <ldap-api.version>1.0.0</ldap-api.version>
<checkstyle.version>6.19</checkstyle.version> <!-- last version that does not require Java 8 -->
<swagger.version>1.5.10</swagger.version>
<swagger.maven.plugin.version>3.1.4</swagger.maven.plugin.version>
http://git-wip-us.apache.org/repos/asf/ambari/blob/8d2e1345/ambari-server/pom.xml
----------------------------------------------------------------------
diff --git a/ambari-server/pom.xml b/ambari-server/pom.xml
index e250da7..8d52821 100644
--- a/ambari-server/pom.xml
+++ b/ambari-server/pom.xml
@@ -1689,6 +1689,11 @@
<version>4.2.2</version>
</dependency>
<dependency>
+ <groupId>org.apache.directory.api</groupId>
+ <artifactId>api-all</artifactId>
+ <version>${ldap-api.version}</version>
+ </dependency>
+ <dependency>
<groupId>com.networknt</groupId>
<artifactId>json-schema-validator</artifactId>
<version>0.1.10</version>
http://git-wip-us.apache.org/repos/asf/ambari/blob/8d2e1345/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationRequestSwagger.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationRequestSwagger.java b/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationRequestSwagger.java
index d6714f9..5e8094e 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationRequestSwagger.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationRequestSwagger.java
@@ -16,7 +16,6 @@ package org.apache.ambari.server.api.services;
import java.util.Map;
import org.apache.ambari.server.controller.ApiModel;
-import org.apache.ambari.server.orm.entities.ConfigurationBaseEntity;
import io.swagger.annotations.ApiModelProperty;
http://git-wip-us.apache.org/repos/asf/ambari/blob/8d2e1345/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/AmbariConfigurationDTO.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/AmbariConfigurationDTO.java b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/AmbariConfigurationDTO.java
new file mode 100644
index 0000000..1b134fe
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/AmbariConfigurationDTO.java
@@ -0,0 +1,67 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.api.services.ldap;
+
+import java.util.Collections;
+import java.util.Map;
+import java.util.Set;
+
+public class AmbariConfigurationDTO {
+ private String type;
+ private Set<Map<String, Object>> data = Collections.emptySet();
+ private String versionTag;
+ private Integer version;
+ private long createdTs;
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public Set<Map<String, Object>> getData() {
+ return data;
+ }
+
+ public void setData(Set<Map<String, Object>> data) {
+ this.data = data;
+ }
+
+ public String getVersionTag() {
+ return versionTag;
+ }
+
+ public void setVersionTag(String versionTag) {
+ this.versionTag = versionTag;
+ }
+
+ public Integer getVersion() {
+ return version;
+ }
+
+ public void setVersion(Integer version) {
+ this.version = version;
+ }
+
+ public long getCreatedTs() {
+ return createdTs;
+ }
+
+ public void setCreatedTs(long createdTs) {
+ this.createdTs = createdTs;
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/8d2e1345/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapCheckConfigurationRequest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapCheckConfigurationRequest.java b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapCheckConfigurationRequest.java
new file mode 100644
index 0000000..188f1b9
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapCheckConfigurationRequest.java
@@ -0,0 +1,47 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.api.services.ldap;
+
+
+import com.google.gson.annotations.SerializedName;
+
+public class LdapCheckConfigurationRequest implements LdapOperationRequest {
+
+ @SerializedName("AmbariConfiguration")
+ private AmbariConfigurationDTO ambariConfiguration;
+
+ @SerializedName("RequestInfo")
+ private LdapRequestInfo requestInfo;
+
+ public LdapCheckConfigurationRequest() {
+ }
+
+
+ public AmbariConfigurationDTO getAmbariConfiguration() {
+ return ambariConfiguration;
+ }
+
+ public void setAmbariConfiguration(AmbariConfigurationDTO ambariConfiguration) {
+ this.ambariConfiguration = ambariConfiguration;
+ }
+
+ public LdapRequestInfo getRequestInfo() {
+ return requestInfo;
+ }
+
+ public void setRequestInfo(LdapRequestInfo requestInfo) {
+ this.requestInfo = requestInfo;
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/8d2e1345/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapOperationRequest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapOperationRequest.java b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapOperationRequest.java
new file mode 100644
index 0000000..06f6c40
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapOperationRequest.java
@@ -0,0 +1,18 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.api.services.ldap;
+
+public interface LdapOperationRequest {
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/8d2e1345/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapRequestInfo.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapRequestInfo.java b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapRequestInfo.java
new file mode 100644
index 0000000..eeecfee
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapRequestInfo.java
@@ -0,0 +1,61 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.api.services.ldap;
+
+import java.util.Map;
+
+import org.apache.ambari.server.controller.RequestPostRequest;
+
+/**
+ * Bean holding LDAP request specific request information.
+ */
+public class LdapRequestInfo implements RequestPostRequest.RequestInfo {
+
+ // no-arg costructor facilitating JSON serialization
+ public LdapRequestInfo() {
+ }
+
+ private String action;
+
+ private Map<String, Object> parameters;
+
+ @Override
+ public String getAction() {
+ return action;
+ }
+
+ public void setAction(String action) {
+ this.action = action;
+ }
+
+ public void setParameters(Map<String, Object> parameters) {
+ this.parameters = parameters;
+ }
+
+ @Override
+ public String getCommand() {
+ return null;
+ }
+
+ @Override
+ public RequestPostRequest.OperationLevel getOperationLevel() {
+ return null;
+ }
+
+ @Override
+ public Map<String, Object> getParameters() {
+ return parameters;
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/8d2e1345/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapRestService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapRestService.java b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapRestService.java
new file mode 100644
index 0000000..33b10fa
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapRestService.java
@@ -0,0 +1,132 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.api.services.ldap;
+
+import javax.inject.Inject;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+import org.apache.ambari.annotations.ApiIgnore;
+import org.apache.ambari.server.StaticallyInject;
+import org.apache.ambari.server.api.services.BaseService;
+import org.apache.ambari.server.api.services.Result;
+import org.apache.ambari.server.api.services.ResultImpl;
+import org.apache.ambari.server.api.services.ResultStatus;
+import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.LdapConfigurationFactory;
+import org.apache.ambari.server.ldap.service.LdapFacade;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Endpoint designated to LDAP specific operations.
+ */
+@StaticallyInject
+@Path("/ldap")
+public class LdapRestService extends BaseService {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(LdapRestService.class);
+
+ @Inject
+ private static LdapFacade ldapFacade;
+
+ @Inject
+ private static LdapConfigurationFactory ldapConfigurationFactory;
+
+ @POST
+ @ApiIgnore // until documented
+ @Path("/action") // todo this needs to be moved under the resource
+ @Consumes(MediaType.APPLICATION_JSON)
+ public Response validateConfiguration(LdapCheckConfigurationRequest ldapCheckConfigurationRequest) {
+
+ Result result = new ResultImpl(new ResultStatus(ResultStatus.STATUS.OK));
+ try {
+
+ validateRequest(ldapCheckConfigurationRequest);
+
+ AmbariLdapConfiguration ambariLdapConfiguration = ldapConfigurationFactory.createLdapConfiguration(
+ ldapCheckConfigurationRequest.getAmbariConfiguration().getData().iterator().next());
+
+ switch (ldapCheckConfigurationRequest.getRequestInfo().getAction()) {
+ case "test-connection":
+
+ LOGGER.info("Testing connection to the LDAP server ...");
+ ldapFacade.checkConnection(ambariLdapConfiguration);
+
+ break;
+ case "test-attributes":
+
+ LOGGER.info("Testing LDAP attributes ....");
+ ldapFacade.checkLdapAttibutes(ldapCheckConfigurationRequest.getRequestInfo().getParameters(), ambariLdapConfiguration);
+
+ break;
+ case "detect-attributes":
+
+ LOGGER.info("Detecting LDAP attributes ...");
+ ldapFacade.detectAttributes(ambariLdapConfiguration);
+
+ break;
+ default:
+ LOGGER.warn("No action provided ...");
+ throw new IllegalArgumentException("No request action provided");
+ }
+
+ } catch (Exception e) {
+ result = new ResultImpl(new ResultStatus(ResultStatus.STATUS.BAD_REQUEST, e));
+ }
+
+ return Response.status(result.getStatus().getStatusCode()).entity(getResultSerializer().serialize(result)).build();
+ }
+
+ private void validateRequest(LdapCheckConfigurationRequest ldapCheckConfigurationRequest) {
+ String errMsg;
+
+ if (null == ldapCheckConfigurationRequest) {
+ errMsg = "No ldap configuraiton request provided";
+ LOGGER.error(errMsg);
+ throw new IllegalArgumentException(errMsg);
+ }
+
+ if (null == ldapCheckConfigurationRequest.getRequestInfo()) {
+ errMsg = String.format("No request information provided. Request: [%s]", ldapCheckConfigurationRequest);
+ LOGGER.error(errMsg);
+ throw new IllegalArgumentException(errMsg);
+ }
+
+ if (null == ldapCheckConfigurationRequest.getAmbariConfiguration()
+ || ldapCheckConfigurationRequest.getAmbariConfiguration().getData().size() != 1) {
+ errMsg = String.format("No / Invalid configuration data provided. Request: [%s]", ldapCheckConfigurationRequest);
+ LOGGER.error(errMsg);
+ throw new IllegalArgumentException(errMsg);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/8d2e1345/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariServer.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariServer.java b/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariServer.java
index 8988be0..6ceed4a 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariServer.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/controller/AmbariServer.java
@@ -77,6 +77,7 @@ import org.apache.ambari.server.controller.internal.ViewPermissionResourceProvid
import org.apache.ambari.server.controller.metrics.ThreadPoolEnabledPropertyProvider;
import org.apache.ambari.server.controller.utilities.KerberosChecker;
import org.apache.ambari.server.controller.utilities.KerberosIdentityCleaner;
+import org.apache.ambari.server.ldap.LdapModule;
import org.apache.ambari.server.metrics.system.MetricsService;
import org.apache.ambari.server.orm.GuiceJpaInitializer;
import org.apache.ambari.server.orm.PersistenceType;
@@ -1061,7 +1062,7 @@ public class AmbariServer {
public static void main(String[] args) throws Exception {
logStartup();
- Injector injector = Guice.createInjector(new ControllerModule(), new AuditLoggerModule());
+ Injector injector = Guice.createInjector(new ControllerModule(), new AuditLoggerModule(), new LdapModule());
AmbariServer server = null;
try {
http://git-wip-us.apache.org/repos/asf/ambari/blob/8d2e1345/ambari-server/src/main/java/org/apache/ambari/server/controller/ControllerModule.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/controller/ControllerModule.java b/ambari-server/src/main/java/org/apache/ambari/server/controller/ControllerModule.java
index b79d122..4f30b15 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/controller/ControllerModule.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/controller/ControllerModule.java
@@ -510,6 +510,7 @@ public class ControllerModule extends AbstractModule {
install(new FactoryModuleBuilder().implement(CollectionPersisterService.class, CsvFilePersisterService.class).build(CollectionPersisterServiceFactory.class));
install(new FactoryModuleBuilder().build(ConfigureClusterTaskFactory.class));
+
}
/**
http://git-wip-us.apache.org/repos/asf/ambari/blob/8d2e1345/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
new file mode 100644
index 0000000..519f400
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
@@ -0,0 +1,129 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.ambari.server.ldap;
+
+import java.util.Map;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.inject.assistedinject.Assisted;
+
+/**
+ * This class is an immutable representation of all the LDAP related configurationMap entries.
+ */
+@Singleton
+public class AmbariLdapConfiguration {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(AmbariLdapConfiguration.class);
+
+ /**
+ * Constants representing supported LDAP related property names
+ */
+ public enum LdapConfigProperty {
+ LDAP_CONFIGURED("ambari.ldap.configured"),
+ AUTOMATIC_ATTRIBUTE_DETECTION("ambari.ldap.automatic.attribute.detection"),
+
+ USE_SSL("ambari.ldap.usessl"),
+ LDAP_SERVER_HOST("ambari.ldap.server.host"),
+ LDAP_SERVER_PORT("ambari.ldap.server.port"),
+ BASE_DN("ambari.ldap.base.dn"),
+
+ BIND_ANONIMOUSLY("ambari.ldap.bindanonymously"),
+ MANAGER_DN("ambari.ldap.managerdn"),
+ MANAGER_PASSWORD("ambari.ldap.managerpassword"),
+ USER_OBJECT_CLASS("ambari.ldap.user.object.class"),
+ USER_NAME_ATTRIBUTE("ambari.ldap.user.name.attribute"),
+ USER_SEARCH_BASE("ambari.ldap.user.search.Base"),
+
+ GROUP_OBJECT_CLASS("ambari.ldap.group.object.class"),
+ GROUP_NAME_ATTRIBUTE("ambari.ldap.group.name.attribute"),
+ GROUP_MEMBER_ATTRIBUTE("ambari.ldap.group.member.attribute"),
+ GROUP_SEARCH_BASE("ambari.ldap.group.member.attribute"),
+ DN_ATTRIBUTE("authentication.ldap.dnAttribute");
+
+ private String propertyName;
+
+ LdapConfigProperty(String propertyName) {
+ this.propertyName = propertyName;
+ }
+
+ public String propertyName() {
+ return this.propertyName;
+ }
+ }
+
+ private final Map<String, Object> configurationMap;
+
+ private Object configurationValue(LdapConfigProperty ldapConfigProperty) {
+ Object value = null;
+ if (configurationMap.containsKey(ldapConfigProperty.propertyName)) {
+ value = configurationMap.get(ldapConfigProperty.propertyName);
+ } else {
+ LOGGER.warn("Ldap configuration property [{}] hasn't been set", ldapConfigProperty.propertyName());
+ }
+
+ return value;
+ }
+
+ @Inject
+ public AmbariLdapConfiguration(@Assisted Map<String, Object> configuration) {
+ this.configurationMap = configuration;
+ }
+
+
+ public String ldapServerHost() {
+ return (String) configurationValue(LdapConfigProperty.LDAP_SERVER_HOST);
+ }
+
+ public int ldapServerPort() {
+ return Integer.valueOf((String) configurationValue(LdapConfigProperty.LDAP_SERVER_PORT));
+ }
+
+ public boolean useSSL() {
+ return Boolean.valueOf((String) configurationValue(LdapConfigProperty.USE_SSL));
+ }
+
+ public boolean bindAnonimously() {
+ return Boolean.valueOf((String) configurationValue(LdapConfigProperty.BIND_ANONIMOUSLY));
+ }
+
+ public String managerDn() {
+ return (String) configurationValue(LdapConfigProperty.MANAGER_DN);
+ }
+
+ public String managerPassword() {
+ return (String) configurationValue(LdapConfigProperty.MANAGER_PASSWORD);
+ }
+
+ public boolean automaticAttributeDetection() {
+ return Boolean.valueOf((String) configurationValue(LdapConfigProperty.AUTOMATIC_ATTRIBUTE_DETECTION));
+ }
+
+ public String baseDn() {
+ return (String) configurationValue(LdapConfigProperty.BASE_DN);
+ }
+
+ public String userObjectClass() {
+ return (String) configurationValue(LdapConfigProperty.USER_OBJECT_CLASS);
+ }
+
+ public String userNameAttribute() {
+ return (String) configurationValue(LdapConfigProperty.USER_NAME_ATTRIBUTE);
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/8d2e1345/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationFactory.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationFactory.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationFactory.java
new file mode 100644
index 0000000..bcd6e39
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationFactory.java
@@ -0,0 +1,21 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap;
+
+import java.util.Map;
+
+public interface LdapConfigurationFactory {
+ AmbariLdapConfiguration createLdapConfiguration(Map<String, Object> configuration);
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/8d2e1345/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationValidatorService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationValidatorService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationValidatorService.java
new file mode 100644
index 0000000..4667721
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationValidatorService.java
@@ -0,0 +1,52 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap;
+
+import org.apache.ambari.server.AmbariException;
+import org.apache.ambari.server.ldap.service.AmbariLdapException;
+
+/**
+ * Collection of operations for validating ldap configuration.
+ * It's intended to decouple implementations using different libraries.
+ */
+public interface LdapConfigurationValidatorService {
+
+ /**
+ * Tests the connection based on the provided configuration.
+ *
+ * @param configuration the ambari ldap configuration instance
+ * @throws AmbariLdapException if the connection is not possible
+ */
+ void checkConnection(AmbariLdapConfiguration configuration) throws AmbariLdapException;
+
+ /**
+ * Checks whether the group related LDAP attributes in the configuration are correct.
+ *
+ * @param configuration the configuration instance holding the available properties
+ * @throws AmbariException if the attributes are not valid
+ */
+ void checkGroupAttributes(AmbariLdapConfiguration configuration) throws AmbariException;
+
+ /**
+ * Tries to connect to the LDAP server with the given credentials.
+ * Primarily used for testing the user before performing other operations (eg. attribute detection)s
+ *
+ * @param username the username
+ * @param password the password
+ * @param configuration the available ldap configuration
+ * @throws AmbariException if the connection couldn't be estabilished
+ */
+ void checkUserAttributes(String username, String password, AmbariLdapConfiguration configuration) throws AmbariException;
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/8d2e1345/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
new file mode 100644
index 0000000..625ce8b
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
@@ -0,0 +1,37 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+package org.apache.ambari.server.ldap;
+
+import org.apache.ambari.server.ldap.service.AmbariLdapFacade;
+import org.apache.ambari.server.ldap.service.LdapFacade;
+import org.apache.ambari.server.ldap.service.ad.AdLdapConfigurationValidatorService;
+
+import com.google.inject.AbstractModule;
+import com.google.inject.assistedinject.FactoryModuleBuilder;
+
+/**
+ * GUICE configuration module for setting up LDAP related infrastructure.
+ */
+public class LdapModule extends AbstractModule {
+
+ @Override
+ protected void configure() {
+ bind(LdapFacade.class).to(AmbariLdapFacade.class);
+ bind(LdapConfigurationValidatorService.class).to(AdLdapConfigurationValidatorService.class);
+
+ install(new FactoryModuleBuilder().build(LdapConfigurationFactory.class));
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/8d2e1345/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapException.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapException.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapException.java
new file mode 100644
index 0000000..cb38acc
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapException.java
@@ -0,0 +1,33 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service;
+
+public class AmbariLdapException extends Exception {
+ public AmbariLdapException() {
+ super();
+ }
+
+ public AmbariLdapException(String message) {
+ super(message);
+ }
+
+ public AmbariLdapException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ public AmbariLdapException(Throwable cause) {
+ super(cause);
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/8d2e1345/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
new file mode 100644
index 0000000..abd028a
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
@@ -0,0 +1,107 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+package org.apache.ambari.server.ldap.service;
+
+import java.util.Map;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+import org.apache.ambari.server.AmbariException;
+import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.LdapConfigurationValidatorService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Singleton
+public class AmbariLdapFacade implements LdapFacade {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(AmbariLdapFacade.class);
+
+ private enum Parameters {
+ TEST_USER_NAME("ldap.test.user.name"),
+ TEST_USER_PASSWORD("ldap.test.user.password");
+
+ private String parameterKey;
+
+ Parameters(String parameterKey) {
+ this.parameterKey = parameterKey;
+ }
+
+ private String getParameterKey() {
+ return parameterKey;
+ }
+
+ }
+
+ @Inject
+ private LdapConfigurationValidatorService ldapConfigurationValidatorService;
+
+ @Inject
+ public AmbariLdapFacade() {
+ }
+
+ @Override
+ public void checkConnection(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariException {
+ try {
+ LOGGER.info("Validating LDAP connection related configuration based on: {}", ambariLdapConfiguration);
+ ldapConfigurationValidatorService.checkConnection(ambariLdapConfiguration);
+ } catch (AmbariLdapException e) {
+ LOGGER.error("Validating LDAP connection configuration failed", e);
+ throw new AmbariException("Validating LDAP connection configuration failed", e);
+ }
+ LOGGER.info("Validating LDAP connection related configuration: SUCCESS");
+ }
+
+
+ @Override
+ public void detectAttributes(AmbariLdapConfiguration ambariLdapConfiguration) {
+ LOGGER.info("Detecting LDAP configuration attributes ...");
+ throw new UnsupportedOperationException("Not yet implemented");
+ }
+
+ @Override
+ public void checkLdapAttibutes(Map<String, Object> parameters, AmbariLdapConfiguration ldapConfiguration) throws AmbariException {
+ String userName = getTestUserNameFromParameters(parameters);
+ String testUserPass = getTestUserPasswordFromParameters(parameters);
+
+ if (null == userName) {
+ throw new IllegalArgumentException("No test user available for testing LDAP attributes");
+ }
+
+ LOGGER.info("Testing LDAP attributes with test user: {}", userName);
+ ldapConfigurationValidatorService.checkUserAttributes(userName, testUserPass, ldapConfiguration);
+ }
+
+
+ private String getTestUserNameFromParameters(Map<String, Object> parameters) {
+ return (String) parameterValue(parameters, Parameters.TEST_USER_NAME);
+ }
+
+ private String getTestUserPasswordFromParameters(Map<String, Object> parameters) {
+ return (String) parameterValue(parameters, Parameters.TEST_USER_PASSWORD);
+ }
+
+ private Object parameterValue(Map<String, Object> parameters, Parameters parameter) {
+ Object value = null;
+ if (parameters.containsKey(parameter.getParameterKey())) {
+ value = parameters.get(parameter.getParameterKey());
+ } else {
+ LOGGER.warn("Parameter [{}] is missing from parameters", parameter.getParameterKey());
+ }
+ return value;
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/8d2e1345/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java
new file mode 100644
index 0000000..38553f0
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java
@@ -0,0 +1,52 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service;
+
+import java.util.Map;
+
+import org.apache.ambari.server.AmbariException;
+import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
+
+/**
+ * The contract defining all the operations required by the application when communicating with an arbitrary LDAP server.
+ * This interface is intended to decouple LDAP specific details from the application.
+ */
+public interface LdapFacade {
+
+ /**
+ * Tests the connection to the LDAP server based on the provided configuration.
+ *
+ * @param ambariLdapConfiguration the available ldap related configuration
+ * @throws AmbariException if the connection fails or other problems occur during the operation
+ */
+ void checkConnection(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariException;
+
+
+ /**
+ * Runs the user and group attribute detection algorithms
+ *
+ * @param ambariLdapConfiguration
+ */
+ void detectAttributes(AmbariLdapConfiguration ambariLdapConfiguration);
+
+ /**
+ * Checks user and group related LDAP configuration attributes in the configuration object with the help of the provided parameters
+ *
+ * @param parameters a map of property name and value pairs holding information to facilitate checking the attributes
+ * @param ambariLdapConfiguration configutration instance with available attributes
+ * @throws AmbariException if the attribute checking fails
+ */
+ void checkLdapAttibutes(Map<String, Object> parameters, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariException;
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/8d2e1345/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapSearchService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapSearchService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapSearchService.java
new file mode 100644
index 0000000..f1abc8b
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapSearchService.java
@@ -0,0 +1,18 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service;
+
+public interface LdapSearchService {
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/8d2e1345/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/AdLdapConfigurationValidatorService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/AdLdapConfigurationValidatorService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/AdLdapConfigurationValidatorService.java
new file mode 100644
index 0000000..11e8655
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/AdLdapConfigurationValidatorService.java
@@ -0,0 +1,177 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service.ad;
+
+import java.io.IOException;
+import java.util.List;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+import org.apache.ambari.server.AmbariException;
+import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.LdapConfigurationValidatorService;
+import org.apache.ambari.server.ldap.service.AmbariLdapException;
+import org.apache.directory.api.ldap.model.cursor.EntryCursor;
+import org.apache.directory.api.ldap.model.cursor.SearchCursor;
+import org.apache.directory.api.ldap.model.entry.Entry;
+import org.apache.directory.api.ldap.model.message.SearchScope;
+import org.apache.directory.api.ldap.model.name.Dn;
+import org.apache.directory.ldap.client.api.LdapConnectionConfig;
+import org.apache.directory.ldap.client.api.LdapNetworkConnection;
+import org.apache.directory.ldap.client.api.search.FilterBuilder;
+import org.apache.directory.shared.ldap.constants.SchemaConstants;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.collect.Lists;
+
+/**
+ * Implementation of the validation logic using the Apache Directory API.
+ */
+@Singleton
+public class AdLdapConfigurationValidatorService implements LdapConfigurationValidatorService {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(AdLdapConfigurationValidatorService.class);
+
+ @Inject
+ private LdapConfigurationConverter ldapConfigurationConverter;
+
+ /**
+ * Facilitating the instantiation
+ */
+ @Inject
+ public AdLdapConfigurationValidatorService() {
+ }
+
+ @Override
+ public void checkConnection(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
+ try {
+ LOGGER.info("Testing the connection based on the configuration: {}", ambariLdapConfiguration);
+
+ LdapConnectionConfig connectionConfig = ldapConfigurationConverter.getLdapConnectionConfig(ambariLdapConfiguration);
+ LdapNetworkConnection connection = new LdapNetworkConnection(connectionConfig);
+
+ if (ambariLdapConfiguration.bindAnonimously()) {
+ LOGGER.debug("Binding anonimously ...");
+ connection.bind();
+ } else {
+ LOGGER.debug("Binding with manager DN and manager password ...");
+ connection.bind(ambariLdapConfiguration.managerDn(), ambariLdapConfiguration.managerPassword());
+ }
+
+ if (connection.isConnected()) {
+ LOGGER.info("Successfully connected to the LDAP server.");
+ }
+
+ connection.close();
+
+ } catch (Exception e) {
+ LOGGER.warn("Could not bind to the LDAP server base don the provided configuration ...");
+ throw new AmbariLdapException(e);
+ }
+ }
+
+
+ /**
+ * Checks the user attributes provided in the configuration instance by issuing a search for a (known) test user in the LDAP.
+ * Attributes are considered correct if there is at least one entry found.
+ *
+ * Invalid attributes are signaled by throwing an exception.
+ *
+ * @param username the username
+ * @param password the password
+ * @param ambariLdapConfiguration configuration instance holding ldap configuration details
+ * @throws AmbariException if the attributes are not valid or any errors occurs
+ */
+ @Override
+ public void checkUserAttributes(String username, String password, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariException {
+ LdapNetworkConnection connection = null;
+ SearchCursor searchCursor = null;
+ try {
+ LOGGER.info("Checking user attributes for user {} r ...", username);
+
+ LdapConnectionConfig connectionConfig = ldapConfigurationConverter.getLdapConnectionConfig(ambariLdapConfiguration);
+ connection = new LdapNetworkConnection(connectionConfig);
+
+
+ if (!ambariLdapConfiguration.bindAnonimously()) {
+ LOGGER.debug("Anonimous binding not supported, binding with the manager detailas...");
+ connection.bind(ambariLdapConfiguration.managerDn(), ambariLdapConfiguration.managerPassword());
+ } else {
+ LOGGER.debug("Binding anonimously ...");
+ connection.bind();
+ }
+
+ if (!connection.isConnected()) {
+ LOGGER.error("Not connected to the LDAP server. Connection instance: {}", connection);
+ throw new IllegalStateException("The connection to the LDAP server is not alive");
+ }
+
+ // set up a filter based on the provided attributes
+ String filter = FilterBuilder.and(
+ FilterBuilder.equal(SchemaConstants.OBJECT_CLASS_AT, ambariLdapConfiguration.userObjectClass()),
+ FilterBuilder.equal(ambariLdapConfiguration.userNameAttribute(), username))
+ .toString();
+
+ LOGGER.info("Searching for the user: {} using the search filter: {}", username, filter);
+ EntryCursor entryCursor = connection.search(new Dn(ambariLdapConfiguration.baseDn()), filter, SearchScope.SUBTREE);
+
+ // collecting search result entries
+ List<Entry> users = Lists.newArrayList();
+ for (Entry entry : entryCursor) {
+ users.add(entry);
+ }
+
+ // there should be at least one user found
+ if (users.isEmpty()) {
+ String msg = String.format("There are no users found using the filter: [ %s ]. Try changing the attribute values", filter);
+ LOGGER.error(msg);
+ throw new Exception(msg);
+ }
+
+ LOGGER.info("Attibute validation succeeded. Filter: {}", filter);
+
+ } catch (Exception e) {
+
+ LOGGER.error("Error while checking user attributes.");
+ throw new AmbariException("Error while checking user attributes", e);
+
+ } finally {
+
+ LOGGER.debug("Closing the connection and searchresult ...");
+
+ if (null != searchCursor) {
+ searchCursor.close();
+ }
+
+ if (null != connection) {
+ try {
+ connection.close();
+ } catch (IOException e) {
+ LOGGER.error("Exception occurred while closing the connection", e);
+ }
+ }
+
+ }
+ }
+
+ @Override
+ public void checkGroupAttributes(AmbariLdapConfiguration configuration) throws AmbariException {
+
+ }
+
+
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/8d2e1345/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/LdapConfigurationConverter.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/LdapConfigurationConverter.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/LdapConfigurationConverter.java
new file mode 100644
index 0000000..a8839f1
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/LdapConfigurationConverter.java
@@ -0,0 +1,50 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service.ad;
+
+import javax.inject.Singleton;
+
+import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
+import org.apache.directory.ldap.client.api.LdapConnectionConfig;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Converts between ambari specific ldap types and the 3rd party ldap library
+ */
+@Singleton
+public class LdapConfigurationConverter {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(LdapConfigurationConverter.class);
+
+ /**
+ * Creates a {@link LdapConnectionConfig} instance based on the provided ambari specific configurations
+ *
+ * @param ambariAmbariLdapConfiguration
+ * @return
+ */
+ public LdapConnectionConfig getLdapConnectionConfig(AmbariLdapConfiguration ambariAmbariLdapConfiguration) {
+ LOGGER.debug("Creating a configuration instance based on the ambari configuration: {}", ambariAmbariLdapConfiguration);
+
+ LdapConnectionConfig ldapConnectionConfig = new LdapConnectionConfig();
+ ldapConnectionConfig.setLdapHost(ambariAmbariLdapConfiguration.ldapServerHost());
+ ldapConnectionConfig.setLdapPort(ambariAmbariLdapConfiguration.ldapServerPort());
+ ldapConnectionConfig.setUseSsl(ambariAmbariLdapConfiguration.useSSL());
+
+ //todo set the other values as required
+ return ldapConnectionConfig;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/8d2e1345/ambari-server/src/test/java/org/apache/ambari/server/api/services/ldap/LDAPServiceTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/api/services/ldap/LDAPServiceTest.java b/ambari-server/src/test/java/org/apache/ambari/server/api/services/ldap/LDAPServiceTest.java
new file mode 100644
index 0000000..f20cd1f
--- /dev/null
+++ b/ambari-server/src/test/java/org/apache/ambari/server/api/services/ldap/LDAPServiceTest.java
@@ -0,0 +1,85 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.api.services.ldap;
+
+import org.apache.directory.ldap.client.api.LdapConnection;
+import org.apache.directory.ldap.client.api.LdapConnectionConfig;
+import org.apache.directory.ldap.client.api.LdapNetworkConnection;
+import org.codehaus.jackson.map.ObjectMapper;
+import org.junit.Assert;
+import org.junit.Test;
+
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+public class LDAPServiceTest {
+
+ private static String JSON_STRING = "{\n" +
+ " \"AmbariConfiguration\": {\n" +
+ " \"type\": \"ldap-config\",\n" +
+ " \"data\": [{\n" +
+ " \"authentication.ldap.primaryUrl\": \"localhost:33389\",\n" +
+ " \"authentication.ldap.secondaryUrl\": \"localhost:333\",\n" +
+ " \"authentication.ldap.baseDn\": \"dc=ambari,dc=apache,dc=org\"\n" +
+ " }]\n" +
+ " }\n" +
+ "}";
+
+ @Test
+ public void testJaxRsJsonTransformation() throws Exception {
+ // GIVEN
+ ObjectMapper objectMapper = new ObjectMapper();
+
+ Gson gsonJsonProvider = new GsonBuilder().create();
+
+
+ // WHEN
+ LdapCheckConfigurationRequest ldapCheckConfigurationRequest = gsonJsonProvider.fromJson(JSON_STRING, LdapCheckConfigurationRequest.class);
+ // LdapCheckConfigurationRequest ldapCheckConfigurationRequest = objectMapper.readValue(JSON_STRING, LdapCheckConfigurationRequest.class);
+
+ // THEN
+ Assert.assertNotNull(ldapCheckConfigurationRequest);
+
+ }
+
+
+ @Test
+ public void testLdapConnection() throws Exception {
+ // GIVEN
+ LdapConnection connection = new LdapNetworkConnection("localhost", 389);
+
+ // WHEN
+ connection.bind();
+ // THEN
+
+ }
+
+
+ @Test
+ public void testLdapConnectionConfigs() throws Exception {
+ // GIVEN
+ LdapConnectionConfig config = new LdapConnectionConfig();
+ config.setLdapHost("localhost");
+ config.setLdapPort(389);
+
+ // WHEN
+ LdapConnection connection = new LdapNetworkConnection(config);
+
+ // THEN
+ connection.anonymousBind();
+
+ Assert.assertNotNull(connection);
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/ambari/blob/8d2e1345/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ad/AdLdapConfigurationValidatorServiceTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ad/AdLdapConfigurationValidatorServiceTest.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ad/AdLdapConfigurationValidatorServiceTest.java
new file mode 100644
index 0000000..0f57099
--- /dev/null
+++ b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ad/AdLdapConfigurationValidatorServiceTest.java
@@ -0,0 +1,129 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service.ad;
+
+import static org.junit.Assert.assertNotNull;
+
+import java.util.Map;
+
+import org.apache.ambari.server.AmbariException;
+import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.LdapConfigurationValidatorService;
+import org.apache.directory.api.ldap.model.cursor.EntryCursor;
+import org.apache.directory.api.ldap.model.cursor.SearchCursor;
+import org.apache.directory.api.ldap.model.entry.Entry;
+import org.apache.directory.api.ldap.model.message.Response;
+import org.apache.directory.api.ldap.model.message.SearchRequest;
+import org.apache.directory.api.ldap.model.message.SearchRequestImpl;
+import org.apache.directory.api.ldap.model.message.SearchResultEntry;
+import org.apache.directory.api.ldap.model.message.SearchScope;
+import org.apache.directory.api.ldap.model.name.Dn;
+import org.apache.directory.ldap.client.api.LdapConnection;
+import org.apache.directory.ldap.client.api.LdapConnectionConfig;
+import org.apache.directory.ldap.client.api.LdapNetworkConnection;
+import org.apache.directory.ldap.client.api.search.FilterBuilder;
+import org.apache.directory.shared.ldap.constants.SchemaConstants;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.collect.Maps;
+
+public class AdLdapConfigurationValidatorServiceTest {
+ private static final Logger LOGGER = LoggerFactory.getLogger(AdLdapConfigurationValidatorService.class);
+ private static final String TEST_USER = "Jocika10";
+
+ LdapConfigurationValidatorService ldapConfigurationValidatorService = new AdLdapConfigurationValidatorService();
+
+
+ @Test
+ public void testCheckAttributes() throws Exception {
+
+ // WHEN
+ LdapConnectionConfig config = new LdapConnectionConfig();
+ config.setLdapHost("localhost");
+ config.setLdapPort(389);
+ LdapConnection connection = new LdapNetworkConnection(config);
+
+ // THEN
+ connection.anonymousBind();
+
+
+ EntryCursor cursor = connection.search("dc=dev,dc=local", "(objectclass=*)", SearchScope.ONELEVEL);
+
+ for (Entry entry : cursor) {
+ assertNotNull(entry);
+ System.out.println(entry);
+ }
+
+ cursor.close();
+
+ }
+
+ @Test
+ public void testCheckUserAttributes() throws Exception {
+ Map<String, Object> ldapPropsMap = Maps.newHashMap();
+
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.BIND_ANONIMOUSLY.propertyName(), true);
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.LDAP_SERVER_HOST.propertyName(), "localhost");
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.LDAP_SERVER_PORT.propertyName(), "389");
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.BASE_DN.propertyName(), "dc=dev,dc=local");
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.USER_OBJECT_CLASS.propertyName(), SchemaConstants.PERSON_OC);
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.USER_NAME_ATTRIBUTE.propertyName(), SchemaConstants.UID_AT);
+
+ AmbariLdapConfiguration ambariLdapConfiguration = new AmbariLdapConfiguration(ldapPropsMap);
+
+
+ try {
+ LOGGER.info("Authenticating user {} against the LDAP server ...", TEST_USER);
+ LdapConfigurationConverter ldapConfigurationConverter = new LdapConfigurationConverter();
+
+ LdapConnectionConfig connectionConfig = ldapConfigurationConverter.getLdapConnectionConfig(ambariLdapConfiguration);
+ LdapNetworkConnection connection = new LdapNetworkConnection(connectionConfig);
+
+ String filter = FilterBuilder.and(
+ FilterBuilder.equal(SchemaConstants.OBJECT_CLASS_AT, ambariLdapConfiguration.userObjectClass()),
+ FilterBuilder.equal(ambariLdapConfiguration.userNameAttribute(), TEST_USER))
+ .toString();
+
+ SearchRequest searchRequest = new SearchRequestImpl();
+ searchRequest.setBase(new Dn(ambariLdapConfiguration.baseDn()));
+ searchRequest.setFilter(filter);
+ searchRequest.setScope(SearchScope.SUBTREE);
+
+ LOGGER.info("loking up user: {} based on the filtr: {}", TEST_USER, filter);
+
+ connection.bind();
+ SearchCursor searchCursor = connection.search(searchRequest);
+
+ while (searchCursor.next()) {
+ Response response = searchCursor.get();
+
+ // process the SearchResultEntry
+ if (response instanceof SearchResultEntry) {
+ Entry resultEntry = ((SearchResultEntry) response).getEntry();
+ System.out.println(resultEntry);
+ }
+ }
+
+ searchCursor.close();
+
+ } catch (Exception e) {
+ throw new AmbariException("Error during user authentication check", e);
+ }
+
+ }
+
+}
\ No newline at end of file
[25/33] ambari git commit: AMBARI-21307 Extracted config keys into an
enum. Organized code (created domain package, moved classes)
Posted by lp...@apache.org.
AMBARI-21307 Extracted config keys into an enum. Organized code (created domain package, moved classes)
Project: http://git-wip-us.apache.org/repos/asf/ambari/repo
Commit: http://git-wip-us.apache.org/repos/asf/ambari/commit/38724b92
Tree: http://git-wip-us.apache.org/repos/asf/ambari/tree/38724b92
Diff: http://git-wip-us.apache.org/repos/asf/ambari/diff/38724b92
Branch: refs/heads/feature-branch-AMBARI-21307
Commit: 38724b9211104d752cfed9e684a83f0c22ccb6bb
Parents: a15c4e5
Author: lpuskas <lp...@apache.org>
Authored: Thu Sep 14 16:33:41 2017 +0200
Committer: lpuskas <lp...@apache.org>
Committed: Fri Oct 13 17:20:52 2017 +0200
----------------------------------------------------------------------
.../services/ldap/LdapConfigurationService.java | 4 +-
.../server/ldap/AmbariLdapConfiguration.java | 232 -------------------
.../server/ldap/LdapConfigurationFactory.java | 34 ---
.../apache/ambari/server/ldap/LdapModule.java | 2 +
.../ldap/domain/AmbariLdapConfiguration.java | 180 ++++++++++++++
.../ldap/domain/LdapConfigurationFactory.java | 34 +++
.../ldap/service/AmbariLdapConfigKeys.java | 72 ++++++
.../AmbariLdapConfigurationProvider.java | 4 +-
.../server/ldap/service/AmbariLdapFacade.java | 2 +-
.../service/LdapAttributeDetectionService.java | 2 +-
.../ldap/service/LdapConfigurationService.java | 2 +-
.../ldap/service/LdapConnectionService.java | 2 +-
.../ambari/server/ldap/service/LdapFacade.java | 2 +-
.../DefaultLdapAttributeDetectionService.java | 15 +-
.../ads/DefaultLdapConfigurationService.java | 2 +-
.../ads/DefaultLdapConnectionService.java | 16 +-
...efaultLdapAttributeDetectionServiceTest.java | 21 +-
.../DefaultLdapConfigurationServiceTest.java | 31 +--
18 files changed, 334 insertions(+), 323 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/ambari/blob/38724b92/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationService.java b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationService.java
index ae47a87..ff95066 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationService.java
@@ -46,8 +46,8 @@ import org.apache.ambari.server.api.services.ResultImpl;
import org.apache.ambari.server.api.services.ResultStatus;
import org.apache.ambari.server.controller.internal.ResourceImpl;
import org.apache.ambari.server.controller.spi.Resource;
-import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
-import org.apache.ambari.server.ldap.LdapConfigurationFactory;
+import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.domain.LdapConfigurationFactory;
import org.apache.ambari.server.ldap.service.LdapFacade;
import org.apache.ambari.server.security.authorization.AuthorizationException;
import org.apache.ambari.server.security.authorization.AuthorizationHelper;
http://git-wip-us.apache.org/repos/asf/ambari/blob/38724b92/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
deleted file mode 100644
index 5bdda7a..0000000
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
+++ /dev/null
@@ -1,232 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.ambari.server.ldap;
-
-import java.util.Map;
-
-import javax.inject.Inject;
-import javax.inject.Singleton;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.inject.assistedinject.Assisted;
-
-/**
- * This class is an immutable representation of all the LDAP related configurationMap entries.
- */
-@Singleton
-public class AmbariLdapConfiguration {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(AmbariLdapConfiguration.class);
-
- /**
- * Constants representing supported LDAP related property names
- */
- public enum AmbariLdapConfig {
-
- LDAP_ENABLED("ambari.ldap.authentication.enabled"),
- SERVER_HOST("ambari.ldap.connectivity.server.host"),
- SERVER_PORT("ambari.ldap.connectivity.server.port"),
- USE_SSL("ambari.ldap.connectivity.use_ssl"),
-
- TRUST_STORE("ambari.ldap.connectivity.trust_store"),
- TRUST_STORE_TYPE("ambari.ldap.connectivity.trust_store.type"),
- TRUST_STORE_PATH("ambari.ldap.connectivity.trust_store.path"),
- TRUST_STORE_PASSWORD("ambari.ldap.connectivity.trust_store.password"),
- ANONYMOUS_BIND("ambari.ldap.connectivity.anonymous_bind"),
-
- BIND_DN("ambari.ldap.connectivity.bind_dn"),
- BIND_PASSWORD("ambari.ldap.connectivity.bind_password"),
-
- ATTR_DETECTION("ambari.ldap.attributes.detection"), // manual | auto
-
- DN_ATTRIBUTE("ambari.ldap.attributes.dn_attr"),
-
- USER_OBJECT_CLASS("ambari.ldap.attributes.user.object_class"),
- USER_NAME_ATTRIBUTE("ambari.ldap.attributes.user.name_attr"),
- USER_GROUP_MEMBER_ATTRIBUTE("ambari.ldap.attributes.user.group_member_attr"),
- USER_SEARCH_BASE("ambari.ldap.attributes.user.search_base"),
-
- GROUP_OBJECT_CLASS("ambari.ldap.attributes.group.object_class"),
- GROUP_NAME_ATTRIBUTE("ambari.ldap.attributes.group.name_attr"),
- GROUP_MEMBER_ATTRIBUTE("ambari.ldap.attributes.group.member_attr"),
- GROUP_SEARCH_BASE("ambari.ldap.attributes.group.search_base"),
-
- USER_SEARCH_FILTER("ambari.ldap.advanced.user_search_filter"),
- USER_MEMBER_REPLACE_PATTERN("ambari.ldap.advanced.user_member_replace_pattern"),
- USER_MEMBER_FILTER("ambari.ldap.advanced.user_member_filter"),
-
- GROUP_SEARCH_FILTER("ambari.ldap.advanced.group_search_filter"),
- GROUP_MEMBER_REPLACE_PATTERN("ambari.ldap.advanced.group_member_replace_pattern"),
- GROUP_MEMBER_FILTER("ambari.ldap.advanced.group_member_filter"),
-
- FORCE_LOWERCASE_USERNAMES("ambari.ldap.advanced.force_lowercase_usernames"),
- REFERRAL_HANDLING("ambari.ldap.advanced.referrals"), // folow
- PAGINATION_ENABLED("ambari.ldap.advanced.pagination_enabled"); // true | false
-
- private String propertyName;
-
- AmbariLdapConfig(String propName) {
- this.propertyName = propName;
- }
-
- public String key() {
- return this.propertyName;
- }
- }
-
- private final Map<String, Object> configurationMap;
-
- private Object configValue(AmbariLdapConfig ambariLdapConfig) {
- Object value = null;
- if (configurationMap.containsKey(ambariLdapConfig.key())) {
- value = configurationMap.get(ambariLdapConfig.key());
- } else {
- LOGGER.warn("Ldap configuration property [{}] hasn't been set", ambariLdapConfig.key());
- }
- return value;
- }
-
- public void setValueFor(AmbariLdapConfig ambariLdapConfig, Object value) {
- configurationMap.put(ambariLdapConfig.key(), value);
- }
-
- @Inject
- public AmbariLdapConfiguration(@Assisted Map<String, Object> configuration) {
- this.configurationMap = configuration;
- }
-
- public boolean ldapEnabled() {
- return Boolean.valueOf((String) configValue(AmbariLdapConfig.LDAP_ENABLED));
- }
-
- public String serverHost() {
- return (String) configValue(AmbariLdapConfig.SERVER_HOST);
- }
-
- public int serverPort() {
- return Integer.valueOf((String) configValue(AmbariLdapConfig.SERVER_PORT));
- }
-
- public boolean useSSL() {
- return Boolean.valueOf((String) configValue(AmbariLdapConfig.USE_SSL));
- }
-
- public String trustStore() {
- return (String) configValue(AmbariLdapConfig.TRUST_STORE);
- }
-
- public String trustStoreType() {
- return (String) configValue(AmbariLdapConfig.TRUST_STORE_TYPE);
- }
-
- public String trustStorePath() {
- return (String) configValue(AmbariLdapConfig.TRUST_STORE_PATH);
- }
-
- public String trustStorePassword() {
- return (String) configValue(AmbariLdapConfig.TRUST_STORE_PASSWORD);
- }
-
- public boolean anonymousBind() {
- return Boolean.valueOf((String) configValue(AmbariLdapConfig.ANONYMOUS_BIND));
- }
-
- public String bindDn() {
- return (String) configValue(AmbariLdapConfig.BIND_DN);
- }
-
- public String bindPassword() {
- return (String) configValue(AmbariLdapConfig.BIND_PASSWORD);
- }
-
- public String attributeDetection() {
- return (String) configValue(AmbariLdapConfig.ATTR_DETECTION);
- }
-
- public String dnAttribute() {
- return (String) configValue(AmbariLdapConfig.DN_ATTRIBUTE);
- }
-
- public String userObjectClass() {
- return (String) configValue(AmbariLdapConfig.USER_OBJECT_CLASS);
- }
-
- public String userNameAttribute() {
- return (String) configValue(AmbariLdapConfig.USER_NAME_ATTRIBUTE);
- }
-
- public String userSearchBase() {
- return (String) configValue(AmbariLdapConfig.USER_SEARCH_BASE);
- }
-
- public String groupObjectClass() {
- return (String) configValue(AmbariLdapConfig.GROUP_OBJECT_CLASS);
- }
-
- public String groupNameAttribute() {
- return (String) configValue(AmbariLdapConfig.GROUP_NAME_ATTRIBUTE);
- }
-
- public String groupMemberAttribute() {
- return (String) configValue(AmbariLdapConfig.GROUP_MEMBER_ATTRIBUTE);
- }
-
- public String groupSearchBase() {
- return (String) configValue(AmbariLdapConfig.GROUP_SEARCH_BASE);
- }
-
- public String userSearchFilter() {
- return (String) configValue(AmbariLdapConfig.USER_SEARCH_FILTER);
- }
-
- public String userMemberReplacePattern() {
- return (String) configValue(AmbariLdapConfig.USER_MEMBER_REPLACE_PATTERN);
- }
-
- public String userMemberFilter() {
- return (String) configValue(AmbariLdapConfig.USER_MEMBER_FILTER);
- }
-
- public String groupSearchFilter() {
- return (String) configValue(AmbariLdapConfig.GROUP_SEARCH_FILTER);
- }
-
- public String groupMemberReplacePattern() {
- return (String) configValue(AmbariLdapConfig.GROUP_MEMBER_REPLACE_PATTERN);
- }
-
- public String groupMemberFilter() {
- return (String) configValue(AmbariLdapConfig.GROUP_MEMBER_FILTER);
- }
-
- public boolean forceLowerCaseUserNames() {
- return Boolean.valueOf((String) configValue(AmbariLdapConfig.FORCE_LOWERCASE_USERNAMES));
- }
-
- public boolean paginationEnabled() {
- return Boolean.valueOf((String) configValue(AmbariLdapConfig.PAGINATION_ENABLED));
- }
-
- public String referralHandling() {
- return (String) configValue(AmbariLdapConfig.REFERRAL_HANDLING);
- }
-
-
- @Override
- public String toString() {
- return configurationMap.toString();
- }
-}
http://git-wip-us.apache.org/repos/asf/ambari/blob/38724b92/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationFactory.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationFactory.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationFactory.java
deleted file mode 100644
index 67ac092..0000000
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationFactory.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.ambari.server.ldap;
-
-import java.util.Map;
-
-/**
- * Factory interface for AmbariLdapConfiguration instances.
- * It's registered as a factory in the GUICE context ( so no implementations required)
- *
- * To be extended with other factory methods upon needs.
- */
-public interface LdapConfigurationFactory {
-
- /**
- * Creates an AmbariLdapConfiguration instance with the provided map of configuration settings.
- *
- * @param configuration a map where keys are the configuration properties and values are the configuration values
- * @return an AmbariLdapConfiguration instance
- */
- AmbariLdapConfiguration createLdapConfiguration(Map<String, Object> configuration);
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/ambari/blob/38724b92/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
index 0be69d4..83a73d1 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
@@ -15,6 +15,8 @@
package org.apache.ambari.server.ldap;
+import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.domain.LdapConfigurationFactory;
import org.apache.ambari.server.ldap.service.AmbariLdapConfigurationProvider;
import org.apache.ambari.server.ldap.service.AmbariLdapFacade;
import org.apache.ambari.server.ldap.service.LdapAttributeDetectionService;
http://git-wip-us.apache.org/repos/asf/ambari/blob/38724b92/ambari-server/src/main/java/org/apache/ambari/server/ldap/domain/AmbariLdapConfiguration.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/domain/AmbariLdapConfiguration.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/domain/AmbariLdapConfiguration.java
new file mode 100644
index 0000000..072393a
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/domain/AmbariLdapConfiguration.java
@@ -0,0 +1,180 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+package org.apache.ambari.server.ldap.domain;
+
+import java.util.Map;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+import org.apache.ambari.server.ldap.service.AmbariLdapConfigKeys;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.inject.assistedinject.Assisted;
+
+/**
+ * This class is an immutable representation of all the LDAP related configurationMap entries.
+ */
+@Singleton
+public class AmbariLdapConfiguration {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(AmbariLdapConfiguration.class);
+
+ private final Map<String, Object> configurationMap;
+
+ private Object configValue(AmbariLdapConfigKeys ambariLdapConfigKeys) {
+ Object value = null;
+ if (configurationMap.containsKey(ambariLdapConfigKeys.key())) {
+ value = configurationMap.get(ambariLdapConfigKeys.key());
+ } else {
+ LOGGER.warn("Ldap configuration property [{}] hasn't been set", ambariLdapConfigKeys.key());
+ }
+ return value;
+ }
+
+ public void setValueFor(AmbariLdapConfigKeys ambariLdapConfigKeys, Object value) {
+ configurationMap.put(ambariLdapConfigKeys.key(), value);
+ }
+
+ // intentionally package private, instances to be created through the factory
+ @Inject
+ AmbariLdapConfiguration(@Assisted Map<String, Object> configuration) {
+ this.configurationMap = configuration;
+ }
+
+ public boolean ldapEnabled() {
+ return Boolean.valueOf((String) configValue(AmbariLdapConfigKeys.LDAP_ENABLED));
+ }
+
+ public String serverHost() {
+ return (String) configValue(AmbariLdapConfigKeys.SERVER_HOST);
+ }
+
+ public int serverPort() {
+ return Integer.valueOf((String) configValue(AmbariLdapConfigKeys.SERVER_PORT));
+ }
+
+ public boolean useSSL() {
+ return Boolean.valueOf((String) configValue(AmbariLdapConfigKeys.USE_SSL));
+ }
+
+ public String trustStore() {
+ return (String) configValue(AmbariLdapConfigKeys.TRUST_STORE);
+ }
+
+ public String trustStoreType() {
+ return (String) configValue(AmbariLdapConfigKeys.TRUST_STORE_TYPE);
+ }
+
+ public String trustStorePath() {
+ return (String) configValue(AmbariLdapConfigKeys.TRUST_STORE_PATH);
+ }
+
+ public String trustStorePassword() {
+ return (String) configValue(AmbariLdapConfigKeys.TRUST_STORE_PASSWORD);
+ }
+
+ public boolean anonymousBind() {
+ return Boolean.valueOf((String) configValue(AmbariLdapConfigKeys.ANONYMOUS_BIND));
+ }
+
+ public String bindDn() {
+ return (String) configValue(AmbariLdapConfigKeys.BIND_DN);
+ }
+
+ public String bindPassword() {
+ return (String) configValue(AmbariLdapConfigKeys.BIND_PASSWORD);
+ }
+
+ public String attributeDetection() {
+ return (String) configValue(AmbariLdapConfigKeys.ATTR_DETECTION);
+ }
+
+ public String dnAttribute() {
+ return (String) configValue(AmbariLdapConfigKeys.DN_ATTRIBUTE);
+ }
+
+ public String userObjectClass() {
+ return (String) configValue(AmbariLdapConfigKeys.USER_OBJECT_CLASS);
+ }
+
+ public String userNameAttribute() {
+ return (String) configValue(AmbariLdapConfigKeys.USER_NAME_ATTRIBUTE);
+ }
+
+ public String userSearchBase() {
+ return (String) configValue(AmbariLdapConfigKeys.USER_SEARCH_BASE);
+ }
+
+ public String groupObjectClass() {
+ return (String) configValue(AmbariLdapConfigKeys.GROUP_OBJECT_CLASS);
+ }
+
+ public String groupNameAttribute() {
+ return (String) configValue(AmbariLdapConfigKeys.GROUP_NAME_ATTRIBUTE);
+ }
+
+ public String groupMemberAttribute() {
+ return (String) configValue(AmbariLdapConfigKeys.GROUP_MEMBER_ATTRIBUTE);
+ }
+
+ public String groupSearchBase() {
+ return (String) configValue(AmbariLdapConfigKeys.GROUP_SEARCH_BASE);
+ }
+
+ public String userSearchFilter() {
+ return (String) configValue(AmbariLdapConfigKeys.USER_SEARCH_FILTER);
+ }
+
+ public String userMemberReplacePattern() {
+ return (String) configValue(AmbariLdapConfigKeys.USER_MEMBER_REPLACE_PATTERN);
+ }
+
+ public String userMemberFilter() {
+ return (String) configValue(AmbariLdapConfigKeys.USER_MEMBER_FILTER);
+ }
+
+ public String groupSearchFilter() {
+ return (String) configValue(AmbariLdapConfigKeys.GROUP_SEARCH_FILTER);
+ }
+
+ public String groupMemberReplacePattern() {
+ return (String) configValue(AmbariLdapConfigKeys.GROUP_MEMBER_REPLACE_PATTERN);
+ }
+
+ public String groupMemberFilter() {
+ return (String) configValue(AmbariLdapConfigKeys.GROUP_MEMBER_FILTER);
+ }
+
+ public boolean forceLowerCaseUserNames() {
+ return Boolean.valueOf((String) configValue(AmbariLdapConfigKeys.FORCE_LOWERCASE_USERNAMES));
+ }
+
+ public boolean paginationEnabled() {
+ return Boolean.valueOf((String) configValue(AmbariLdapConfigKeys.PAGINATION_ENABLED));
+ }
+
+ public String referralHandling() {
+ return (String) configValue(AmbariLdapConfigKeys.REFERRAL_HANDLING);
+ }
+
+
+ @Override
+ public String toString() {
+ return configurationMap.toString();
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/38724b92/ambari-server/src/main/java/org/apache/ambari/server/ldap/domain/LdapConfigurationFactory.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/domain/LdapConfigurationFactory.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/domain/LdapConfigurationFactory.java
new file mode 100644
index 0000000..f9a74da
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/domain/LdapConfigurationFactory.java
@@ -0,0 +1,34 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.domain;
+
+import java.util.Map;
+
+/**
+ * Factory interface for AmbariLdapConfiguration instances.
+ * It's registered as a factory in the GUICE context ( so no implementations required)
+ *
+ * To be extended with other factory methods upon needs.
+ */
+public interface LdapConfigurationFactory {
+
+ /**
+ * Creates an AmbariLdapConfiguration instance with the provided map of configuration settings.
+ *
+ * @param configuration a map where keys are the configuration properties and values are the configuration values
+ * @return an AmbariLdapConfiguration instance
+ */
+ AmbariLdapConfiguration createLdapConfiguration(Map<String, Object> configuration);
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/ambari/blob/38724b92/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapConfigKeys.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapConfigKeys.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapConfigKeys.java
new file mode 100644
index 0000000..9cf4e56
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapConfigKeys.java
@@ -0,0 +1,72 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service;
+
+/**
+ * Constants representing supported LDAP related property names
+ * // todo extend this with validation information, description, defaults maybe
+ */
+public enum AmbariLdapConfigKeys {
+
+ LDAP_ENABLED("ambari.ldap.authentication.enabled"),
+ SERVER_HOST("ambari.ldap.connectivity.server.host"),
+ SERVER_PORT("ambari.ldap.connectivity.server.port"),
+ USE_SSL("ambari.ldap.connectivity.use_ssl"),
+
+ TRUST_STORE("ambari.ldap.connectivity.trust_store"),
+ TRUST_STORE_TYPE("ambari.ldap.connectivity.trust_store.type"),
+ TRUST_STORE_PATH("ambari.ldap.connectivity.trust_store.path"),
+ TRUST_STORE_PASSWORD("ambari.ldap.connectivity.trust_store.password"),
+ ANONYMOUS_BIND("ambari.ldap.connectivity.anonymous_bind"),
+
+ BIND_DN("ambari.ldap.connectivity.bind_dn"),
+ BIND_PASSWORD("ambari.ldap.connectivity.bind_password"),
+
+ ATTR_DETECTION("ambari.ldap.attributes.detection"), // manual | auto
+
+ DN_ATTRIBUTE("ambari.ldap.attributes.dn_attr"),
+
+ USER_OBJECT_CLASS("ambari.ldap.attributes.user.object_class"),
+ USER_NAME_ATTRIBUTE("ambari.ldap.attributes.user.name_attr"),
+ USER_GROUP_MEMBER_ATTRIBUTE("ambari.ldap.attributes.user.group_member_attr"),
+ USER_SEARCH_BASE("ambari.ldap.attributes.user.search_base"),
+
+ GROUP_OBJECT_CLASS("ambari.ldap.attributes.group.object_class"),
+ GROUP_NAME_ATTRIBUTE("ambari.ldap.attributes.group.name_attr"),
+ GROUP_MEMBER_ATTRIBUTE("ambari.ldap.attributes.group.member_attr"),
+ GROUP_SEARCH_BASE("ambari.ldap.attributes.group.search_base"),
+
+ USER_SEARCH_FILTER("ambari.ldap.advanced.user_search_filter"),
+ USER_MEMBER_REPLACE_PATTERN("ambari.ldap.advanced.user_member_replace_pattern"),
+ USER_MEMBER_FILTER("ambari.ldap.advanced.user_member_filter"),
+
+ GROUP_SEARCH_FILTER("ambari.ldap.advanced.group_search_filter"),
+ GROUP_MEMBER_REPLACE_PATTERN("ambari.ldap.advanced.group_member_replace_pattern"),
+ GROUP_MEMBER_FILTER("ambari.ldap.advanced.group_member_filter"),
+
+ FORCE_LOWERCASE_USERNAMES("ambari.ldap.advanced.force_lowercase_usernames"),
+ REFERRAL_HANDLING("ambari.ldap.advanced.referrals"), // folow
+ PAGINATION_ENABLED("ambari.ldap.advanced.pagination_enabled"); // true | false
+
+ private String propertyName;
+
+ AmbariLdapConfigKeys(String propName) {
+ this.propertyName = propName;
+ }
+
+ public String key() {
+ return this.propertyName;
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/38724b92/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapConfigurationProvider.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapConfigurationProvider.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapConfigurationProvider.java
index 80ed828..af9f2e7 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapConfigurationProvider.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapConfigurationProvider.java
@@ -23,8 +23,8 @@ import javax.inject.Singleton;
import org.apache.ambari.server.events.AmbariLdapConfigChangedEvent;
import org.apache.ambari.server.events.publishers.AmbariEventPublisher;
-import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
-import org.apache.ambari.server.ldap.LdapConfigurationFactory;
+import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.domain.LdapConfigurationFactory;
import org.apache.ambari.server.orm.dao.AmbariConfigurationDAO;
import org.apache.ambari.server.orm.entities.AmbariConfigurationEntity;
import org.apache.ambari.server.security.authorization.AmbariLdapAuthenticationProvider;
http://git-wip-us.apache.org/repos/asf/ambari/blob/38724b92/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
index 689a072..7a6ad5a 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
@@ -21,7 +21,7 @@ import java.util.Set;
import javax.inject.Inject;
import javax.inject.Singleton;
-import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
http://git-wip-us.apache.org/repos/asf/ambari/blob/38724b92/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapAttributeDetectionService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapAttributeDetectionService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapAttributeDetectionService.java
index 4cfa81e..90e3b8b 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapAttributeDetectionService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapAttributeDetectionService.java
@@ -14,7 +14,7 @@
package org.apache.ambari.server.ldap.service;
-import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
/**
* Contract defining operations to detect user and group attributes.
http://git-wip-us.apache.org/repos/asf/ambari/blob/38724b92/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConfigurationService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConfigurationService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConfigurationService.java
index 06566cc..5c376c9 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConfigurationService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConfigurationService.java
@@ -17,7 +17,7 @@ package org.apache.ambari.server.ldap.service;
import java.util.Set;
import org.apache.ambari.server.AmbariException;
-import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
import org.apache.directory.ldap.client.api.LdapConnection;
/**
http://git-wip-us.apache.org/repos/asf/ambari/blob/38724b92/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConnectionService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConnectionService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConnectionService.java
index b4daeaa..6f1e1ff 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConnectionService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConnectionService.java
@@ -14,7 +14,7 @@
package org.apache.ambari.server.ldap.service;
-import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
import org.apache.directory.ldap.client.api.LdapConnection;
/**
http://git-wip-us.apache.org/repos/asf/ambari/blob/38724b92/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java
index 3ae913c..ef84d1b 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java
@@ -17,7 +17,7 @@ package org.apache.ambari.server.ldap.service;
import java.util.Map;
import java.util.Set;
-import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
/**
* The contract defining all the operations required by the application when communicating with an arbitrary LDAP server.
http://git-wip-us.apache.org/repos/asf/ambari/blob/38724b92/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionService.java
index b499b65..ed24015 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionService.java
@@ -17,7 +17,8 @@ package org.apache.ambari.server.ldap.service.ads;
import javax.inject.Inject;
import javax.inject.Singleton;
-import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.service.AmbariLdapConfigKeys;
import org.apache.ambari.server.ldap.service.AmbariLdapException;
import org.apache.ambari.server.ldap.service.LdapAttributeDetectionService;
import org.apache.ambari.server.ldap.service.ads.detectors.GroupMemberAttrDetector;
@@ -112,9 +113,9 @@ public class DefaultLdapAttributeDetectionService implements LdapAttributeDetect
}
}
- ambariLdapConfiguration.setValueFor(AmbariLdapConfiguration.AmbariLdapConfig.USER_NAME_ATTRIBUTE, userNameAttrDetector.detect());
- ambariLdapConfiguration.setValueFor(AmbariLdapConfiguration.AmbariLdapConfig.USER_OBJECT_CLASS, userObjectClassDetector.detect());
- ambariLdapConfiguration.setValueFor(AmbariLdapConfiguration.AmbariLdapConfig.USER_GROUP_MEMBER_ATTRIBUTE, userGroupMemberAttrDetector.detect());
+ ambariLdapConfiguration.setValueFor(AmbariLdapConfigKeys.USER_NAME_ATTRIBUTE, userNameAttrDetector.detect());
+ ambariLdapConfiguration.setValueFor(AmbariLdapConfigKeys.USER_OBJECT_CLASS, userObjectClassDetector.detect());
+ ambariLdapConfiguration.setValueFor(AmbariLdapConfigKeys.USER_GROUP_MEMBER_ATTRIBUTE, userGroupMemberAttrDetector.detect());
LOGGER.info("Decorated ambari ldap config : [{}]", ambariLdapConfiguration);
@@ -177,9 +178,9 @@ public class DefaultLdapAttributeDetectionService implements LdapAttributeDetect
}
}
- ambariLdapConfiguration.setValueFor(AmbariLdapConfiguration.AmbariLdapConfig.GROUP_NAME_ATTRIBUTE, groupNameAttrDetector.detect());
- ambariLdapConfiguration.setValueFor(AmbariLdapConfiguration.AmbariLdapConfig.GROUP_OBJECT_CLASS, groupObjectClassDetector.detect());
- ambariLdapConfiguration.setValueFor(AmbariLdapConfiguration.AmbariLdapConfig.GROUP_MEMBER_ATTRIBUTE, groupMemberAttrDetector.detect());
+ ambariLdapConfiguration.setValueFor(AmbariLdapConfigKeys.GROUP_NAME_ATTRIBUTE, groupNameAttrDetector.detect());
+ ambariLdapConfiguration.setValueFor(AmbariLdapConfigKeys.GROUP_OBJECT_CLASS, groupObjectClassDetector.detect());
+ ambariLdapConfiguration.setValueFor(AmbariLdapConfigKeys.GROUP_MEMBER_ATTRIBUTE, groupMemberAttrDetector.detect());
LOGGER.info("Decorated ambari ldap config : [{}]", ambariLdapConfiguration);
http://git-wip-us.apache.org/repos/asf/ambari/blob/38724b92/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
index 0a309cd..7214fd3 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
@@ -20,7 +20,7 @@ import java.util.Set;
import javax.inject.Inject;
import javax.inject.Singleton;
-import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
import org.apache.ambari.server.ldap.service.AmbariLdapException;
import org.apache.ambari.server.ldap.service.LdapConfigurationService;
import org.apache.directory.api.ldap.codec.decorators.SearchResultEntryDecorator;
http://git-wip-us.apache.org/repos/asf/ambari/blob/38724b92/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConnectionService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConnectionService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConnectionService.java
index 457e23e..1e9c612 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConnectionService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConnectionService.java
@@ -12,25 +12,11 @@
* limitations under the License.
*/
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
package org.apache.ambari.server.ldap.service.ads;
import javax.inject.Singleton;
-import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
import org.apache.ambari.server.ldap.service.LdapConnectionService;
import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.LdapConnectionConfig;
http://git-wip-us.apache.org/repos/asf/ambari/blob/38724b92/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionServiceTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionServiceTest.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionServiceTest.java
index 3d335bf..2920588 100644
--- a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionServiceTest.java
+++ b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionServiceTest.java
@@ -17,7 +17,8 @@ package org.apache.ambari.server.ldap.service.ads;
import java.util.Map;
-import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.service.AmbariLdapConfigKeys;
import org.apache.ambari.server.ldap.service.LdapConnectionService;
import org.apache.directory.api.ldap.model.constants.SchemaConstants;
import org.apache.directory.ldap.client.api.LdapConnection;
@@ -51,7 +52,7 @@ public class DefaultLdapAttributeDetectionServiceTest {
public void before() {
Map<String, Object> initialProps = Maps.newHashMap();
- initialProps.put(AmbariLdapConfiguration.AmbariLdapConfig.BIND_DN.key(), "");
+ initialProps.put(AmbariLdapConfigKeys.BIND_DN.key(), "");
testLdapConfiguration = new AmbariLdapConfiguration(initialProps);
}
@@ -92,15 +93,15 @@ public class DefaultLdapAttributeDetectionServiceTest {
private Map<String, Object> getTestPropertiesMap() {
Map<String, Object> ldapPropsMap = Maps.newHashMap();
- ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.ANONYMOUS_BIND.key(), "true");
- ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.SERVER_HOST.key(), "ldap.forumsys.com");
- ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.SERVER_PORT.key(), "389");
- ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.BIND_DN.key(), "cn=read-only-admin,dc=example,dc=com");
- ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.BIND_PASSWORD.key(), "password");
- ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.DN_ATTRIBUTE.key(), SchemaConstants.CN_AT);
+ ldapPropsMap.put(AmbariLdapConfigKeys.ANONYMOUS_BIND.key(), "true");
+ ldapPropsMap.put(AmbariLdapConfigKeys.SERVER_HOST.key(), "ldap.forumsys.com");
+ ldapPropsMap.put(AmbariLdapConfigKeys.SERVER_PORT.key(), "389");
+ ldapPropsMap.put(AmbariLdapConfigKeys.BIND_DN.key(), "cn=read-only-admin,dc=example,dc=com");
+ ldapPropsMap.put(AmbariLdapConfigKeys.BIND_PASSWORD.key(), "password");
+ ldapPropsMap.put(AmbariLdapConfigKeys.DN_ATTRIBUTE.key(), SchemaConstants.CN_AT);
- ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.USER_SEARCH_BASE.key(), "dc=example,dc=com");
- ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.GROUP_SEARCH_BASE.key(), "dc=example,dc=com");
+ ldapPropsMap.put(AmbariLdapConfigKeys.USER_SEARCH_BASE.key(), "dc=example,dc=com");
+ ldapPropsMap.put(AmbariLdapConfigKeys.GROUP_SEARCH_BASE.key(), "dc=example,dc=com");
return ldapPropsMap;
http://git-wip-us.apache.org/repos/asf/ambari/blob/38724b92/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java
index 1ba6110..449d003 100644
--- a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java
+++ b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java
@@ -18,7 +18,8 @@ import static org.junit.Assert.assertNotNull;
import java.util.Map;
-import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.service.AmbariLdapConfigKeys;
import org.apache.ambari.server.ldap.service.LdapConfigurationService;
import org.apache.ambari.server.ldap.service.LdapConnectionService;
import org.apache.directory.api.ldap.model.constants.SchemaConstants;
@@ -74,14 +75,14 @@ public class DefaultLdapConfigurationServiceTest {
// GIVEN
Map<String, Object> ldapPropsMap = Maps.newHashMap();
- ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.ANONYMOUS_BIND.key(), "true");
- ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.SERVER_HOST.key(), "ldap.forumsys.com");
- ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.SERVER_PORT.key(), "389");
- ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.BIND_DN.key(), "dc=example,dc=com");
+ ldapPropsMap.put(AmbariLdapConfigKeys.ANONYMOUS_BIND.key(), "true");
+ ldapPropsMap.put(AmbariLdapConfigKeys.SERVER_HOST.key(), "ldap.forumsys.com");
+ ldapPropsMap.put(AmbariLdapConfigKeys.SERVER_PORT.key(), "389");
+ ldapPropsMap.put(AmbariLdapConfigKeys.BIND_DN.key(), "dc=example,dc=com");
- ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.USER_OBJECT_CLASS.key(), SchemaConstants.PERSON_OC);
- ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.USER_NAME_ATTRIBUTE.key(), SchemaConstants.UID_AT);
- ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.USER_SEARCH_BASE.key(), "dc=example,dc=com");
+ ldapPropsMap.put(AmbariLdapConfigKeys.USER_OBJECT_CLASS.key(), SchemaConstants.PERSON_OC);
+ ldapPropsMap.put(AmbariLdapConfigKeys.USER_NAME_ATTRIBUTE.key(), SchemaConstants.UID_AT);
+ ldapPropsMap.put(AmbariLdapConfigKeys.USER_SEARCH_BASE.key(), "dc=example,dc=com");
AmbariLdapConfiguration ambariLdapConfiguration = new AmbariLdapConfiguration(ldapPropsMap);
@@ -96,14 +97,14 @@ public class DefaultLdapConfigurationServiceTest {
// GIVEN
Map<String, Object> ldapPropsMap = Maps.newHashMap();
- ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.ANONYMOUS_BIND.key(), "true");
- ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.SERVER_HOST.key(), "ldap.forumsys.com");
- ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.SERVER_PORT.key(), "389");
- ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.BIND_DN.key(), "dc=example,dc=com");
+ ldapPropsMap.put(AmbariLdapConfigKeys.ANONYMOUS_BIND.key(), "true");
+ ldapPropsMap.put(AmbariLdapConfigKeys.SERVER_HOST.key(), "ldap.forumsys.com");
+ ldapPropsMap.put(AmbariLdapConfigKeys.SERVER_PORT.key(), "389");
+ ldapPropsMap.put(AmbariLdapConfigKeys.BIND_DN.key(), "dc=example,dc=com");
- ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.USER_OBJECT_CLASS.key(), SchemaConstants.PERSON_OC);
- ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.USER_NAME_ATTRIBUTE.key(), SchemaConstants.UID_AT);
- ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.USER_SEARCH_BASE.key(), "dc=example,dc=com");
+ ldapPropsMap.put(AmbariLdapConfigKeys.USER_OBJECT_CLASS.key(), SchemaConstants.PERSON_OC);
+ ldapPropsMap.put(AmbariLdapConfigKeys.USER_NAME_ATTRIBUTE.key(), SchemaConstants.UID_AT);
+ ldapPropsMap.put(AmbariLdapConfigKeys.USER_SEARCH_BASE.key(), "dc=example,dc=com");
AmbariLdapConfiguration ambariLdapConfiguration = new AmbariLdapConfiguration(ldapPropsMap);
[02/33] ambari git commit: AMBARI-22229.Handle upload of
interpreter.json to remote storage in Ambari(Prabhjyot Singh via Venkata
Sairam)
Posted by lp...@apache.org.
AMBARI-22229.Handle upload of interpreter.json to remote storage in Ambari(Prabhjyot Singh via Venkata Sairam)
Project: http://git-wip-us.apache.org/repos/asf/ambari/repo
Commit: http://git-wip-us.apache.org/repos/asf/ambari/commit/a8ba5e61
Tree: http://git-wip-us.apache.org/repos/asf/ambari/tree/a8ba5e61
Diff: http://git-wip-us.apache.org/repos/asf/ambari/diff/a8ba5e61
Branch: refs/heads/feature-branch-AMBARI-21307
Commit: a8ba5e61c50ac92b787d3b2de4cec8d29da92d74
Parents: 0f76c7f
Author: Venkata Sairam <ve...@gmail.com>
Authored: Fri Oct 13 15:22:33 2017 +0530
Committer: Venkata Sairam <ve...@gmail.com>
Committed: Fri Oct 13 15:22:33 2017 +0530
----------------------------------------------------------------------
.../common-services/ZEPPELIN/0.7.0/package/scripts/master.py | 3 ++-
.../src/test/python/stacks/2.6/ZEPPELIN/test_zeppelin_070.py | 8 ++++----
2 files changed, 6 insertions(+), 5 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/ambari/blob/a8ba5e61/ambari-server/src/main/resources/common-services/ZEPPELIN/0.7.0/package/scripts/master.py
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/resources/common-services/ZEPPELIN/0.7.0/package/scripts/master.py b/ambari-server/src/main/resources/common-services/ZEPPELIN/0.7.0/package/scripts/master.py
index a8b1b32..6a84d79 100644
--- a/ambari-server/src/main/resources/common-services/ZEPPELIN/0.7.0/package/scripts/master.py
+++ b/ambari-server/src/main/resources/common-services/ZEPPELIN/0.7.0/package/scripts/master.py
@@ -305,7 +305,8 @@ class Master(Script):
def get_zeppelin_conf_FS_directory(self, params):
hdfs_interpreter_config = params.config['configurations']['zeppelin-config']['zeppelin.config.fs.dir']
- if not hdfs_interpreter_config.startswith("/"):
+ # if it doesn't start from "/" or doesn't contains "://" as in hdfs://, file://, etc then make it a absolute path
+ if not (hdfs_interpreter_config.startswith("/") or '://' in hdfs_interpreter_config):
hdfs_interpreter_config = "/user/" + format("{zeppelin_user}") + "/" + hdfs_interpreter_config
return hdfs_interpreter_config
http://git-wip-us.apache.org/repos/asf/ambari/blob/a8ba5e61/ambari-server/src/test/python/stacks/2.6/ZEPPELIN/test_zeppelin_070.py
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/python/stacks/2.6/ZEPPELIN/test_zeppelin_070.py b/ambari-server/src/test/python/stacks/2.6/ZEPPELIN/test_zeppelin_070.py
index e5d0240..400350c 100644
--- a/ambari-server/src/test/python/stacks/2.6/ZEPPELIN/test_zeppelin_070.py
+++ b/ambari-server/src/test/python/stacks/2.6/ZEPPELIN/test_zeppelin_070.py
@@ -342,7 +342,7 @@ class TestZeppelin070(RMFTestCase):
)
self.assertResourceCalled('HdfsResource',
- '/user/zeppelin/hdfs:///user/zeppelin/conf',
+ 'hdfs:///user/zeppelin/conf',
security_enabled=False,
hadoop_bin_dir='/usr/hdp/2.5.0.0-1235/hadoop/bin',
keytab=UnknownConfigurationMock(),
@@ -368,7 +368,7 @@ class TestZeppelin070(RMFTestCase):
self.assertResourceCalled('HdfsResource',
- '/user/zeppelin/hdfs:///user/zeppelin/conf/interpreter.json',
+ 'hdfs:///user/zeppelin/conf/interpreter.json',
security_enabled=False,
hadoop_bin_dir='/usr/hdp/2.5.0.0-1235/hadoop/bin',
keytab=UnknownConfigurationMock(),
@@ -395,7 +395,7 @@ class TestZeppelin070(RMFTestCase):
)
self.assertResourceCalled('HdfsResource',
- '/user/zeppelin/hdfs:///user/zeppelin/conf/interpreter.json',
+ 'hdfs:///user/zeppelin/conf/interpreter.json',
security_enabled=False,
hadoop_bin_dir='/usr/hdp/2.5.0.0-1235/hadoop/bin',
keytab=UnknownConfigurationMock(),
@@ -421,7 +421,7 @@ class TestZeppelin070(RMFTestCase):
group='zeppelin',
)
- self.assertResourceCalled('HdfsResource', '/user/zeppelin/hdfs:///user/zeppelin/conf/interpreter.json',
+ self.assertResourceCalled('HdfsResource', 'hdfs:///user/zeppelin/conf/interpreter.json',
security_enabled = False,
hadoop_bin_dir = '/usr/hdp/2.5.0.0-1235/hadoop/bin',
keytab = UnknownConfigurationMock(),
[27/33] ambari git commit: AMBARI-21307 Refactor - using the
LdapConnectionTemplate for ldap operations
Posted by lp...@apache.org.
http://git-wip-us.apache.org/repos/asf/ambari/blob/1ecd85c4/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionServiceTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionServiceTest.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionServiceTest.java
deleted file mode 100644
index 878d1f0..0000000
--- a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionServiceTest.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.ambari.server.ldap.service.ads;
-
-
-import java.util.Map;
-
-import org.apache.ambari.server.ldap.domain.AmbariLdapConfigKeys;
-import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
-import org.apache.ambari.server.ldap.domain.TestAmbariLdapConfigurationFactory;
-import org.apache.ambari.server.ldap.service.LdapConnectionService;
-import org.apache.directory.api.ldap.model.constants.SchemaConstants;
-import org.apache.directory.ldap.client.api.LdapConnection;
-import org.easymock.EasyMockRule;
-import org.easymock.TestSubject;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.Maps;
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-
-public class DefaultLdapAttributeDetectionServiceTest {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(DefaultLdapAttributeDetectionServiceTest.class);
-
- @Rule
- public EasyMockRule mocks = new EasyMockRule(this);
-
- private AmbariLdapConfiguration testLdapConfiguration;
- private TestAmbariLdapConfigurationFactory ldapConfigurationFactory = new TestAmbariLdapConfigurationFactory();
-
- private LdapConnection connection;
-
- @TestSubject
- private DefaultLdapAttributeDetectionService attributeDetectionService = new DefaultLdapAttributeDetectionService();
-
- @Before
- public void before() {
-
- Map<String, Object> initialProps = Maps.newHashMap();
- initialProps.put(AmbariLdapConfigKeys.BIND_DN.key(), "");
- testLdapConfiguration = ldapConfigurationFactory.createLdapConfiguration(initialProps);
- }
-
- @Test
- public void testShouldUserNameAttributeBeDetectedWhenSearchReturnsValidUsers() throws Exception {
- // GIVEN
-// a set of entries returned from the LDAP search
-
- // WHEN
- AmbariLdapConfiguration ambariLdapConfiguration = attributeDetectionService.detectLdapUserAttributes(connection, testLdapConfiguration);
-
- // THEN
- Assert.assertNotNull(ambariLdapConfiguration);
- Assert.assertEquals("The username attribute is not the expected", "uid", ambariLdapConfiguration.userNameAttribute());
-
- }
-
-
- @Test
- public void functionalTest() throws Exception {
- // GIVEN
- AmbariLdapConfiguration ambariLdapConfiguration = ldapConfigurationFactory.createLdapConfiguration(getTestPropertiesMap());
- LdapConnectionService connectionService = new DefaultLdapConnectionService();
- LdapConnection ldapConnection = connectionService.createLdapConnection(ambariLdapConfiguration);
-
- // WHEN
- AmbariLdapConfiguration config = attributeDetectionService.detectLdapUserAttributes(ldapConnection, ambariLdapConfiguration);
- config = attributeDetectionService.detectLdapGroupAttributes(ldapConnection, ambariLdapConfiguration);
-
- Gson gson = new GsonBuilder().create();
- LOGGER.info(gson.toJson(config));
-
- // THEN
- ldapConnection.close();
-
- }
-
- private Map<String, Object> getTestPropertiesMap() {
- Map<String, Object> ldapPropsMap = Maps.newHashMap();
-
- ldapPropsMap.put(AmbariLdapConfigKeys.ANONYMOUS_BIND.key(), "true");
- ldapPropsMap.put(AmbariLdapConfigKeys.SERVER_HOST.key(), "ldap.forumsys.com");
- ldapPropsMap.put(AmbariLdapConfigKeys.SERVER_PORT.key(), "389");
- ldapPropsMap.put(AmbariLdapConfigKeys.BIND_DN.key(), "cn=read-only-admin,dc=example,dc=com");
- ldapPropsMap.put(AmbariLdapConfigKeys.BIND_PASSWORD.key(), "password");
- ldapPropsMap.put(AmbariLdapConfigKeys.DN_ATTRIBUTE.key(), SchemaConstants.CN_AT);
-
- ldapPropsMap.put(AmbariLdapConfigKeys.USER_SEARCH_BASE.key(), "dc=example,dc=com");
- ldapPropsMap.put(AmbariLdapConfigKeys.GROUP_SEARCH_BASE.key(), "dc=example,dc=com");
-
- return ldapPropsMap;
-
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/ambari/blob/1ecd85c4/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java
deleted file mode 100644
index 2844054..0000000
--- a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.ambari.server.ldap.service.ads;
-
-import static org.junit.Assert.assertNotNull;
-
-import java.util.Map;
-
-import org.apache.ambari.server.ldap.domain.AmbariLdapConfigKeys;
-import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
-import org.apache.ambari.server.ldap.domain.TestAmbariLdapConfigurationFactory;
-import org.apache.ambari.server.ldap.service.LdapConfigurationService;
-import org.apache.ambari.server.ldap.service.LdapConnectionService;
-import org.apache.directory.api.ldap.model.constants.SchemaConstants;
-import org.apache.directory.api.ldap.model.cursor.EntryCursor;
-import org.apache.directory.api.ldap.model.entry.Entry;
-import org.apache.directory.api.ldap.model.message.SearchScope;
-import org.apache.directory.ldap.client.api.LdapConnection;
-import org.apache.directory.ldap.client.api.LdapConnectionConfig;
-import org.apache.directory.ldap.client.api.LdapNetworkConnection;
-import org.apache.directory.ldap.client.api.search.FilterBuilder;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.Maps;
-
-public class DefaultLdapConfigurationServiceTest {
- private static final Logger LOGGER = LoggerFactory.getLogger(DefaultLdapConfigurationService.class);
- private static final String TEST_USER = "einstein";
-
- private TestAmbariLdapConfigurationFactory ldapConfigurationFactory = new TestAmbariLdapConfigurationFactory();
-
- LdapConfigurationService ldapConfigurationService = new DefaultLdapConfigurationService();
-
-
- @Test
- public void testCheckAttributes() throws Exception {
-
- // WHEN
- LdapConnectionConfig config = new LdapConnectionConfig();
- config.setLdapHost("172.22.112.167");
- config.setLdapPort(389);
- LdapConnection connection = new LdapNetworkConnection(config);
-
- // THEN
- connection.bind("CN=Robert Levas,CN=Users,DC=HWQE,DC=HORTONWORKS,DC=COM", "Hadoop1234");
-
- String filter = FilterBuilder.and(
- FilterBuilder.equal(SchemaConstants.OBJECT_CLASS_AT, "person"),
- FilterBuilder.equal("name", "User1 Levas")).toString();
-
- EntryCursor cursor = connection.search("OU=levas,DC=hwqe,DC=hortonworks,DC=com", filter, SearchScope.SUBTREE);
-
- for (Entry entry : cursor) {
- assertNotNull(entry);
- System.out.println(entry);
- }
-
- cursor.close();
-
- }
-
- @Test
- public void testCheckUserAttributes() throws Exception {
- // GIVEN
- Map<String, Object> ldapPropsMap = Maps.newHashMap();
-
- ldapPropsMap.put(AmbariLdapConfigKeys.ANONYMOUS_BIND.key(), "true");
- ldapPropsMap.put(AmbariLdapConfigKeys.SERVER_HOST.key(), "ldap.forumsys.com");
- ldapPropsMap.put(AmbariLdapConfigKeys.SERVER_PORT.key(), "389");
- ldapPropsMap.put(AmbariLdapConfigKeys.BIND_DN.key(), "dc=example,dc=com");
-
- ldapPropsMap.put(AmbariLdapConfigKeys.USER_OBJECT_CLASS.key(), SchemaConstants.PERSON_OC);
- ldapPropsMap.put(AmbariLdapConfigKeys.USER_NAME_ATTRIBUTE.key(), SchemaConstants.UID_AT);
- ldapPropsMap.put(AmbariLdapConfigKeys.USER_SEARCH_BASE.key(), "dc=example,dc=com");
-
-
- AmbariLdapConfiguration ambariLdapConfiguration = ldapConfigurationFactory.createLdapConfiguration(ldapPropsMap);
- LdapConnectionService connectionService = new DefaultLdapConnectionService();
- LdapConnection ldapConnection = connectionService.createLdapConnection(ambariLdapConfiguration);
-
- ldapConfigurationService.checkUserAttributes(ldapConnection, "einstein", "", ambariLdapConfiguration);
- }
-
- @Test
- public void testRetrieveGorupsForuser() throws Exception {
- // GIVEN
- Map<String, Object> ldapPropsMap = Maps.newHashMap();
-
- ldapPropsMap.put(AmbariLdapConfigKeys.ANONYMOUS_BIND.key(), "true");
- ldapPropsMap.put(AmbariLdapConfigKeys.SERVER_HOST.key(), "ldap.forumsys.com");
- ldapPropsMap.put(AmbariLdapConfigKeys.SERVER_PORT.key(), "389");
- ldapPropsMap.put(AmbariLdapConfigKeys.BIND_DN.key(), "dc=example,dc=com");
-
- ldapPropsMap.put(AmbariLdapConfigKeys.USER_OBJECT_CLASS.key(), SchemaConstants.PERSON_OC);
- ldapPropsMap.put(AmbariLdapConfigKeys.USER_NAME_ATTRIBUTE.key(), SchemaConstants.UID_AT);
- ldapPropsMap.put(AmbariLdapConfigKeys.USER_SEARCH_BASE.key(), "dc=example,dc=com");
-
-
- AmbariLdapConfiguration ambariLdapConfiguration = ldapConfigurationFactory.createLdapConfiguration(ldapPropsMap);
- LdapConnectionService connectionService = new DefaultLdapConnectionService();
- LdapConnection ldapConnection = connectionService.createLdapConnection(ambariLdapConfiguration);
-
- ldapConfigurationService.checkGroupAttributes(ldapConnection, "uid=einstein,dc=example,dc=com", ambariLdapConfiguration);
- }
-
- @Test
- public void testListSupportedProperties(){
- StringBuilder sb = new StringBuilder().append(System.lineSeparator());
- for (AmbariLdapConfigKeys configKey : AmbariLdapConfigKeys.values()) {
- sb.append(configKey.key()).append(System.lineSeparator());
- }
- LOGGER.info(sb.toString());
-
- }
-}
\ No newline at end of file
[19/33] ambari git commit: AMBARI-21307 Added the supported ldap
properties to the code. Refactored existing code relying on these properties
Posted by lp...@apache.org.
AMBARI-21307 Added the supported ldap properties to the code. Refactored existing code relying on these properties
Project: http://git-wip-us.apache.org/repos/asf/ambari/repo
Commit: http://git-wip-us.apache.org/repos/asf/ambari/commit/3800adf6
Tree: http://git-wip-us.apache.org/repos/asf/ambari/tree/3800adf6
Diff: http://git-wip-us.apache.org/repos/asf/ambari/diff/3800adf6
Branch: refs/heads/feature-branch-AMBARI-21307
Commit: 3800adf622800844803b5b12b92324994ddee748
Parents: 12be829
Author: lpuskas <lp...@apache.org>
Authored: Fri Sep 8 13:57:25 2017 +0300
Committer: lpuskas <lp...@apache.org>
Committed: Fri Oct 13 17:20:51 2017 +0200
----------------------------------------------------------------------
.../server/ldap/AmbariLdapConfiguration.java | 189 ++++++++++++-------
.../AmbariLdapConfigurationProvider.java | 6 +-
.../server/ldap/service/AmbariLdapFacade.java | 10 +-
.../service/LdapAttributeDetectionService.java | 43 +++++
.../ambari/server/ldap/service/LdapFacade.java | 2 +-
.../ads/DefaultAttributeDetectionService.java | 47 +++++
.../ads/DefaultLdapConfigurationService.java | 4 +-
.../ads/DefaultLdapConnectionService.java | 4 +-
.../DefaultAttributeDetectionServiceTest.java | 102 ++++++++++
.../DefaultLdapConfigurationServiceTest.java | 30 ++-
10 files changed, 348 insertions(+), 89 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/ambari/blob/3800adf6/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
index e913e77..76faeed 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
@@ -34,63 +34,67 @@ public class AmbariLdapConfiguration {
/**
* Constants representing supported LDAP related property names
*/
- public enum LdapConfigProperty {
- LDAP_CONFIGURED("ambari.ldap.configured"),
- AUTOMATIC_ATTRIBUTE_DETECTION("ambari.ldap.automatic.attribute.detection"),
- USE_SSL("ambari.ldap.usessl"),
- LDAP_SERVER_HOST("ambari.ldap.server.host"),
- LDAP_SERVER_PORT("ambari.ldap.server.port"),
- LDAP_TRUSTSTORE("ambari.ldap.truststore"),
- LDAP_TRUSTSTORE_TYPE("ambari.ldap.truststore.type"),
- LDAP_TRUSTSTORE_PATH("ambari.ldap.truststore.path"),
- LDAP_TRUSTSTORE_PASSWORD("ambari.ldap.truststore.password"),
- BASE_DN("ambari.ldap.bind.dn"),
- REFERRAL("ambari.ldap.referral"),
- PAGINATION_ENABLED("ambari.ldap.pagination.enabled"),
-
- BIND_ANONIMOUSLY("ambari.ldap.bindanonymously"),
- MANAGER_DN("ambari.ldap.managerdn"),
- MANAGER_PASSWORD("ambari.ldap.managerpassword"),
- USER_OBJECT_CLASS("ambari.ldap.user.object.class"),
- USER_NAME_ATTRIBUTE("ambari.ldap.user.name.attribute"),
- USER_NAME_FORCE_LOWERCASE("ambari.ldap.username.force.lowercase"),
- USER_SEARCH_BASE("ambari.ldap.user.search.base"),
- SYNC_USER_MEMBER_REPLACE_PATTERN("ambari.ldap.sync.user.member.replacepattern"),
- SYNC_USER_MEMBER_FILTER("ambari.ldap.sync.user.member_filter"),
-
- ADMIN_GROUP_MAPPING_RULES ("ambari.ldap.admin.group.mappingrules"),
- GROUP_OBJECT_CLASS("ambari.ldap.group.object.class"),
- GROUP_NAME_ATTRIBUTE("ambari.ldap.group.name.attribute"),
- GROUP_MEMBER_ATTRIBUTE("ambari.ldap.group.member.attribute"),
- GROUP_SEARCH_BASE("ambari.ldap.group.search.base"),
- SYNC_GROUP_MEMBER_REPLACE_PATTERN("ambari.ldap.sync.group.member.replacepattern"),
- SYNC_GROUP_MEMBER_FILTER("ambari.ldap.sync.group.member_filter"),
- DN_ATTRIBUTE("authentication.ldap.dnAttribute"),
-
- TEST_USER_NAME("ambari.ldap.test.user.name"),
- TEST_USER_PASSWORD("ambari.ldap.test.user.password");
+ public enum AmbariLdapConfig {
+
+ LDAP_ENABLED("ambari.ldap.authentication.enabled"),
+ SERVER_HOST("ambari.ldap.connectivity.server.host"),
+ SERVER_PORT("ambari.ldap.connectivity.server.port"),
+ USE_SSL("ambari.ldap.connectivity.use_ssl"),
+
+ TRUST_STORE("ambari.ldap.connectivity.trust_store"),
+ TRUST_STORE_TYPE("ambari.ldap.connectivity.trust_store.type"),
+ TRUST_STORE_PATH("ambari.ldap.connectivity.trust_store.path"),
+ TRUST_STORE_PASSWORD("ambari.ldap.connectivity.trust_store.password"),
+ ANONYMOUS_BIND("ambari.ldap.connectivity.anonymous_bind"),
+
+ BIND_DN("ambari.ldap.connectivity.bind_dn"),
+ BIND_PASSWORD("ambari.ldap.connectivity.bind_password"),
+
+ ATTR_DETECTION("ambari.ldap.attributes.detection"), // manual | auto
+
+ DN_ATTRIBUTE("ambari.ldap.attributes.dn_attr"),
+
+ USER_OBJECT_CLASS("ambari.ldap.attributes.user.object_class"),
+ USER_NAME_ATTRIBUTE("ambari.ldap.attributes.user.name_attr"),
+ USER_SEARCH_BASE("ambari.ldap.attributes.user.search_base"),
+
+ GROUP_OBJECT_CLASS("ambari.ldap.attributes.group.object_class"),
+ GROUP_NAME_ATTRIBUTE("ambari.ldap.attributes.group.name_attr"),
+ GROUP_MEMBER_ATTRIBUTE("ambari.ldap.attributes.group.member_attr"),
+ GROUP_SEARCH_BASE("ambari.ldap.attributes.user.search_base"),
+
+ USER_SEARCH_FILTER("ambari.ldap.advanced.user_search_filter"),
+ USER_MEMBER_REPLACE_PATTERN("ambari.ldap.advanced.user_member_replace_pattern"),
+ USER_MEMBER_FILTER("ambari.ldap.advanced.user_member_filter"),
+
+ GROUP_SEARCH_FILTER("ambari.ldap.advanced.group_search_filter"),
+ GROUP_MEMBER_REPLACE_PATTERN("ambari.ldap.advanced.group_member_replace_pattern"),
+ GROUP_MEMBER_FILTER("ambari.ldap.advanced.group_member_filter"),
+
+ FORCE_LOWERCASE_USERNAMES("ambari.ldap.advanced.force_lowercase_usernames"),
+ REFERRAL_HANDLING("ambari.ldap.advanced.referrals"), // folow
+ PAGINATION_ENABLED("ambari.ldap.advanced.pagination_enabled"); // true | false
private String propertyName;
- LdapConfigProperty(String propertyName) {
- this.propertyName = propertyName;
+ AmbariLdapConfig(String propName) {
+ this.propertyName = propName;
}
- public String propertyName() {
+ public String key() {
return this.propertyName;
}
}
private final Map<String, Object> configurationMap;
- private Object configurationValue(LdapConfigProperty ldapConfigProperty) {
+ private Object configValue(AmbariLdapConfig ambariLdapConfig) {
Object value = null;
- if (configurationMap.containsKey(ldapConfigProperty.propertyName)) {
- value = configurationMap.get(ldapConfigProperty.propertyName);
+ if (configurationMap.containsKey(ambariLdapConfig.key())) {
+ value = configurationMap.get(ambariLdapConfig.key());
} else {
- LOGGER.warn("Ldap configuration property [{}] hasn't been set", ldapConfigProperty.propertyName());
+ LOGGER.warn("Ldap configuration property [{}] hasn't been set", ambariLdapConfig.key());
}
-
return value;
}
@@ -99,65 +103,120 @@ public class AmbariLdapConfiguration {
this.configurationMap = configuration;
}
+ public boolean ldapEnabled() {
+ return Boolean.valueOf((String) configValue(AmbariLdapConfig.LDAP_ENABLED));
+ }
- public String ldapServerHost() {
- return (String) configurationValue(LdapConfigProperty.LDAP_SERVER_HOST);
+ public String serverHost() {
+ return (String) configValue(AmbariLdapConfig.SERVER_HOST);
}
- public int ldapServerPort() {
- return Integer.valueOf((String) configurationValue(LdapConfigProperty.LDAP_SERVER_PORT));
+ public int serverPort() {
+ return Integer.valueOf((String) configValue(AmbariLdapConfig.SERVER_PORT));
}
public boolean useSSL() {
- return Boolean.valueOf((String) configurationValue(LdapConfigProperty.USE_SSL));
+ return Boolean.valueOf((String) configValue(AmbariLdapConfig.USE_SSL));
+ }
+
+ public String trustStore() {
+ return (String) configValue(AmbariLdapConfig.TRUST_STORE);
+ }
+
+ public String trustStoreType() {
+ return (String) configValue(AmbariLdapConfig.TRUST_STORE_TYPE);
+ }
+
+ public String trustStorePath() {
+ return (String) configValue(AmbariLdapConfig.TRUST_STORE_PATH);
+ }
+
+ public String trustStorePassword() {
+ return (String) configValue(AmbariLdapConfig.TRUST_STORE_PASSWORD);
}
- public boolean bindAnonimously() {
- return Boolean.valueOf((String) configurationValue(LdapConfigProperty.BIND_ANONIMOUSLY));
+ public boolean anonymousBind() {
+ return Boolean.valueOf((String) configValue(AmbariLdapConfig.ANONYMOUS_BIND));
}
- public String managerDn() {
- return (String) configurationValue(LdapConfigProperty.MANAGER_DN);
+ public String bindDn() {
+ return (String) configValue(AmbariLdapConfig.BIND_DN);
}
- public String managerPassword() {
- return (String) configurationValue(LdapConfigProperty.MANAGER_PASSWORD);
+ public String bindPassword() {
+ return (String) configValue(AmbariLdapConfig.BIND_PASSWORD);
}
- public boolean automaticAttributeDetection() {
- return Boolean.valueOf((String) configurationValue(LdapConfigProperty.AUTOMATIC_ATTRIBUTE_DETECTION));
+ public String attributeDetection() {
+ return (String) configValue(AmbariLdapConfig.ATTR_DETECTION);
}
- public String baseDn() {
- return (String) configurationValue(LdapConfigProperty.BASE_DN);
+ public String dnAttribute() {
+ return (String) configValue(AmbariLdapConfig.DN_ATTRIBUTE);
}
public String userObjectClass() {
- return (String) configurationValue(LdapConfigProperty.USER_OBJECT_CLASS);
+ return (String) configValue(AmbariLdapConfig.USER_OBJECT_CLASS);
}
public String userNameAttribute() {
- return (String) configurationValue(LdapConfigProperty.USER_NAME_ATTRIBUTE);
+ return (String) configValue(AmbariLdapConfig.USER_NAME_ATTRIBUTE);
}
public String userSearchBase() {
- return (String) configurationValue(LdapConfigProperty.USER_SEARCH_BASE);
+ return (String) configValue(AmbariLdapConfig.USER_SEARCH_BASE);
}
public String groupObjectClass() {
- return (String) configurationValue(LdapConfigProperty.GROUP_OBJECT_CLASS);
+ return (String) configValue(AmbariLdapConfig.GROUP_OBJECT_CLASS);
}
public String groupNameAttribute() {
- return (String) configurationValue(LdapConfigProperty.GROUP_NAME_ATTRIBUTE);
+ return (String) configValue(AmbariLdapConfig.GROUP_NAME_ATTRIBUTE);
}
public String groupMemberAttribute() {
- return (String) configurationValue(LdapConfigProperty.GROUP_MEMBER_ATTRIBUTE);
+ return (String) configValue(AmbariLdapConfig.GROUP_MEMBER_ATTRIBUTE);
}
public String groupSearchBase() {
- return (String) configurationValue(LdapConfigProperty.GROUP_SEARCH_BASE);
+ return (String) configValue(AmbariLdapConfig.GROUP_SEARCH_BASE);
+ }
+
+ public String userSearchFilter() {
+ return (String) configValue(AmbariLdapConfig.USER_SEARCH_FILTER);
+ }
+
+ public String userMemberReplacePattern() {
+ return (String) configValue(AmbariLdapConfig.USER_MEMBER_REPLACE_PATTERN);
+ }
+
+ public String userMemberFilter() {
+ return (String) configValue(AmbariLdapConfig.USER_MEMBER_FILTER);
+ }
+
+ public String groupSearchFilter() {
+ return (String) configValue(AmbariLdapConfig.GROUP_SEARCH_FILTER);
+ }
+
+ public String groupMemberReplacePattern() {
+ return (String) configValue(AmbariLdapConfig.GROUP_MEMBER_REPLACE_PATTERN);
+ }
+
+ public String groupMemberFilter() {
+ return (String) configValue(AmbariLdapConfig.GROUP_MEMBER_FILTER);
+ }
+
+ public boolean forceLowerCaseUserNames() {
+ return Boolean.valueOf((String) configValue(AmbariLdapConfig.FORCE_LOWERCASE_USERNAMES));
+ }
+
+ public boolean paginationEnabled() {
+ return Boolean.valueOf((String) configValue(AmbariLdapConfig.PAGINATION_ENABLED));
+ }
+
+ public String referralHandling() {
+ return (String) configValue(AmbariLdapConfig.REFERRAL_HANDLING);
}
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/3800adf6/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapConfigurationProvider.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapConfigurationProvider.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapConfigurationProvider.java
index 7f3e8a9..80ed828 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapConfigurationProvider.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapConfigurationProvider.java
@@ -24,6 +24,7 @@ import javax.inject.Singleton;
import org.apache.ambari.server.events.AmbariLdapConfigChangedEvent;
import org.apache.ambari.server.events.publishers.AmbariEventPublisher;
import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.LdapConfigurationFactory;
import org.apache.ambari.server.orm.dao.AmbariConfigurationDAO;
import org.apache.ambari.server.orm.entities.AmbariConfigurationEntity;
import org.apache.ambari.server.security.authorization.AmbariLdapAuthenticationProvider;
@@ -55,6 +56,9 @@ public class AmbariLdapConfigurationProvider implements Provider<AmbariLdapConfi
@Inject
private Provider<AmbariConfigurationDAO> ambariConfigurationDAOProvider;
+ @Inject
+ private LdapConfigurationFactory ldapConfigurationFactory;
+
private Gson gson = new GsonBuilder().create();
@Inject
@@ -95,7 +99,7 @@ public class AmbariLdapConfigurationProvider implements Provider<AmbariLdapConfi
if (configEntity != null) {
Set propertyMaps = gson.fromJson(configEntity.getConfigurationBaseEntity().getConfigurationData(), Set.class);
- instance = new AmbariLdapConfiguration((Map<String, Object>) propertyMaps.iterator().next());
+ instance = ldapConfigurationFactory.createLdapConfiguration((Map<String, Object>) propertyMaps.iterator().next());
}
LOGGER.info("Loaded LDAP configuration instance: [ {} ]", instance);
http://git-wip-us.apache.org/repos/asf/ambari/blob/3800adf6/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
index 90a5ba7..16bf6b7 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
@@ -55,6 +55,9 @@ public class AmbariLdapFacade implements LdapFacade {
@Inject
private LdapConnectionService ldapConnectionService;
+ @Inject
+ private LdapAttributeDetectionService ldapAttributeDetectionService;
+
//todo remove this, added for testing purposes only
@Inject
private Provider<AmbariLdapConfiguration> ambariLdapConfigurationProvider;
@@ -78,9 +81,12 @@ public class AmbariLdapFacade implements LdapFacade {
@Override
- public void detectAttributes(AmbariLdapConfiguration ambariLdapConfiguration) {
+ public AmbariLdapConfiguration detectAttributes(AmbariLdapConfiguration ambariLdapConfiguration) {
LOGGER.info("Detecting LDAP configuration attributes ...");
- LOGGER.info("LDAP config: {}", ambariLdapConfigurationProvider.get());
+
+ LdapConnection connection = ldapConnectionService.createLdapConnection(ambariLdapConfiguration);
+ ambariLdapConfiguration = ldapAttributeDetectionService.detectLdapUserAttributes(connection, ambariLdapConfiguration);
+ return ambariLdapConfiguration;
}
@Override
http://git-wip-us.apache.org/repos/asf/ambari/blob/3800adf6/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapAttributeDetectionService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapAttributeDetectionService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapAttributeDetectionService.java
new file mode 100644
index 0000000..70a8977
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapAttributeDetectionService.java
@@ -0,0 +1,43 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service;
+
+import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
+import org.apache.directory.ldap.client.api.LdapConnection;
+
+/**
+ * Contract defining operations to detect user and group attributes.
+ */
+public interface LdapAttributeDetectionService {
+
+ /**
+ * Decorates the passed in configuration with the detected ldap user attribute values
+ *
+ * @param ldapConnection the connection instance to LDAP
+ * @param ambariLdapConfiguration configuration instance holding connection details
+ * @return the configuration decorated with user related attributes
+ */
+ AmbariLdapConfiguration detectLdapUserAttributes(LdapConnection ldapConnection, AmbariLdapConfiguration ambariLdapConfiguration);
+
+ /**
+ * Decorates the passed in configuration with the detected ldap group attribute values
+ *
+ * @param ldapConnection the connection instance to LDAP
+ * @param ambariLdapConfiguration configuration instance holding connection details
+ * @return the configuration decorated with group related attributes
+ */
+ AmbariLdapConfiguration detectLdapGroupAttributes(LdapConnection ldapConnection, AmbariLdapConfiguration ambariLdapConfiguration);
+}
+
http://git-wip-us.apache.org/repos/asf/ambari/blob/3800adf6/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java
index eadff7d..76b16c4 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java
@@ -39,7 +39,7 @@ public interface LdapFacade {
*
* @param ambariLdapConfiguration
*/
- void detectAttributes(AmbariLdapConfiguration ambariLdapConfiguration);
+ AmbariLdapConfiguration detectAttributes(AmbariLdapConfiguration ambariLdapConfiguration);
/**
* Checks user and group related LDAP configuration attributes in the configuration object with the help of the provided parameters
http://git-wip-us.apache.org/repos/asf/ambari/blob/3800adf6/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionService.java
new file mode 100644
index 0000000..55d0765
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionService.java
@@ -0,0 +1,47 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service.ads;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.service.LdapAttributeDetectionService;
+import org.apache.directory.ldap.client.api.LdapConnection;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Singleton
+public class DefaultAttributeDetectionService implements LdapAttributeDetectionService {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(DefaultAttributeDetectionService.class);
+
+ @Inject
+ public DefaultAttributeDetectionService() {
+ }
+
+ @Override
+ public AmbariLdapConfiguration detectLdapUserAttributes(LdapConnection connection, AmbariLdapConfiguration ambariLdapConfiguration) {
+ LOGGER.info("Detecting LDAP user attributes ...");
+
+ return null;
+ }
+
+ @Override
+ public AmbariLdapConfiguration detectLdapGroupAttributes(LdapConnection connection, AmbariLdapConfiguration ambariLdapConfiguration) {
+ LOGGER.info("Detecting LDAP group attributes ...");
+ return null;
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/3800adf6/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
index abc9201..db8c77f 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
@@ -186,9 +186,9 @@ public class DefaultLdapConfigurationService implements LdapConfigurationService
*/
private void bind(AmbariLdapConfiguration ambariLdapConfiguration, LdapConnection connection) throws LdapException {
LOGGER.info("Connecting to LDAP ....");
- if (!ambariLdapConfiguration.bindAnonimously()) {
+ if (!ambariLdapConfiguration.anonymousBind()) {
LOGGER.debug("Anonimous binding not supported, binding with the manager detailas...");
- connection.bind(ambariLdapConfiguration.managerDn(), ambariLdapConfiguration.managerPassword());
+ connection.bind(ambariLdapConfiguration.bindDn(), ambariLdapConfiguration.bindPassword());
} else {
LOGGER.debug("Binding anonimously ...");
connection.bind();
http://git-wip-us.apache.org/repos/asf/ambari/blob/3800adf6/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConnectionService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConnectionService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConnectionService.java
index ced52fc..f39df54 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConnectionService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConnectionService.java
@@ -52,8 +52,8 @@ public class DefaultLdapConnectionService implements LdapConnectionService {
LOGGER.debug("Creating a configuration instance based on the ambari configuration: {}", ambariAmbariLdapConfiguration);
LdapConnectionConfig ldapConnectionConfig = new LdapConnectionConfig();
- ldapConnectionConfig.setLdapHost(ambariAmbariLdapConfiguration.ldapServerHost());
- ldapConnectionConfig.setLdapPort(ambariAmbariLdapConfiguration.ldapServerPort());
+ ldapConnectionConfig.setLdapHost(ambariAmbariLdapConfiguration.serverHost());
+ ldapConnectionConfig.setLdapPort(ambariAmbariLdapConfiguration.serverPort());
ldapConnectionConfig.setUseSsl(ambariAmbariLdapConfiguration.useSSL());
// todo set the other values as required
http://git-wip-us.apache.org/repos/asf/ambari/blob/3800adf6/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionServiceTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionServiceTest.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionServiceTest.java
new file mode 100644
index 0000000..5b3ac20
--- /dev/null
+++ b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionServiceTest.java
@@ -0,0 +1,102 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service.ads;
+
+
+import java.util.Map;
+
+import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.service.LdapConnectionService;
+import org.apache.directory.api.ldap.model.constants.SchemaConstants;
+import org.apache.directory.ldap.client.api.LdapConnection;
+import org.apache.directory.ldap.client.api.LdapNetworkConnection;
+import org.easymock.EasyMockRule;
+import org.easymock.TestSubject;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.collect.Maps;
+
+public class DefaultAttributeDetectionServiceTest {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(DefaultAttributeDetectionServiceTest.class);
+
+ @Rule
+ public EasyMockRule mocks = new EasyMockRule(this);
+
+ private AmbariLdapConfiguration testLdapConfiguration;
+ private LdapConnection connection;
+
+ @TestSubject
+ private DefaultAttributeDetectionService attributeDetectionService = new DefaultAttributeDetectionService();
+
+ @Before
+ public void before() {
+
+ Map<String, Object> initialProps = Maps.newHashMap();
+ initialProps.put(AmbariLdapConfiguration.AmbariLdapConfig.BIND_DN.key(), "");
+ testLdapConfiguration = new AmbariLdapConfiguration(initialProps);
+ }
+
+ @Test
+ public void testShouldUserNameAttributeBeDetectedWhenSearchReturnsValidUsers() throws Exception {
+ // GIVEN
+// a set of entries returned from the LDAP search
+
+ // WHEN
+ AmbariLdapConfiguration ambariLdapConfiguration = attributeDetectionService.detectLdapUserAttributes(connection, testLdapConfiguration);
+
+ // THEN
+ Assert.assertNotNull(ambariLdapConfiguration);
+ Assert.assertEquals("The username attribute is not the expected", "uid", ambariLdapConfiguration.userNameAttribute());
+
+ }
+
+
+ private Map<String, Object> getTestPropertiesMap() {
+ Map<String, Object> ldapPropsMap = Maps.newHashMap();
+
+ ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.ANONYMOUS_BIND.key(), "true");
+ ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.SERVER_HOST.key(), "ldap.forumsys.com");
+ ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.SERVER_PORT.key(), "389");
+ ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.BIND_DN.key(), "dc=example,dc=com");
+
+ ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.USER_OBJECT_CLASS.key(), SchemaConstants.PERSON_OC);
+ ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.USER_NAME_ATTRIBUTE.key(), SchemaConstants.UID_AT);
+ ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.USER_SEARCH_BASE.key(), "dc=example,dc=com");
+
+ return ldapPropsMap;
+
+ }
+
+ @Test
+ public void functionalTest() throws Exception {
+ // GIVEN
+ AmbariLdapConfiguration ambariLdapConfiguration = new AmbariLdapConfiguration(getTestPropertiesMap());
+ LdapConnectionService connectionService = new DefaultLdapConnectionService();
+ LdapNetworkConnection ldapConnection = connectionService.createLdapConnection(ambariLdapConfiguration);
+
+
+ // WHEN
+ AmbariLdapConfiguration config = attributeDetectionService.detectLdapUserAttributes(ldapConnection, ambariLdapConfiguration);
+
+ // THEN
+
+ }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/ambari/blob/3800adf6/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java
index b5978a5..e023c6c 100644
--- a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java
+++ b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java
@@ -74,14 +74,14 @@ public class DefaultLdapConfigurationServiceTest {
// GIVEN
Map<String, Object> ldapPropsMap = Maps.newHashMap();
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.BIND_ANONIMOUSLY.propertyName(), "true");
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.LDAP_SERVER_HOST.propertyName(), "ldap.forumsys.com");
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.LDAP_SERVER_PORT.propertyName(), "389");
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.BASE_DN.propertyName(), "dc=example,dc=com");
+ ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.ANONYMOUS_BIND.key(), "true");
+ ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.SERVER_HOST.key(), "ldap.forumsys.com");
+ ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.SERVER_PORT.key(), "389");
+ ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.BIND_DN.key(), "dc=example,dc=com");
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.USER_OBJECT_CLASS.propertyName(), SchemaConstants.PERSON_OC);
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.USER_NAME_ATTRIBUTE.propertyName(), SchemaConstants.UID_AT);
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.USER_SEARCH_BASE.propertyName(), "dc=example,dc=com");
+ ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.USER_OBJECT_CLASS.key(), SchemaConstants.PERSON_OC);
+ ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.USER_NAME_ATTRIBUTE.key(), SchemaConstants.UID_AT);
+ ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.USER_SEARCH_BASE.key(), "dc=example,dc=com");
AmbariLdapConfiguration ambariLdapConfiguration = new AmbariLdapConfiguration(ldapPropsMap);
@@ -96,16 +96,14 @@ public class DefaultLdapConfigurationServiceTest {
// GIVEN
Map<String, Object> ldapPropsMap = Maps.newHashMap();
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.BIND_ANONIMOUSLY.propertyName(), "true");
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.LDAP_SERVER_HOST.propertyName(), "ldap.forumsys.com");
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.LDAP_SERVER_PORT.propertyName(), "389");
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.BASE_DN.propertyName(), "dc=example,dc=com");
+ ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.ANONYMOUS_BIND.key(), "true");
+ ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.SERVER_HOST.key(), "ldap.forumsys.com");
+ ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.SERVER_PORT.key(), "389");
+ ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.BIND_DN.key(), "dc=example,dc=com");
-
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.GROUP_OBJECT_CLASS.propertyName(), SchemaConstants.GROUP_OF_UNIQUE_NAMES_OC);
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.GROUP_NAME_ATTRIBUTE.propertyName(), SchemaConstants.CN_AT);
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.GROUP_MEMBER_ATTRIBUTE.propertyName(), SchemaConstants.UNIQUE_MEMBER_AT);
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.GROUP_SEARCH_BASE.propertyName(), "dc=example,dc=com");
+ ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.USER_OBJECT_CLASS.key(), SchemaConstants.PERSON_OC);
+ ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.USER_NAME_ATTRIBUTE.key(), SchemaConstants.UID_AT);
+ ldapPropsMap.put(AmbariLdapConfiguration.AmbariLdapConfig.USER_SEARCH_BASE.key(), "dc=example,dc=com");
AmbariLdapConfiguration ambariLdapConfiguration = new AmbariLdapConfiguration(ldapPropsMap);
[24/33] ambari git commit: AMBARI-21307 Testing the attribute
detection - fixing bugs, cleanup
Posted by lp...@apache.org.
AMBARI-21307 Testing the attribute detection - fixing bugs, cleanup
Project: http://git-wip-us.apache.org/repos/asf/ambari/repo
Commit: http://git-wip-us.apache.org/repos/asf/ambari/commit/dd990097
Tree: http://git-wip-us.apache.org/repos/asf/ambari/tree/dd990097
Diff: http://git-wip-us.apache.org/repos/asf/ambari/diff/dd990097
Branch: refs/heads/feature-branch-AMBARI-21307
Commit: dd9900973cc84c7bffe4919fb40b81b2383d86ec
Parents: 0467801
Author: lpuskas <lp...@apache.org>
Authored: Tue Sep 12 18:58:44 2017 +0200
Committer: lpuskas <lp...@apache.org>
Committed: Fri Oct 13 17:20:52 2017 +0200
----------------------------------------------------------------------
.../api/services/ldap/LdapConfigurationService.java | 11 +++++++----
.../ambari/server/ldap/AmbariLdapConfiguration.java | 2 +-
.../org/apache/ambari/server/ldap/LdapModule.java | 3 +++
.../ambari/server/ldap/service/AmbariLdapFacade.java | 6 ++++++
.../ads/DefaultAttributeDetectionService.java | 15 +++++++--------
.../service/ads/DefaultLdapConfigurationService.java | 3 ---
.../ads/detectors/GroupMemberAttrDetector.java | 3 +++
.../service/ads/detectors/GroupNameAttrDetector.java | 3 +++
.../ads/detectors/GroupObjectClassDetector.java | 3 +++
.../ads/detectors/UserGroupMemberAttrDetector.java | 3 +++
.../service/ads/detectors/UserNameAttrDetector.java | 3 +++
.../ads/DefaultAttributeDetectionServiceTest.java | 3 +--
.../ads/DefaultLdapConfigurationServiceTest.java | 4 ++--
13 files changed, 42 insertions(+), 20 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/ambari/blob/dd990097/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationService.java b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationService.java
index 66809c3..ae47a87 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapConfigurationService.java
@@ -86,6 +86,7 @@ public class LdapConfigurationService extends AmbariConfigurationService {
authorize();
Set<String> groups = Sets.newHashSet();
+ Object responseEntity = null;
Result result = new ResultImpl(new ResultStatus(ResultStatus.STATUS.OK));
try {
@@ -108,13 +109,14 @@ public class LdapConfigurationService extends AmbariConfigurationService {
LOGGER.info("Testing LDAP attributes ....");
groups = ldapFacade.checkLdapAttributes(ldapConfigurationRequest.getRequestInfo().getParameters(), ambariLdapConfiguration);
- setResult(groups, result);
+ responseEntity = groups;
break;
case DETECT_ATTRIBUTES:
LOGGER.info("Detecting LDAP attributes ...");
- ldapFacade.detectAttributes(ambariLdapConfiguration);
+ ambariLdapConfiguration = ldapFacade.detectAttributes(ambariLdapConfiguration);
+ responseEntity = ambariLdapConfiguration;
break;
default:
@@ -123,10 +125,11 @@ public class LdapConfigurationService extends AmbariConfigurationService {
}
} catch (Exception e) {
- result.setResultStatus(new ResultStatus(ResultStatus.STATUS.BAD_REQUEST, e));
+ result.setResultStatus(new ResultStatus(ResultStatus.STATUS.SERVER_ERROR, e));
+ responseEntity = e.getMessage();
}
- return Response.status(result.getStatus().getStatusCode()).entity(getResultSerializer().serialize(result)).build();
+ return Response.status(result.getStatus().getStatusCode()).entity(responseEntity).build();
}
private void setResult(Set<String> groups, Result result) {
http://git-wip-us.apache.org/repos/asf/ambari/blob/dd990097/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
index ebb567d..5bdda7a 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
@@ -62,7 +62,7 @@ public class AmbariLdapConfiguration {
GROUP_OBJECT_CLASS("ambari.ldap.attributes.group.object_class"),
GROUP_NAME_ATTRIBUTE("ambari.ldap.attributes.group.name_attr"),
GROUP_MEMBER_ATTRIBUTE("ambari.ldap.attributes.group.member_attr"),
- GROUP_SEARCH_BASE("ambari.ldap.attributes.user.search_base"),
+ GROUP_SEARCH_BASE("ambari.ldap.attributes.group.search_base"),
USER_SEARCH_FILTER("ambari.ldap.advanced.user_search_filter"),
USER_MEMBER_REPLACE_PATTERN("ambari.ldap.advanced.user_member_replace_pattern"),
http://git-wip-us.apache.org/repos/asf/ambari/blob/dd990097/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
index 81f2a44..5d6a698 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
@@ -17,8 +17,10 @@ package org.apache.ambari.server.ldap;
import org.apache.ambari.server.ldap.service.AmbariLdapConfigurationProvider;
import org.apache.ambari.server.ldap.service.AmbariLdapFacade;
+import org.apache.ambari.server.ldap.service.LdapAttributeDetectionService;
import org.apache.ambari.server.ldap.service.LdapConnectionService;
import org.apache.ambari.server.ldap.service.LdapFacade;
+import org.apache.ambari.server.ldap.service.ads.DefaultAttributeDetectionService;
import org.apache.ambari.server.ldap.service.ads.DefaultLdapConfigurationService;
import org.apache.ambari.server.ldap.service.ads.DefaultLdapConnectionService;
@@ -35,6 +37,7 @@ public class LdapModule extends AbstractModule {
bind(LdapFacade.class).to(AmbariLdapFacade.class);
bind(LdapConfigurationService.class).to(DefaultLdapConfigurationService.class);
bind(LdapConnectionService.class).to(DefaultLdapConnectionService.class);
+ bind(LdapAttributeDetectionService.class).to(DefaultAttributeDetectionService.class);
bind(AmbariLdapConfiguration.class).toProvider(AmbariLdapConfigurationProvider.class);
http://git-wip-us.apache.org/repos/asf/ambari/blob/dd990097/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
index d2bdef3..719bb7b 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
@@ -95,13 +95,18 @@ public class AmbariLdapFacade implements LdapFacade {
LdapConnection connection = ldapConnectionService.getBoundLdapConnection(ambariLdapConfiguration);
try {
+ // decorate the configuration with detected user attributes
ambariLdapConfiguration = ldapAttributeDetectionService.detectLdapUserAttributes(connection, ambariLdapConfiguration);
+
+ // decorate the configuration with detected group attributes
ambariLdapConfiguration = ldapAttributeDetectionService.detectLdapGroupAttributes(connection, ambariLdapConfiguration);
return ambariLdapConfiguration;
} catch (Exception e) {
+
LOGGER.error("Error during LDAP attribute detection", e);
throw new AmbariLdapException(e);
+
} finally {
try {
connection.unBind();
@@ -126,6 +131,7 @@ public class AmbariLdapFacade implements LdapFacade {
LOGGER.info("Testing LDAP user attributes with test user: {}", userName);
String userDn = ldapConfigurationService.checkUserAttributes(ldapConnection, userName, testUserPass, ldapConfiguration);
+ // todo handle the case where group membership is stored in the user rather than the group
LOGGER.info("Testing LDAP group attributes with test user dn: {}", userDn);
Set<String> groups = ldapConfigurationService.checkGroupAttributes(ldapConnection, userDn, ldapConfiguration);
http://git-wip-us.apache.org/repos/asf/ambari/blob/dd990097/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionService.java
index b3a4fde..e5254b5 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionService.java
@@ -48,21 +48,22 @@ public class DefaultAttributeDetectionService implements LdapAttributeDetectionS
@Inject
- private UserNameAttrDetector userNameAttrDetector = new UserNameAttrDetector(); // todo remove instantition
+ private UserNameAttrDetector userNameAttrDetector;
@Inject
- private UserObjectClassDetector userObjectClassDetector = new UserObjectClassDetector(); // todo remove instantition
+ private UserObjectClassDetector userObjectClassDetector;
@Inject
- private UserGroupMemberAttrDetector userGroupMemberAttrDetector = new UserGroupMemberAttrDetector(); // todo remove instantition
+ private UserGroupMemberAttrDetector userGroupMemberAttrDetector;
@Inject
- private GroupNameAttrDetector groupNameAttrDetector = new GroupNameAttrDetector(); // todo remove instantition
+ private GroupNameAttrDetector groupNameAttrDetector;
@Inject
- private GroupObjectClassDetector groupObjectClassDetector = new GroupObjectClassDetector(); // todo remove instantition
+ private GroupObjectClassDetector groupObjectClassDetector;
- private GroupMemberAttrDetector groupMemberAttrDetector = new GroupMemberAttrDetector(); // todo remove instantition
+ @Inject
+ private GroupMemberAttrDetector groupMemberAttrDetector;
@Inject
public DefaultAttributeDetectionService() {
@@ -81,8 +82,6 @@ public class DefaultAttributeDetectionService implements LdapAttributeDetectionS
SearchCursor searchCursor = null;
try {
- // todo should the bind operation be done in the facade?
- connection.bind(ambariLdapConfiguration.bindDn(), ambariLdapConfiguration.bindPassword());
SearchRequest searchRequest = assembleUserSearchRequest(ambariLdapConfiguration);
http://git-wip-us.apache.org/repos/asf/ambari/blob/dd990097/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
index 5735d7d..c90b5ac 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
@@ -49,9 +49,6 @@ public class DefaultLdapConfigurationService implements LdapConfigurationService
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultLdapConfigurationService.class);
- /**
- * Facilitating the instantiation
- */
@Inject
public DefaultLdapConfigurationService() {
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/dd990097/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupMemberAttrDetector.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupMemberAttrDetector.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupMemberAttrDetector.java
index 6931736..aa444ab 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupMemberAttrDetector.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupMemberAttrDetector.java
@@ -14,6 +14,8 @@
package org.apache.ambari.server.ldap.service.ads.detectors;
+import javax.inject.Inject;
+
import org.apache.directory.api.ldap.model.entry.Entry;
public class GroupMemberAttrDetector extends OccurranceAndWeightBasedDetector {
@@ -42,6 +44,7 @@ public class GroupMemberAttrDetector extends OccurranceAndWeightBasedDetector {
}
+ @Inject
public GroupMemberAttrDetector() {
for (GroupMemberAttr groupMemberAttr : GroupMemberAttr.values()) {
occurranceMap().put(groupMemberAttr.attrName(), 0);
http://git-wip-us.apache.org/repos/asf/ambari/blob/dd990097/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupNameAttrDetector.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupNameAttrDetector.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupNameAttrDetector.java
index f868383..d4dcdff 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupNameAttrDetector.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupNameAttrDetector.java
@@ -14,6 +14,8 @@
package org.apache.ambari.server.ldap.service.ads.detectors;
+import javax.inject.Inject;
+
import org.apache.directory.api.ldap.model.entry.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -45,6 +47,7 @@ public class GroupNameAttrDetector extends OccurranceAndWeightBasedDetector {
}
+ @Inject
public GroupNameAttrDetector() {
for (GroupNameAttr groupNameAttr : GroupNameAttr.values()) {
http://git-wip-us.apache.org/repos/asf/ambari/blob/dd990097/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupObjectClassDetector.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupObjectClassDetector.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupObjectClassDetector.java
index fddc5a5..88824c4 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupObjectClassDetector.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/GroupObjectClassDetector.java
@@ -14,6 +14,8 @@
package org.apache.ambari.server.ldap.service.ads.detectors;
+import javax.inject.Inject;
+
import org.apache.directory.api.ldap.model.entry.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -50,6 +52,7 @@ public class GroupObjectClassDetector extends OccurranceAndWeightBasedDetector {
}
+ @Inject
public GroupObjectClassDetector() {
for (ObjectClassValue ocVal : ObjectClassValue.values()) {
occurranceMap().put(ocVal.ocVal(), 0);
http://git-wip-us.apache.org/repos/asf/ambari/blob/dd990097/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserGroupMemberAttrDetector.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserGroupMemberAttrDetector.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserGroupMemberAttrDetector.java
index c3f2ab4..913c2b6 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserGroupMemberAttrDetector.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserGroupMemberAttrDetector.java
@@ -14,6 +14,8 @@
package org.apache.ambari.server.ldap.service.ads.detectors;
+import javax.inject.Inject;
+
import org.apache.directory.api.ldap.model.entry.Entry;
public class UserGroupMemberAttrDetector extends OccurranceAndWeightBasedDetector {
@@ -42,6 +44,7 @@ public class UserGroupMemberAttrDetector extends OccurranceAndWeightBasedDetecto
}
+ @Inject
public UserGroupMemberAttrDetector() {
for (UserGroupMemberAttr userGroupMemberAttr : UserGroupMemberAttr.values()) {
occurranceMap().put(userGroupMemberAttr.attrName(), 0);
http://git-wip-us.apache.org/repos/asf/ambari/blob/dd990097/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserNameAttrDetector.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserNameAttrDetector.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserNameAttrDetector.java
index 40bf09b..eade3c8 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserNameAttrDetector.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/UserNameAttrDetector.java
@@ -14,6 +14,8 @@
package org.apache.ambari.server.ldap.service.ads.detectors;
+import javax.inject.Inject;
+
import org.apache.directory.api.ldap.model.entry.Entry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -44,6 +46,7 @@ public class UserNameAttrDetector extends OccurranceAndWeightBasedDetector {
}
+ @Inject
public UserNameAttrDetector() {
for (UserNameAttrs nameAttr : UserNameAttrs.values()) {
occurranceMap().put(nameAttr.attrName(), 0);
http://git-wip-us.apache.org/repos/asf/ambari/blob/dd990097/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionServiceTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionServiceTest.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionServiceTest.java
index 08f2d6c..9b03b86 100644
--- a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionServiceTest.java
+++ b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultAttributeDetectionServiceTest.java
@@ -21,7 +21,6 @@ import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
import org.apache.ambari.server.ldap.service.LdapConnectionService;
import org.apache.directory.api.ldap.model.constants.SchemaConstants;
import org.apache.directory.ldap.client.api.LdapConnection;
-import org.apache.directory.ldap.client.api.LdapNetworkConnection;
import org.easymock.EasyMockRule;
import org.easymock.TestSubject;
import org.junit.Assert;
@@ -76,7 +75,7 @@ public class DefaultAttributeDetectionServiceTest {
// GIVEN
AmbariLdapConfiguration ambariLdapConfiguration = new AmbariLdapConfiguration(getTestPropertiesMap());
LdapConnectionService connectionService = new DefaultLdapConnectionService();
- LdapNetworkConnection ldapConnection = connectionService.createLdapConnection(ambariLdapConfiguration);
+ LdapConnection ldapConnection = connectionService.createLdapConnection(ambariLdapConfiguration);
// WHEN
AmbariLdapConfiguration config = attributeDetectionService.detectLdapUserAttributes(ldapConnection, ambariLdapConfiguration);
http://git-wip-us.apache.org/repos/asf/ambari/blob/dd990097/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java
index e023c6c..1e69012 100644
--- a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java
+++ b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java
@@ -86,7 +86,7 @@ public class DefaultLdapConfigurationServiceTest {
AmbariLdapConfiguration ambariLdapConfiguration = new AmbariLdapConfiguration(ldapPropsMap);
LdapConnectionService connectionService = new DefaultLdapConnectionService();
- LdapNetworkConnection ldapConnection = connectionService.createLdapConnection(ambariLdapConfiguration);
+ LdapConnection ldapConnection = connectionService.createLdapConnection(ambariLdapConfiguration);
ldapConfigurationService.checkUserAttributes(ldapConnection, "einstein", "", ambariLdapConfiguration);
}
@@ -108,7 +108,7 @@ public class DefaultLdapConfigurationServiceTest {
AmbariLdapConfiguration ambariLdapConfiguration = new AmbariLdapConfiguration(ldapPropsMap);
LdapConnectionService connectionService = new DefaultLdapConnectionService();
- LdapNetworkConnection ldapConnection = connectionService.createLdapConnection(ambariLdapConfiguration);
+ LdapConnection ldapConnection = connectionService.createLdapConnection(ambariLdapConfiguration);
ldapConfigurationService.checkGroupAttributes(ldapConnection, "uid=einstein,dc=example,dc=com", ambariLdapConfiguration);
}
[21/33] ambari git commit: AMBARI-2130 ldap connections handled in
thefacade. Code cleanup
Posted by lp...@apache.org.
AMBARI-2130 ldap connections handled in thefacade. Code cleanup
Project: http://git-wip-us.apache.org/repos/asf/ambari/repo
Commit: http://git-wip-us.apache.org/repos/asf/ambari/commit/0467801f
Tree: http://git-wip-us.apache.org/repos/asf/ambari/tree/0467801f
Diff: http://git-wip-us.apache.org/repos/asf/ambari/diff/0467801f
Branch: refs/heads/feature-branch-AMBARI-21307
Commit: 0467801fec1e17ec2123ef9586674cf4a6009520
Parents: 14ec2ae
Author: lpuskas <lp...@apache.org>
Authored: Tue Sep 12 15:38:25 2017 +0200
Committer: lpuskas <lp...@apache.org>
Committed: Fri Oct 13 17:20:51 2017 +0200
----------------------------------------------------------------------
.../server/ldap/service/AmbariLdapFacade.java | 51 +++++++++----
.../ldap/service/LdapConnectionService.java | 12 ++-
.../ambari/server/ldap/service/LdapFacade.java | 2 +-
.../ads/DefaultLdapConfigurationService.java | 77 ++++----------------
.../ads/DefaultLdapConnectionService.java | 41 ++++++++++-
.../OccurranceAndWeightBasedDetector.java | 2 +-
6 files changed, 103 insertions(+), 82 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/ambari/blob/0467801f/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
index f159418..d2bdef3 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
@@ -19,7 +19,6 @@ import java.util.Map;
import java.util.Set;
import javax.inject.Inject;
-import javax.inject.Provider;
import javax.inject.Singleton;
import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
@@ -58,35 +57,59 @@ public class AmbariLdapFacade implements LdapFacade {
@Inject
private LdapAttributeDetectionService ldapAttributeDetectionService;
- //todo remove this, added for testing purposes only
- @Inject
- private Provider<AmbariLdapConfiguration> ambariLdapConfigurationProvider;
-
@Inject
public AmbariLdapFacade() {
}
@Override
public void checkConnection(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
+ LdapConnection connection = null;
try {
+
LOGGER.info("Validating LDAP connection related configuration based on: {}", ambariLdapConfiguration);
- LdapConnection connection = ldapConnectionService.createLdapConnection(ambariLdapConfiguration);
+ connection = ldapConnectionService.getBoundLdapConnection(ambariLdapConfiguration);
ldapConfigurationService.checkConnection(connection, ambariLdapConfiguration);
- } catch (AmbariLdapException e) {
+ LOGGER.info("Validating LDAP connection related configuration: SUCCESS");
+
+ } catch (Exception e) {
+
LOGGER.error("Validating LDAP connection configuration failed", e);
- throw e;
+ throw new AmbariLdapException(e);
+
+ } finally {
+ try {
+ connection.unBind();
+ connection.close();
+ } catch (Exception e) {
+ throw new AmbariLdapException(e);
+ }
}
- LOGGER.info("Validating LDAP connection related configuration: SUCCESS");
+
}
@Override
- public AmbariLdapConfiguration detectAttributes(AmbariLdapConfiguration ambariLdapConfiguration) {
+ public AmbariLdapConfiguration detectAttributes(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
LOGGER.info("Detecting LDAP configuration attributes ...");
- LdapConnection connection = ldapConnectionService.createLdapConnection(ambariLdapConfiguration);
- ambariLdapConfiguration = ldapAttributeDetectionService.detectLdapUserAttributes(connection, ambariLdapConfiguration);
- return ambariLdapConfiguration;
+ LdapConnection connection = ldapConnectionService.getBoundLdapConnection(ambariLdapConfiguration);
+ try {
+
+ ambariLdapConfiguration = ldapAttributeDetectionService.detectLdapUserAttributes(connection, ambariLdapConfiguration);
+ ambariLdapConfiguration = ldapAttributeDetectionService.detectLdapGroupAttributes(connection, ambariLdapConfiguration);
+ return ambariLdapConfiguration;
+
+ } catch (Exception e) {
+ LOGGER.error("Error during LDAP attribute detection", e);
+ throw new AmbariLdapException(e);
+ } finally {
+ try {
+ connection.unBind();
+ connection.close();
+ } catch (Exception e) {
+ throw new AmbariLdapException(e);
+ }
+ }
}
@Override
@@ -98,7 +121,7 @@ public class AmbariLdapFacade implements LdapFacade {
throw new IllegalArgumentException("No test user available for testing LDAP attributes");
}
- LdapConnection ldapConnection = ldapConnectionService.createLdapConnection(ldapConfiguration);
+ LdapConnection ldapConnection = ldapConnectionService.getBoundLdapConnection(ldapConfiguration);
LOGGER.info("Testing LDAP user attributes with test user: {}", userName);
String userDn = ldapConfigurationService.checkUserAttributes(ldapConnection, userName, testUserPass, ldapConfiguration);
http://git-wip-us.apache.org/repos/asf/ambari/blob/0467801f/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConnectionService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConnectionService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConnectionService.java
index 50ee8ed..b4daeaa 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConnectionService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConnectionService.java
@@ -15,7 +15,7 @@
package org.apache.ambari.server.ldap.service;
import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
-import org.apache.directory.ldap.client.api.LdapNetworkConnection;
+import org.apache.directory.ldap.client.api.LdapConnection;
/**
* Contract defining factory methods for creating LDAP connection instances.
@@ -29,7 +29,15 @@ public interface LdapConnectionService {
* @param ambariLdapConfiguration configuration instance with information for creating the connection instance
* @return a set up LdapConnection instance
*/
- LdapNetworkConnection createLdapConnection(AmbariLdapConfiguration ambariLdapConfiguration);
+ LdapConnection createLdapConnection(AmbariLdapConfiguration ambariLdapConfiguration);
+
+ /**
+ * Creates an LdapConnection instance and binds to the LDAP server based on the provided configuration entries
+ *
+ * @param ambariLdapConfiguration ambari configuration instance
+ * @return
+ */
+ LdapConnection getBoundLdapConnection(AmbariLdapConfiguration ambariLdapConfiguration);
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/0467801f/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java
index 7cd25da..6060d7f 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java
@@ -39,7 +39,7 @@ public interface LdapFacade {
*
* @param ambariLdapConfiguration
*/
- AmbariLdapConfiguration detectAttributes(AmbariLdapConfiguration ambariLdapConfiguration);
+ AmbariLdapConfiguration detectAttributes(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException;
/**
* Checks user and group related LDAP configuration attributes in the configuration object with the help of the provided parameters
http://git-wip-us.apache.org/repos/asf/ambari/blob/0467801f/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
index fa2e44b..5735d7d 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationService.java
@@ -14,24 +14,20 @@
package org.apache.ambari.server.ldap.service.ads;
-import java.io.IOException;
import java.util.List;
import java.util.Set;
import javax.inject.Inject;
import javax.inject.Singleton;
-import org.apache.ambari.server.AmbariException;
import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
import org.apache.ambari.server.ldap.LdapConfigurationService;
import org.apache.ambari.server.ldap.service.AmbariLdapException;
-import org.apache.ambari.server.ldap.service.LdapConnectionService;
import org.apache.directory.api.ldap.codec.decorators.SearchResultEntryDecorator;
import org.apache.directory.api.ldap.model.constants.SchemaConstants;
import org.apache.directory.api.ldap.model.cursor.EntryCursor;
import org.apache.directory.api.ldap.model.cursor.SearchCursor;
import org.apache.directory.api.ldap.model.entry.Entry;
-import org.apache.directory.api.ldap.model.exception.LdapException;
import org.apache.directory.api.ldap.model.message.Response;
import org.apache.directory.api.ldap.model.message.SearchRequest;
import org.apache.directory.api.ldap.model.message.SearchRequestImpl;
@@ -53,9 +49,6 @@ public class DefaultLdapConfigurationService implements LdapConfigurationService
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultLdapConfigurationService.class);
- @Inject
- private LdapConnectionService ldapConnectionService;
-
/**
* Facilitating the instantiation
*/
@@ -65,12 +58,12 @@ public class DefaultLdapConfigurationService implements LdapConfigurationService
@Override
public void checkConnection(LdapConnection ldapConnection, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
- try {
- bind(ambariLdapConfiguration, ldapConnection);
- } catch (LdapException e) {
- LOGGER.error("Could not connect to the LDAP server", e);
- throw new AmbariLdapException(e);
+
+ if (!ldapConnection.isConnected()) {
+ LOGGER.error("Could not connect to the LDAP server");
+ throw new AmbariLdapException("Could not connect to the LDAP server. Configuration: " + ambariLdapConfiguration);
}
+
}
@@ -80,22 +73,20 @@ public class DefaultLdapConfigurationService implements LdapConfigurationService
*
* Invalid attributes are signaled by throwing an exception.
*
+ * @param ldapConnection connection instance used to connect to the LDAP server
* @param testUserName the test username
* @param testPassword the test password
* @param ambariLdapConfiguration configuration instance holding ldap configuration details
* @return the DN of the test user
- * @throws AmbariException if the attributes are not valid or any errors occurs
+ * @throws AmbariLdapException if an error occurs
*/
@Override
public String checkUserAttributes(LdapConnection ldapConnection, String testUserName, String testPassword, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
- SearchCursor searchCursor = null;
String userDn = null;
+ EntryCursor entryCursor = null;
try {
LOGGER.info("Checking user attributes for user {} r ...", testUserName);
- // bind anonimously or with manager data
- bind(ambariLdapConfiguration, ldapConnection);
-
// set up a filter based on the provided attributes
String filter = FilterBuilder.and(
FilterBuilder.equal(SchemaConstants.OBJECT_CLASS_AT, ambariLdapConfiguration.userObjectClass()),
@@ -103,7 +94,7 @@ public class DefaultLdapConfigurationService implements LdapConfigurationService
.toString();
LOGGER.info("Searching for the user: {} using the search filter: {}", testUserName, filter);
- EntryCursor entryCursor = ldapConnection.search(new Dn(ambariLdapConfiguration.userSearchBase()), filter, SearchScope.SUBTREE);
+ entryCursor = ldapConnection.search(new Dn(ambariLdapConfiguration.userSearchBase()), filter, SearchScope.SUBTREE);
// collecting search result entries
List<Entry> users = Lists.newArrayList();
@@ -127,7 +118,9 @@ public class DefaultLdapConfigurationService implements LdapConfigurationService
throw new AmbariLdapException(e.getMessage(), e);
} finally {
- closeResources(ldapConnection, searchCursor);
+ if (null != entryCursor) {
+ entryCursor.close();
+ }
}
return userDn;
}
@@ -141,8 +134,6 @@ public class DefaultLdapConfigurationService implements LdapConfigurationService
try {
LOGGER.info("Checking group attributes for user dn {} ...", userDn);
- bind(ambariLdapConfiguration, ldapConnection);
-
// set up a filter based on the provided attributes
String filter = FilterBuilder.and(
FilterBuilder.equal(SchemaConstants.OBJECT_CLASS_AT, ambariLdapConfiguration.groupObjectClass()),
@@ -171,36 +162,14 @@ public class DefaultLdapConfigurationService implements LdapConfigurationService
throw new AmbariLdapException(e.getMessage(), e);
} finally {
- closeResources(ldapConnection, searchCursor);
+ if (null != searchCursor) {
+ searchCursor.close();
+ }
}
return processGroupResults(groupResponses, ambariLdapConfiguration);
}
- /**
- * Binds to the LDAP server (anonimously or wit manager credentials)
- *
- * @param ambariLdapConfiguration configuration instance
- * @param connection connection instance
- * @throws LdapException if the bind operation fails
- */
- private void bind(AmbariLdapConfiguration ambariLdapConfiguration, LdapConnection connection) throws LdapException {
- LOGGER.info("Connecting to LDAP ....");
- if (!ambariLdapConfiguration.anonymousBind()) {
- LOGGER.debug("Anonimous binding not supported, binding with the manager detailas...");
- connection.bind(ambariLdapConfiguration.bindDn(), ambariLdapConfiguration.bindPassword());
- } else {
- LOGGER.debug("Binding anonymously ...");
- connection.bind();
- }
-
- if (!connection.isConnected()) {
- LOGGER.error("Not connected to the LDAP server. Connection instance: {}", connection);
- throw new IllegalStateException("The connection to the LDAP server is not alive");
- }
- LOGGER.info("Connected to LDAP.");
- }
-
/**
* Extracts meaningful values from the search result.
@@ -220,22 +189,6 @@ public class DefaultLdapConfigurationService implements LdapConfigurationService
return groupStrSet;
}
- private void closeResources(LdapConnection connection, SearchCursor searchCursor) {
- LOGGER.debug("Housekeeping: closing the connection and the search cursor ...");
-
- if (null != searchCursor) {
- // this method is idempotent
- searchCursor.close();
- }
-
- if (null != connection) {
- try {
- connection.close();
- } catch (IOException e) {
- LOGGER.error("Exception occurred while closing the connection", e);
- }
- }
- }
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/0467801f/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConnectionService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConnectionService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConnectionService.java
index f39df54..457e23e 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConnectionService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConnectionService.java
@@ -32,6 +32,7 @@ import javax.inject.Singleton;
import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
import org.apache.ambari.server.ldap.service.LdapConnectionService;
+import org.apache.directory.ldap.client.api.LdapConnection;
import org.apache.directory.ldap.client.api.LdapConnectionConfig;
import org.apache.directory.ldap.client.api.LdapNetworkConnection;
import org.slf4j.Logger;
@@ -45,18 +46,54 @@ public class DefaultLdapConnectionService implements LdapConnectionService {
@Override
public LdapNetworkConnection createLdapConnection(AmbariLdapConfiguration ambariLdapConfiguration) {
LOGGER.debug("Creating ldap connection instance from: {}", ambariLdapConfiguration);
+
return new LdapNetworkConnection(getLdapConnectionConfig(ambariLdapConfiguration));
}
+ @Override
+ public LdapConnection getBoundLdapConnection(AmbariLdapConfiguration ambariLdapConfiguration) {
+ LOGGER.info("Creating LDAP connection instance and binding to LDAP server ...");
+
+ try {
+ LdapConnection connection = createLdapConnection(ambariLdapConfiguration);
+
+ if (!ambariLdapConfiguration.anonymousBind()) {
+
+ LOGGER.debug("Anonymous binding not supported, binding with the manager detailas...");
+ connection.bind(ambariLdapConfiguration.bindDn(), ambariLdapConfiguration.bindPassword());
+
+ } else {
+
+ LOGGER.debug("Binding anonymously ...");
+ connection.bind();
+
+ }
+
+ if (!connection.isConnected()) {
+
+ LOGGER.error("Not connected to the LDAP server. Connection instance: {}", connection);
+ throw new IllegalStateException("The connection to the LDAP server is not alive");
+
+ }
+
+ LOGGER.info("Connected / bound to LDAP server.");
+ return connection;
+
+ } catch (Exception e) {
+ LOGGER.error("Could not create or bind LdapConnection", e);
+ throw new IllegalArgumentException(e);
+ }
+
+ }
+
private LdapConnectionConfig getLdapConnectionConfig(AmbariLdapConfiguration ambariAmbariLdapConfiguration) {
- LOGGER.debug("Creating a configuration instance based on the ambari configuration: {}", ambariAmbariLdapConfiguration);
+ LOGGER.debug("Creating a LDAP connection config instance based on the ambari configuration: {}", ambariAmbariLdapConfiguration);
LdapConnectionConfig ldapConnectionConfig = new LdapConnectionConfig();
ldapConnectionConfig.setLdapHost(ambariAmbariLdapConfiguration.serverHost());
ldapConnectionConfig.setLdapPort(ambariAmbariLdapConfiguration.serverPort());
ldapConnectionConfig.setUseSsl(ambariAmbariLdapConfiguration.useSSL());
- // todo set the other values as required
return ldapConnectionConfig;
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/0467801f/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/OccurranceAndWeightBasedDetector.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/OccurranceAndWeightBasedDetector.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/OccurranceAndWeightBasedDetector.java
index 8aaf6c1..71dfb42 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/OccurranceAndWeightBasedDetector.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/detectors/OccurranceAndWeightBasedDetector.java
@@ -78,7 +78,7 @@ public abstract class OccurranceAndWeightBasedDetector implements AttributeDetec
@Override
public void collect(Entry entry) {
- LOGGER.info("Collecting ldap attributes/values form entry with dn: [{]]", entry.getDn());
+ LOGGER.info("Collecting ldap attributes/values form entry with dn: [{}]", entry.getDn());
for (String attributeValue : occurranceMap().keySet()) {
if (applies(entry, attributeValue)) {
[17/33] ambari git commit: AMBARI-21307 renamed package,
minor corrections. Changed endpoint name
Posted by lp...@apache.org.
AMBARI-21307 renamed package, minor corrections. Changed endpoint name
Project: http://git-wip-us.apache.org/repos/asf/ambari/repo
Commit: http://git-wip-us.apache.org/repos/asf/ambari/commit/5b7c55f6
Tree: http://git-wip-us.apache.org/repos/asf/ambari/tree/5b7c55f6
Diff: http://git-wip-us.apache.org/repos/asf/ambari/diff/5b7c55f6
Branch: refs/heads/feature-branch-AMBARI-21307
Commit: 5b7c55f6c0ab42b7e3f5b513bd40934b2cfb6ad9
Parents: e87ca3c
Author: lpuskas <lp...@apache.org>
Authored: Mon Aug 14 13:21:07 2017 +0200
Committer: lpuskas <lp...@apache.org>
Committed: Fri Oct 13 17:20:50 2017 +0200
----------------------------------------------------------------------
.../services/AmbariConfigurationService.java | 2 +-
.../api/services/ldap/LdapRestService.java | 15 +-
.../server/ldap/AmbariLdapConfiguration.java | 5 +-
.../apache/ambari/server/ldap/LdapModule.java | 4 +-
...efaultLdapConfigurationValidatorService.java | 243 -------------------
.../ad/DefaultLdapConnectionService.java | 63 -----
...efaultLdapConfigurationValidatorService.java | 243 +++++++++++++++++++
.../ads/DefaultLdapConnectionService.java | 63 +++++
...ltLdapConfigurationValidatorServiceTest.java | 113 ---------
...ltLdapConfigurationValidatorServiceTest.java | 113 +++++++++
10 files changed, 435 insertions(+), 429 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/ambari/blob/5b7c55f6/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationService.java b/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationService.java
index 927e518..492509f 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationService.java
@@ -63,7 +63,7 @@ import io.swagger.annotations.ApiResponses;
* }
* </pre>
*/
-@Path("/configurations/")
+@Path("/ambariconfigs/")
@Api(value = "Ambari Configurations", description = "Endpoint for Ambari configuration related operations")
public class AmbariConfigurationService extends BaseService {
http://git-wip-us.apache.org/repos/asf/ambari/blob/5b7c55f6/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapRestService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapRestService.java b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapRestService.java
index 8578204..4e654dc 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapRestService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/api/services/ldap/LdapRestService.java
@@ -34,6 +34,7 @@ import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@@ -70,8 +71,9 @@ public class LdapRestService extends BaseService {
@POST
@ApiIgnore // until documented
- @Path("/action") // todo this needs to be moved under the resource
+ @Path("/validate") // todo this needs to be moved under the resource
@Consumes(MediaType.APPLICATION_JSON)
+ @Produces(MediaType.APPLICATION_JSON)
public Response validateConfiguration(LdapCheckConfigurationRequest ldapCheckConfigurationRequest) {
Set<String> groups = Sets.newHashSet();
@@ -95,10 +97,7 @@ public class LdapRestService extends BaseService {
LOGGER.info("Testing LDAP attributes ....");
groups = ldapFacade.checkLdapAttibutes(ldapCheckConfigurationRequest.getRequestInfo().getParameters(), ambariLdapConfiguration);
- // todo factor out the resource creation, design better the structure in the response
- Resource resource = new ResourceImpl(Resource.Type.AmbariConfiguration);
- resource.setProperty("groups", groups);
- result.getResultTree().addChild(resource, "payload");
+ setResult(groups, result);
break;
case "detect-attributes":
@@ -119,6 +118,12 @@ public class LdapRestService extends BaseService {
return Response.status(result.getStatus().getStatusCode()).entity(getResultSerializer().serialize(result)).build();
}
+ private void setResult(Set<String> groups, Result result) {
+ Resource resource = new ResourceImpl(Resource.Type.AmbariConfiguration);
+ resource.setProperty("groups", groups);
+ result.getResultTree().addChild(resource, "payload");
+ }
+
private void validateRequest(LdapCheckConfigurationRequest ldapCheckConfigurationRequest) {
String errMsg;
http://git-wip-us.apache.org/repos/asf/ambari/blob/5b7c55f6/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
index 8ab587b..b1cbced 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
@@ -37,11 +37,12 @@ public class AmbariLdapConfiguration {
public enum LdapConfigProperty {
LDAP_CONFIGURED("ambari.ldap.configured"),
AUTOMATIC_ATTRIBUTE_DETECTION("ambari.ldap.automatic.attribute.detection"),
-
USE_SSL("ambari.ldap.usessl"),
LDAP_SERVER_HOST("ambari.ldap.server.host"),
LDAP_SERVER_PORT("ambari.ldap.server.port"),
- BASE_DN("ambari.ldap.base.dn"),
+ LDAP_TRUSTSTORE_TYPE("ambari.ldap.truststore.type"),
+ LDAP_TRUSTSTORE_PATH("ambari.ldap.truststore.path"),
+ BASE_DN("ambari.ldap.bind.dn"),
BIND_ANONIMOUSLY("ambari.ldap.bindanonymously"),
MANAGER_DN("ambari.ldap.managerdn"),
http://git-wip-us.apache.org/repos/asf/ambari/blob/5b7c55f6/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
index 1b49159..a4ad2ee 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
@@ -18,8 +18,8 @@ package org.apache.ambari.server.ldap;
import org.apache.ambari.server.ldap.service.AmbariLdapFacade;
import org.apache.ambari.server.ldap.service.LdapConnectionService;
import org.apache.ambari.server.ldap.service.LdapFacade;
-import org.apache.ambari.server.ldap.service.ad.DefaultLdapConfigurationValidatorService;
-import org.apache.ambari.server.ldap.service.ad.DefaultLdapConnectionService;
+import org.apache.ambari.server.ldap.service.ads.DefaultLdapConfigurationValidatorService;
+import org.apache.ambari.server.ldap.service.ads.DefaultLdapConnectionService;
import com.google.inject.AbstractModule;
import com.google.inject.assistedinject.FactoryModuleBuilder;
http://git-wip-us.apache.org/repos/asf/ambari/blob/5b7c55f6/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConfigurationValidatorService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConfigurationValidatorService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConfigurationValidatorService.java
deleted file mode 100644
index a8503ca..0000000
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConfigurationValidatorService.java
+++ /dev/null
@@ -1,243 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.ambari.server.ldap.service.ad;
-
-import java.io.IOException;
-import java.util.List;
-import java.util.Set;
-
-import javax.inject.Inject;
-import javax.inject.Singleton;
-
-import org.apache.ambari.server.AmbariException;
-import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
-import org.apache.ambari.server.ldap.LdapConfigurationValidatorService;
-import org.apache.ambari.server.ldap.service.AmbariLdapException;
-import org.apache.ambari.server.ldap.service.LdapConnectionService;
-import org.apache.directory.api.ldap.codec.decorators.SearchResultEntryDecorator;
-import org.apache.directory.api.ldap.model.cursor.EntryCursor;
-import org.apache.directory.api.ldap.model.cursor.SearchCursor;
-import org.apache.directory.api.ldap.model.entry.Entry;
-import org.apache.directory.api.ldap.model.exception.LdapException;
-import org.apache.directory.api.ldap.model.message.Response;
-import org.apache.directory.api.ldap.model.message.SearchRequest;
-import org.apache.directory.api.ldap.model.message.SearchRequestImpl;
-import org.apache.directory.api.ldap.model.message.SearchScope;
-import org.apache.directory.api.ldap.model.name.Dn;
-import org.apache.directory.ldap.client.api.LdapConnection;
-import org.apache.directory.ldap.client.api.search.FilterBuilder;
-import org.apache.directory.shared.ldap.constants.SchemaConstants;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.Lists;
-import com.google.common.collect.Sets;
-
-/**
- * Implementation of the validation logic using the Apache Directory API.
- */
-@Singleton
-public class DefaultLdapConfigurationValidatorService implements LdapConfigurationValidatorService {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(DefaultLdapConfigurationValidatorService.class);
-
- @Inject
- private LdapConnectionService ldapConnectionService;
-
- /**
- * Facilitating the instantiation
- */
- @Inject
- public DefaultLdapConfigurationValidatorService() {
- }
-
- @Override
- public void checkConnection(LdapConnection ldapConnection, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
- try {
- bind(ambariLdapConfiguration, ldapConnection);
- } catch (LdapException e) {
- LOGGER.error("Could not connect to the LDAP server", e);
- throw new AmbariLdapException(e);
- }
- }
-
-
- /**
- * Checks the user attributes provided in the configuration instance by issuing a search for a (known) test user in the LDAP.
- * Attributes are considered correct if there is at least one entry found.
- *
- * Invalid attributes are signaled by throwing an exception.
- *
- * @param testUserName the test username
- * @param testPassword the test password
- * @param ambariLdapConfiguration configuration instance holding ldap configuration details
- * @return the DN of the test user
- * @throws AmbariException if the attributes are not valid or any errors occurs
- */
- @Override
- public String checkUserAttributes(LdapConnection ldapConnection, String testUserName, String testPassword, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
- SearchCursor searchCursor = null;
- String userDn = null;
- try {
- LOGGER.info("Checking user attributes for user {} r ...", testUserName);
-
- // bind anonimously or with manager data
- bind(ambariLdapConfiguration, ldapConnection);
-
- // set up a filter based on the provided attributes
- String filter = FilterBuilder.and(
- FilterBuilder.equal(SchemaConstants.OBJECT_CLASS_AT, ambariLdapConfiguration.userObjectClass()),
- FilterBuilder.equal(ambariLdapConfiguration.userNameAttribute(), testUserName))
- .toString();
-
- LOGGER.info("Searching for the user: {} using the search filter: {}", testUserName, filter);
- EntryCursor entryCursor = ldapConnection.search(new Dn(ambariLdapConfiguration.userSearchBase()), filter, SearchScope.SUBTREE);
-
- // collecting search result entries
- List<Entry> users = Lists.newArrayList();
- for (Entry entry : entryCursor) {
- users.add(entry);
- userDn = entry.getDn().getNormName();
- }
-
- // there should be at least one user found
- if (users.isEmpty()) {
- String msg = String.format("There are no users found using the filter: [ %s ]. Try changing the attribute values", filter);
- LOGGER.error(msg);
- throw new Exception(msg);
- }
-
- LOGGER.info("Attibute validation succeeded. Filter: {}", filter);
-
- } catch (Exception e) {
-
- LOGGER.error("User attributes validation failed.", e);
- throw new AmbariLdapException(e.getMessage(), e);
-
- } finally {
- closeResources(ldapConnection, searchCursor);
- }
- return userDn;
- }
-
-
- @Override
- public Set<String> checkGroupAttributes(LdapConnection ldapConnection, String userDn, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
- SearchCursor searchCursor = null;
- Set<Response> groupResponses = Sets.newHashSet();
-
- try {
- LOGGER.info("Checking group attributes for user dn {} ...", userDn);
-
- bind(ambariLdapConfiguration, ldapConnection);
-
- // set up a filter based on the provided attributes
- String filter = FilterBuilder.and(
- FilterBuilder.equal(SchemaConstants.OBJECT_CLASS_AT, ambariLdapConfiguration.groupObjectClass()),
- FilterBuilder.equal(ambariLdapConfiguration.groupMemberAttribute(), userDn)
- ).toString();
-
- LOGGER.info("Searching for the groups the user dn: {} is member of using the search filter: {}", userDn, filter);
-
- // assemble a search request
- SearchRequest searchRequest = new SearchRequestImpl();
- searchRequest.setFilter(filter);
- searchRequest.setBase(new Dn(ambariLdapConfiguration.groupSearchBase()));
- searchRequest.setScope(SearchScope.SUBTREE);
- searchRequest.addAttributes(ambariLdapConfiguration.groupMemberAttribute(), ambariLdapConfiguration.groupNameAttribute());
-
- // perform the search
- searchCursor = ldapConnection.search(searchRequest);
-
- for (Response response : searchCursor) {
- groupResponses.add(response);
- }
-
- } catch (Exception e) {
-
- LOGGER.error("User attributes validation failed.", e);
- throw new AmbariLdapException(e.getMessage(), e);
-
- } finally {
- closeResources(ldapConnection, searchCursor);
- }
-
- return processGroupResults(groupResponses, ambariLdapConfiguration);
- }
-
- /**
- * Binds to the LDAP server (anonimously or wit manager credentials)
- *
- * @param ambariLdapConfiguration configuration instance
- * @param connection connection instance
- * @throws LdapException if the bind operation fails
- */
- private void bind(AmbariLdapConfiguration ambariLdapConfiguration, LdapConnection connection) throws LdapException {
- LOGGER.info("Connecting to LDAP ....");
- if (!ambariLdapConfiguration.bindAnonimously()) {
- LOGGER.debug("Anonimous binding not supported, binding with the manager detailas...");
- connection.bind(ambariLdapConfiguration.managerDn(), ambariLdapConfiguration.managerPassword());
- } else {
- LOGGER.debug("Binding anonimously ...");
- connection.bind();
- }
-
- if (!connection.isConnected()) {
- LOGGER.error("Not connected to the LDAP server. Connection instance: {}", connection);
- throw new IllegalStateException("The connection to the LDAP server is not alive");
- }
- LOGGER.info("Connected to LDAP.");
- }
-
-
- /**
- * Extracts meaningful values from the search result.
- *
- * @param groupResponses the result entries returned by the search
- * @param ambariLdapConfiguration holds the keys of the meaningful attributes
- * @return a set with the group names the test user belongs to
- */
- private Set<String> processGroupResults(Set<Response> groupResponses, AmbariLdapConfiguration ambariLdapConfiguration) {
- Set<String> groupStrSet = Sets.newHashSet();
- for (Response response : groupResponses) {
- Entry entry = ((SearchResultEntryDecorator) response).getEntry();
- groupStrSet.add(entry.get(ambariLdapConfiguration.groupNameAttribute()).get().getString());
- }
-
- LOGGER.debug("Extracted group names from group search responses: {}", groupStrSet);
- return groupStrSet;
- }
-
- private void closeResources(LdapConnection connection, SearchCursor searchCursor) {
- LOGGER.debug("Housekeeping: closing the connection and the search cursor ...");
-
- if (null != searchCursor) {
- // this method is idempotent
- searchCursor.close();
- }
-
- if (null != connection) {
- try {
- connection.close();
- } catch (IOException e) {
- LOGGER.error("Exception occurred while closing the connection", e);
- }
- }
- }
-
-}
-
-
-
http://git-wip-us.apache.org/repos/asf/ambari/blob/5b7c55f6/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConnectionService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConnectionService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConnectionService.java
deleted file mode 100644
index 25dc1f2..0000000
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConnectionService.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.ambari.server.ldap.service.ad;
-
-import javax.inject.Singleton;
-
-import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
-import org.apache.ambari.server.ldap.service.LdapConnectionService;
-import org.apache.directory.ldap.client.api.LdapConnectionConfig;
-import org.apache.directory.ldap.client.api.LdapNetworkConnection;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-@Singleton
-public class DefaultLdapConnectionService implements LdapConnectionService {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(DefaultLdapConnectionService.class);
-
- @Override
- public LdapNetworkConnection createLdapConnection(AmbariLdapConfiguration ambariLdapConfiguration) {
- LOGGER.debug("Creating ldap connection instance from: {}", ambariLdapConfiguration);
- return new LdapNetworkConnection(getLdapConnectionConfig(ambariLdapConfiguration));
- }
-
- private LdapConnectionConfig getLdapConnectionConfig(AmbariLdapConfiguration ambariAmbariLdapConfiguration) {
- LOGGER.debug("Creating a configuration instance based on the ambari configuration: {}", ambariAmbariLdapConfiguration);
-
- LdapConnectionConfig ldapConnectionConfig = new LdapConnectionConfig();
- ldapConnectionConfig.setLdapHost(ambariAmbariLdapConfiguration.ldapServerHost());
- ldapConnectionConfig.setLdapPort(ambariAmbariLdapConfiguration.ldapServerPort());
- ldapConnectionConfig.setUseSsl(ambariAmbariLdapConfiguration.useSSL());
-
- // todo set the other values as required
- return ldapConnectionConfig;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/ambari/blob/5b7c55f6/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationValidatorService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationValidatorService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationValidatorService.java
new file mode 100644
index 0000000..040983a
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationValidatorService.java
@@ -0,0 +1,243 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service.ads;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Set;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+import org.apache.ambari.server.AmbariException;
+import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.LdapConfigurationValidatorService;
+import org.apache.ambari.server.ldap.service.AmbariLdapException;
+import org.apache.ambari.server.ldap.service.LdapConnectionService;
+import org.apache.directory.api.ldap.codec.decorators.SearchResultEntryDecorator;
+import org.apache.directory.api.ldap.model.constants.SchemaConstants;
+import org.apache.directory.api.ldap.model.cursor.EntryCursor;
+import org.apache.directory.api.ldap.model.cursor.SearchCursor;
+import org.apache.directory.api.ldap.model.entry.Entry;
+import org.apache.directory.api.ldap.model.exception.LdapException;
+import org.apache.directory.api.ldap.model.message.Response;
+import org.apache.directory.api.ldap.model.message.SearchRequest;
+import org.apache.directory.api.ldap.model.message.SearchRequestImpl;
+import org.apache.directory.api.ldap.model.message.SearchScope;
+import org.apache.directory.api.ldap.model.name.Dn;
+import org.apache.directory.ldap.client.api.LdapConnection;
+import org.apache.directory.ldap.client.api.search.FilterBuilder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+
+/**
+ * Implementation of the validation logic using the Apache Directory API.
+ */
+@Singleton
+public class DefaultLdapConfigurationValidatorService implements LdapConfigurationValidatorService {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(DefaultLdapConfigurationValidatorService.class);
+
+ @Inject
+ private LdapConnectionService ldapConnectionService;
+
+ /**
+ * Facilitating the instantiation
+ */
+ @Inject
+ public DefaultLdapConfigurationValidatorService() {
+ }
+
+ @Override
+ public void checkConnection(LdapConnection ldapConnection, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
+ try {
+ bind(ambariLdapConfiguration, ldapConnection);
+ } catch (LdapException e) {
+ LOGGER.error("Could not connect to the LDAP server", e);
+ throw new AmbariLdapException(e);
+ }
+ }
+
+
+ /**
+ * Checks the user attributes provided in the configuration instance by issuing a search for a (known) test user in the LDAP.
+ * Attributes are considered correct if there is at least one entry found.
+ *
+ * Invalid attributes are signaled by throwing an exception.
+ *
+ * @param testUserName the test username
+ * @param testPassword the test password
+ * @param ambariLdapConfiguration configuration instance holding ldap configuration details
+ * @return the DN of the test user
+ * @throws AmbariException if the attributes are not valid or any errors occurs
+ */
+ @Override
+ public String checkUserAttributes(LdapConnection ldapConnection, String testUserName, String testPassword, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
+ SearchCursor searchCursor = null;
+ String userDn = null;
+ try {
+ LOGGER.info("Checking user attributes for user {} r ...", testUserName);
+
+ // bind anonimously or with manager data
+ bind(ambariLdapConfiguration, ldapConnection);
+
+ // set up a filter based on the provided attributes
+ String filter = FilterBuilder.and(
+ FilterBuilder.equal(SchemaConstants.OBJECT_CLASS_AT, ambariLdapConfiguration.userObjectClass()),
+ FilterBuilder.equal(ambariLdapConfiguration.userNameAttribute(), testUserName))
+ .toString();
+
+ LOGGER.info("Searching for the user: {} using the search filter: {}", testUserName, filter);
+ EntryCursor entryCursor = ldapConnection.search(new Dn(ambariLdapConfiguration.userSearchBase()), filter, SearchScope.SUBTREE);
+
+ // collecting search result entries
+ List<Entry> users = Lists.newArrayList();
+ for (Entry entry : entryCursor) {
+ users.add(entry);
+ userDn = entry.getDn().getNormName();
+ }
+
+ // there should be at least one user found
+ if (users.isEmpty()) {
+ String msg = String.format("There are no users found using the filter: [ %s ]. Try changing the attribute values", filter);
+ LOGGER.error(msg);
+ throw new Exception(msg);
+ }
+
+ LOGGER.info("Attibute validation succeeded. Filter: {}", filter);
+
+ } catch (Exception e) {
+
+ LOGGER.error("User attributes validation failed.", e);
+ throw new AmbariLdapException(e.getMessage(), e);
+
+ } finally {
+ closeResources(ldapConnection, searchCursor);
+ }
+ return userDn;
+ }
+
+
+ @Override
+ public Set<String> checkGroupAttributes(LdapConnection ldapConnection, String userDn, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
+ SearchCursor searchCursor = null;
+ Set<Response> groupResponses = Sets.newHashSet();
+
+ try {
+ LOGGER.info("Checking group attributes for user dn {} ...", userDn);
+
+ bind(ambariLdapConfiguration, ldapConnection);
+
+ // set up a filter based on the provided attributes
+ String filter = FilterBuilder.and(
+ FilterBuilder.equal(SchemaConstants.OBJECT_CLASS_AT, ambariLdapConfiguration.groupObjectClass()),
+ FilterBuilder.equal(ambariLdapConfiguration.groupMemberAttribute(), userDn)
+ ).toString();
+
+ LOGGER.info("Searching for the groups the user dn: {} is member of using the search filter: {}", userDn, filter);
+
+ // assemble a search request
+ SearchRequest searchRequest = new SearchRequestImpl();
+ searchRequest.setFilter(filter);
+ searchRequest.setBase(new Dn(ambariLdapConfiguration.groupSearchBase()));
+ searchRequest.setScope(SearchScope.SUBTREE);
+ searchRequest.addAttributes(ambariLdapConfiguration.groupMemberAttribute(), ambariLdapConfiguration.groupNameAttribute());
+
+ // perform the search
+ searchCursor = ldapConnection.search(searchRequest);
+
+ for (Response response : searchCursor) {
+ groupResponses.add(response);
+ }
+
+ } catch (Exception e) {
+
+ LOGGER.error("User attributes validation failed.", e);
+ throw new AmbariLdapException(e.getMessage(), e);
+
+ } finally {
+ closeResources(ldapConnection, searchCursor);
+ }
+
+ return processGroupResults(groupResponses, ambariLdapConfiguration);
+ }
+
+ /**
+ * Binds to the LDAP server (anonimously or wit manager credentials)
+ *
+ * @param ambariLdapConfiguration configuration instance
+ * @param connection connection instance
+ * @throws LdapException if the bind operation fails
+ */
+ private void bind(AmbariLdapConfiguration ambariLdapConfiguration, LdapConnection connection) throws LdapException {
+ LOGGER.info("Connecting to LDAP ....");
+ if (!ambariLdapConfiguration.bindAnonimously()) {
+ LOGGER.debug("Anonimous binding not supported, binding with the manager detailas...");
+ connection.bind(ambariLdapConfiguration.managerDn(), ambariLdapConfiguration.managerPassword());
+ } else {
+ LOGGER.debug("Binding anonimously ...");
+ connection.bind();
+ }
+
+ if (!connection.isConnected()) {
+ LOGGER.error("Not connected to the LDAP server. Connection instance: {}", connection);
+ throw new IllegalStateException("The connection to the LDAP server is not alive");
+ }
+ LOGGER.info("Connected to LDAP.");
+ }
+
+
+ /**
+ * Extracts meaningful values from the search result.
+ *
+ * @param groupResponses the result entries returned by the search
+ * @param ambariLdapConfiguration holds the keys of the meaningful attributes
+ * @return a set with the group names the test user belongs to
+ */
+ private Set<String> processGroupResults(Set<Response> groupResponses, AmbariLdapConfiguration ambariLdapConfiguration) {
+ Set<String> groupStrSet = Sets.newHashSet();
+ for (Response response : groupResponses) {
+ Entry entry = ((SearchResultEntryDecorator) response).getEntry();
+ groupStrSet.add(entry.get(ambariLdapConfiguration.groupNameAttribute()).get().getString());
+ }
+
+ LOGGER.debug("Extracted group names from group search responses: {}", groupStrSet);
+ return groupStrSet;
+ }
+
+ private void closeResources(LdapConnection connection, SearchCursor searchCursor) {
+ LOGGER.debug("Housekeeping: closing the connection and the search cursor ...");
+
+ if (null != searchCursor) {
+ // this method is idempotent
+ searchCursor.close();
+ }
+
+ if (null != connection) {
+ try {
+ connection.close();
+ } catch (IOException e) {
+ LOGGER.error("Exception occurred while closing the connection", e);
+ }
+ }
+ }
+
+}
+
+
+
http://git-wip-us.apache.org/repos/asf/ambari/blob/5b7c55f6/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConnectionService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConnectionService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConnectionService.java
new file mode 100644
index 0000000..ced52fc
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConnectionService.java
@@ -0,0 +1,63 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service.ads;
+
+import javax.inject.Singleton;
+
+import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.service.LdapConnectionService;
+import org.apache.directory.ldap.client.api.LdapConnectionConfig;
+import org.apache.directory.ldap.client.api.LdapNetworkConnection;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Singleton
+public class DefaultLdapConnectionService implements LdapConnectionService {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(DefaultLdapConnectionService.class);
+
+ @Override
+ public LdapNetworkConnection createLdapConnection(AmbariLdapConfiguration ambariLdapConfiguration) {
+ LOGGER.debug("Creating ldap connection instance from: {}", ambariLdapConfiguration);
+ return new LdapNetworkConnection(getLdapConnectionConfig(ambariLdapConfiguration));
+ }
+
+ private LdapConnectionConfig getLdapConnectionConfig(AmbariLdapConfiguration ambariAmbariLdapConfiguration) {
+ LOGGER.debug("Creating a configuration instance based on the ambari configuration: {}", ambariAmbariLdapConfiguration);
+
+ LdapConnectionConfig ldapConnectionConfig = new LdapConnectionConfig();
+ ldapConnectionConfig.setLdapHost(ambariAmbariLdapConfiguration.ldapServerHost());
+ ldapConnectionConfig.setLdapPort(ambariAmbariLdapConfiguration.ldapServerPort());
+ ldapConnectionConfig.setUseSsl(ambariAmbariLdapConfiguration.useSSL());
+
+ // todo set the other values as required
+ return ldapConnectionConfig;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/5b7c55f6/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConfigurationValidatorServiceTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConfigurationValidatorServiceTest.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConfigurationValidatorServiceTest.java
deleted file mode 100644
index 663ea12..0000000
--- a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConfigurationValidatorServiceTest.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.ambari.server.ldap.service.ad;
-
-import static org.junit.Assert.assertNotNull;
-
-import java.util.Map;
-
-import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
-import org.apache.ambari.server.ldap.LdapConfigurationValidatorService;
-import org.apache.ambari.server.ldap.service.LdapConnectionService;
-import org.apache.directory.api.ldap.model.cursor.EntryCursor;
-import org.apache.directory.api.ldap.model.entry.Entry;
-import org.apache.directory.api.ldap.model.message.SearchScope;
-import org.apache.directory.ldap.client.api.LdapConnection;
-import org.apache.directory.ldap.client.api.LdapConnectionConfig;
-import org.apache.directory.ldap.client.api.LdapNetworkConnection;
-import org.apache.directory.shared.ldap.constants.SchemaConstants;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.Maps;
-
-public class DefaultLdapConfigurationValidatorServiceTest {
- private static final Logger LOGGER = LoggerFactory.getLogger(DefaultLdapConfigurationValidatorService.class);
- private static final String TEST_USER = "einstein";
-
- LdapConfigurationValidatorService ldapConfigurationValidatorService = new DefaultLdapConfigurationValidatorService();
-
-
- @Test
- public void testCheckAttributes() throws Exception {
-
- // WHEN
- LdapConnectionConfig config = new LdapConnectionConfig();
- config.setLdapHost("localhost");
- config.setLdapPort(389);
- LdapConnection connection = new LdapNetworkConnection(config);
-
- // THEN
- connection.anonymousBind();
-
-
- EntryCursor cursor = connection.search("dc=dev,dc=local", "(objectclass=*)", SearchScope.ONELEVEL);
-
- for (Entry entry : cursor) {
- assertNotNull(entry);
- System.out.println(entry);
- }
-
- cursor.close();
-
- }
-
- @Test
- public void testCheckUserAttributes() throws Exception {
- // GIVEN
- Map<String, Object> ldapPropsMap = Maps.newHashMap();
-
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.BIND_ANONIMOUSLY.propertyName(), "true");
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.LDAP_SERVER_HOST.propertyName(), "ldap.forumsys.com");
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.LDAP_SERVER_PORT.propertyName(), "389");
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.BASE_DN.propertyName(), "dc=example,dc=com");
-
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.USER_OBJECT_CLASS.propertyName(), SchemaConstants.PERSON_OC);
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.USER_NAME_ATTRIBUTE.propertyName(), SchemaConstants.UID_AT);
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.USER_SEARCH_BASE.propertyName(), "dc=example,dc=com");
-
-
- AmbariLdapConfiguration ambariLdapConfiguration = new AmbariLdapConfiguration(ldapPropsMap);
- LdapConnectionService connectionService = new DefaultLdapConnectionService();
- LdapNetworkConnection ldapConnection = connectionService.createLdapConnection(ambariLdapConfiguration);
-
- ldapConfigurationValidatorService.checkUserAttributes(ldapConnection, "einstein", "", ambariLdapConfiguration);
- }
-
- @Test
- public void testRetrieveGorupsForuser() throws Exception {
- // GIVEN
- Map<String, Object> ldapPropsMap = Maps.newHashMap();
-
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.BIND_ANONIMOUSLY.propertyName(), "true");
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.LDAP_SERVER_HOST.propertyName(), "ldap.forumsys.com");
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.LDAP_SERVER_PORT.propertyName(), "389");
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.BASE_DN.propertyName(), "dc=example,dc=com");
-
-
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.GROUP_OBJECT_CLASS.propertyName(), SchemaConstants.GROUP_OF_UNIQUE_NAMES_OC);
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.GROUP_NAME_ATTRIBUTE.propertyName(), SchemaConstants.CN_AT);
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.GROUP_MEMBER_ATTRIBUTE.propertyName(), SchemaConstants.UNIQUE_MEMBER_AT);
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.GROUP_SEARCH_BASE.propertyName(), "dc=example,dc=com");
-
-
- AmbariLdapConfiguration ambariLdapConfiguration = new AmbariLdapConfiguration(ldapPropsMap);
- LdapConnectionService connectionService = new DefaultLdapConnectionService();
- LdapNetworkConnection ldapConnection = connectionService.createLdapConnection(ambariLdapConfiguration);
-
- ldapConfigurationValidatorService.checkGroupAttributes(ldapConnection, "uid=einstein,dc=example,dc=com", ambariLdapConfiguration);
- }
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/ambari/blob/5b7c55f6/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationValidatorServiceTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationValidatorServiceTest.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationValidatorServiceTest.java
new file mode 100644
index 0000000..1c7f75d
--- /dev/null
+++ b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationValidatorServiceTest.java
@@ -0,0 +1,113 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service.ads;
+
+import static org.junit.Assert.assertNotNull;
+
+import java.util.Map;
+
+import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.LdapConfigurationValidatorService;
+import org.apache.ambari.server.ldap.service.LdapConnectionService;
+import org.apache.directory.api.ldap.model.constants.SchemaConstants;
+import org.apache.directory.api.ldap.model.cursor.EntryCursor;
+import org.apache.directory.api.ldap.model.entry.Entry;
+import org.apache.directory.api.ldap.model.message.SearchScope;
+import org.apache.directory.ldap.client.api.LdapConnection;
+import org.apache.directory.ldap.client.api.LdapConnectionConfig;
+import org.apache.directory.ldap.client.api.LdapNetworkConnection;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.collect.Maps;
+
+public class DefaultLdapConfigurationValidatorServiceTest {
+ private static final Logger LOGGER = LoggerFactory.getLogger(DefaultLdapConfigurationValidatorService.class);
+ private static final String TEST_USER = "einstein";
+
+ LdapConfigurationValidatorService ldapConfigurationValidatorService = new DefaultLdapConfigurationValidatorService();
+
+
+ @Test
+ public void testCheckAttributes() throws Exception {
+
+ // WHEN
+ LdapConnectionConfig config = new LdapConnectionConfig();
+ config.setLdapHost("localhost");
+ config.setLdapPort(389);
+ LdapConnection connection = new LdapNetworkConnection(config);
+
+ // THEN
+ connection.anonymousBind();
+
+
+ EntryCursor cursor = connection.search("dc=dev,dc=local", "(objectclass=*)", SearchScope.ONELEVEL);
+
+ for (Entry entry : cursor) {
+ assertNotNull(entry);
+ System.out.println(entry);
+ }
+
+ cursor.close();
+
+ }
+
+ @Test
+ public void testCheckUserAttributes() throws Exception {
+ // GIVEN
+ Map<String, Object> ldapPropsMap = Maps.newHashMap();
+
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.BIND_ANONIMOUSLY.propertyName(), "true");
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.LDAP_SERVER_HOST.propertyName(), "ldap.forumsys.com");
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.LDAP_SERVER_PORT.propertyName(), "389");
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.BASE_DN.propertyName(), "dc=example,dc=com");
+
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.USER_OBJECT_CLASS.propertyName(), SchemaConstants.PERSON_OC);
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.USER_NAME_ATTRIBUTE.propertyName(), SchemaConstants.UID_AT);
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.USER_SEARCH_BASE.propertyName(), "dc=example,dc=com");
+
+
+ AmbariLdapConfiguration ambariLdapConfiguration = new AmbariLdapConfiguration(ldapPropsMap);
+ LdapConnectionService connectionService = new DefaultLdapConnectionService();
+ LdapNetworkConnection ldapConnection = connectionService.createLdapConnection(ambariLdapConfiguration);
+
+ ldapConfigurationValidatorService.checkUserAttributes(ldapConnection, "einstein", "", ambariLdapConfiguration);
+ }
+
+ @Test
+ public void testRetrieveGorupsForuser() throws Exception {
+ // GIVEN
+ Map<String, Object> ldapPropsMap = Maps.newHashMap();
+
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.BIND_ANONIMOUSLY.propertyName(), "true");
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.LDAP_SERVER_HOST.propertyName(), "ldap.forumsys.com");
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.LDAP_SERVER_PORT.propertyName(), "389");
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.BASE_DN.propertyName(), "dc=example,dc=com");
+
+
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.GROUP_OBJECT_CLASS.propertyName(), SchemaConstants.GROUP_OF_UNIQUE_NAMES_OC);
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.GROUP_NAME_ATTRIBUTE.propertyName(), SchemaConstants.CN_AT);
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.GROUP_MEMBER_ATTRIBUTE.propertyName(), SchemaConstants.UNIQUE_MEMBER_AT);
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.GROUP_SEARCH_BASE.propertyName(), "dc=example,dc=com");
+
+
+ AmbariLdapConfiguration ambariLdapConfiguration = new AmbariLdapConfiguration(ldapPropsMap);
+ LdapConnectionService connectionService = new DefaultLdapConnectionService();
+ LdapNetworkConnection ldapConnection = connectionService.createLdapConnection(ambariLdapConfiguration);
+
+ ldapConfigurationValidatorService.checkGroupAttributes(ldapConnection, "uid=einstein,dc=example,dc=com", ambariLdapConfiguration);
+ }
+}
\ No newline at end of file
[05/33] ambari git commit: AMBARI-22226. RU: Downgrade is failed ZKFC
(ncole)
Posted by lp...@apache.org.
AMBARI-22226. RU: Downgrade is failed ZKFC (ncole)
Project: http://git-wip-us.apache.org/repos/asf/ambari/repo
Commit: http://git-wip-us.apache.org/repos/asf/ambari/commit/20faae7a
Tree: http://git-wip-us.apache.org/repos/asf/ambari/tree/20faae7a
Diff: http://git-wip-us.apache.org/repos/asf/ambari/diff/20faae7a
Branch: refs/heads/feature-branch-AMBARI-21307
Commit: 20faae7a3647943b61e46f41ce27da81e91dc519
Parents: 3a0d168
Author: Nate Cole <nc...@hortonworks.com>
Authored: Fri Oct 13 08:42:12 2017 -0400
Committer: Nate Cole <nc...@hortonworks.com>
Committed: Fri Oct 13 09:19:08 2017 -0400
----------------------------------------------------------------------
.../upgrades/FinalizeUpgradeAction.java | 21 ++++++++++----------
1 file changed, 10 insertions(+), 11 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/ambari/blob/20faae7a/ambari-server/src/main/java/org/apache/ambari/server/serveraction/upgrades/FinalizeUpgradeAction.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/serveraction/upgrades/FinalizeUpgradeAction.java b/ambari-server/src/main/java/org/apache/ambari/server/serveraction/upgrades/FinalizeUpgradeAction.java
index d6876d9..87ea1fc 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/serveraction/upgrades/FinalizeUpgradeAction.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/serveraction/upgrades/FinalizeUpgradeAction.java
@@ -271,7 +271,7 @@ public class FinalizeUpgradeAction extends AbstractUpgradeServerAction {
errors.size())).append(System.lineSeparator());
for (InfoTuple error : errors) {
- messageBuff.append(String.format("%s: $s (current = %s, desired = %s ", error.hostName,
+ messageBuff.append(String.format("%s: %s (current = %s, desired = %s)", error.hostName,
error.componentName, error.currentVersion, error.targetVersion));
messageBuff.append(System.lineSeparator());
@@ -367,23 +367,22 @@ public class FinalizeUpgradeAction extends AbstractUpgradeServerAction {
Set<InfoTuple> errors = new TreeSet<>();
Cluster cluster = upgradeContext.getCluster();
- RepositoryVersionEntity repositoryVersionEntity = upgradeContext.getRepositoryVersion();
- StackId targetStackId = repositoryVersionEntity.getStackId();
-
Set<String> servicesParticipating = upgradeContext.getSupportedServices();
for (String serviceName : servicesParticipating) {
Service service = cluster.getService(serviceName);
- String targetVersion = upgradeContext.getTargetVersion(serviceName);
+ RepositoryVersionEntity repositoryVersionEntity = upgradeContext.getTargetRepositoryVersion(serviceName);
+ StackId targetStackId = repositoryVersionEntity.getStackId();
+ String targetVersion = repositoryVersionEntity.getVersion();
for (ServiceComponent serviceComponent : service.getServiceComponents().values()) {
- for (ServiceComponentHost serviceComponentHost : serviceComponent.getServiceComponentHosts().values()) {
- ComponentInfo componentInfo = ambariMetaInfo.getComponent(targetStackId.getStackName(),
- targetStackId.getStackVersion(), service.getName(), serviceComponent.getName());
+ ComponentInfo componentInfo = ambariMetaInfo.getComponent(targetStackId.getStackName(),
+ targetStackId.getStackVersion(), service.getName(), serviceComponent.getName());
- if (!componentInfo.isVersionAdvertised()) {
- continue;
- }
+ if (!componentInfo.isVersionAdvertised()) {
+ continue;
+ }
+ for (ServiceComponentHost serviceComponentHost : serviceComponent.getServiceComponentHosts().values()) {
if (!StringUtils.equals(targetVersion, serviceComponentHost.getVersion())) {
errors.add(new InfoTuple(service.getName(), serviceComponent.getName(),
serviceComponentHost.getHostName(), serviceComponentHost.getVersion(),
[09/33] ambari git commit: AMBARI-21307 Rest resource for supporting
ambari configurations
Posted by lp...@apache.org.
AMBARI-21307 Rest resource for supporting ambari configurations
Project: http://git-wip-us.apache.org/repos/asf/ambari/repo
Commit: http://git-wip-us.apache.org/repos/asf/ambari/commit/47350522
Tree: http://git-wip-us.apache.org/repos/asf/ambari/tree/47350522
Diff: http://git-wip-us.apache.org/repos/asf/ambari/diff/47350522
Branch: refs/heads/feature-branch-AMBARI-21307
Commit: 473505226b6d1cdca200011c13b68ae99fa83248
Parents: 20faae7
Author: lpuskas <lp...@apache.org>
Authored: Wed Jul 5 14:20:18 2017 +0200
Committer: lpuskas <lp...@apache.org>
Committed: Fri Oct 13 17:20:48 2017 +0200
----------------------------------------------------------------------
.../resources/ResourceInstanceFactoryImpl.java | 4 +
.../services/AmbariConfigurationService.java | 146 +++++++++++
.../internal/AbstractProviderModule.java | 2 +-
.../AmbariConfigurationResourceProvider.java | 247 +++++++++++++++++++
.../internal/DefaultProviderModule.java | 26 +-
.../ambari/server/controller/spi/Resource.java | 5 +-
.../server/orm/dao/AmbariConfigurationDAO.java | 92 +++++++
.../orm/entities/AmbariConfigurationEntity.java | 70 ++++++
.../orm/entities/ConfigurationBaseEntity.java | 159 ++++++++++++
.../authorization/RoleAuthorization.java | 95 +++----
.../resources/Ambari-DDL-Postgres-CREATE.sql | 25 +-
.../src/main/resources/META-INF/persistence.xml | 2 +
12 files changed, 809 insertions(+), 64 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/ambari/blob/47350522/ambari-server/src/main/java/org/apache/ambari/server/api/resources/ResourceInstanceFactoryImpl.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/api/resources/ResourceInstanceFactoryImpl.java b/ambari-server/src/main/java/org/apache/ambari/server/api/resources/ResourceInstanceFactoryImpl.java
index d0d115d..f5fb6e9 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/api/resources/ResourceInstanceFactoryImpl.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/api/resources/ResourceInstanceFactoryImpl.java
@@ -471,6 +471,10 @@ public class ResourceInstanceFactoryImpl implements ResourceInstanceFactory {
case RemoteCluster:
resourceDefinition = new RemoteClusterResourceDefinition();
break;
+ case AmbariConfiguration:
+ resourceDefinition = new SimpleResourceDefinition(Resource.Type.AmbariConfiguration, "ambariconfiguration", "ambariconfigurations");
+
+ break;
default:
throw new IllegalArgumentException("Unsupported resource type: " + type);
http://git-wip-us.apache.org/repos/asf/ambari/blob/47350522/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationService.java b/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationService.java
new file mode 100644
index 0000000..0fa6e44
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/api/services/AmbariConfigurationService.java
@@ -0,0 +1,146 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.api.services;
+
+import java.util.Collections;
+
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+
+import org.apache.ambari.server.controller.spi.Resource;
+import org.apache.http.HttpStatus;
+
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiImplicitParam;
+import io.swagger.annotations.ApiImplicitParams;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiResponse;
+import io.swagger.annotations.ApiResponses;
+
+/**
+ * Rest endpoint for managing ambari configurations. Supports CRUD operations.
+ * Ambari configurations are resources that relate to the ambari server instance even before a cluster is provisioned.
+ *
+ * Ambari configuration resources may be shared with components and services in the cluster
+ * (by recommending them as default values)
+ *
+ * Eg. LDAP configuration is stored as ambariconfiguration.
+ * The request payload has the form:
+ *
+ * <pre>
+ * {
+ * "AmbariConfiguration": {
+ * "type": "ldap-configuration",
+ * "data": [
+ * {
+ * "authentication.ldap.primaryUrl": "localhost:33389"
+ * },
+ * {
+ * "authentication.ldap.secondaryUrl": "localhost:333"
+ * },
+ * {
+ * "authentication.ldap.baseDn": "dc=ambari,dc=apache,dc=org"
+ * }
+ * // ......
+ * ]
+ * }
+ * }
+ * </pre>
+ */
+@Path("/configurations/")
+@Api(value = "/configurations", description = "Endpoint for Ambari configuration related operations")
+public class AmbariConfigurationService extends BaseService {
+
+ /**
+ * Creates an ambari configuration resource.
+ *
+ * @param body the payload in json format
+ * @param headers http headers
+ * @param uri request uri information
+ * @return
+ */
+ @POST
+ @Produces(MediaType.TEXT_PLAIN)
+ @ApiOperation(value = "Creates an ambari configuration resource")
+ @ApiImplicitParams({
+ @ApiImplicitParam(dataType = "", paramType = PARAM_TYPE_BODY)
+ })
+ @ApiResponses({
+ @ApiResponse(code = HttpStatus.SC_CREATED, message = MSG_SUCCESSFUL_OPERATION),
+ @ApiResponse(code = HttpStatus.SC_ACCEPTED, message = MSG_REQUEST_ACCEPTED),
+ @ApiResponse(code = HttpStatus.SC_BAD_REQUEST, message = MSG_INVALID_ARGUMENTS),
+ @ApiResponse(code = HttpStatus.SC_CONFLICT, message = MSG_RESOURCE_ALREADY_EXISTS),
+ @ApiResponse(code = HttpStatus.SC_UNAUTHORIZED, message = MSG_NOT_AUTHENTICATED),
+ @ApiResponse(code = HttpStatus.SC_FORBIDDEN, message = MSG_PERMISSION_DENIED),
+ @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = MSG_SERVER_ERROR),
+ })
+ public Response createAmbariConfiguration(String body, @Context HttpHeaders headers, @Context UriInfo uri) {
+ return handleRequest(headers, body, uri, Request.Type.POST, createResource(Resource.Type.AmbariConfiguration,
+ Collections.EMPTY_MAP));
+ }
+
+ @GET
+ @Produces(MediaType.TEXT_PLAIN)
+ @ApiOperation(value = "Retrieve ambari configuration resources")
+ public Response getAmbariConfigurations(String body, @Context HttpHeaders headers, @Context UriInfo uri) {
+ return handleRequest(headers, body, uri, Request.Type.GET, createResource(Resource.Type.AmbariConfiguration,
+ Collections.EMPTY_MAP));
+ }
+
+ @GET
+ @Path("{configurationId}")
+ @Produces(MediaType.TEXT_PLAIN)
+ @ApiOperation(value = "Retrieve ambari configuration resource")
+ public Response getAmbariConfiguration(String body, @Context HttpHeaders headers, @Context UriInfo uri,
+ @PathParam("configurationId") String configurationId) {
+ return handleRequest(headers, body, uri, Request.Type.GET, createResource(Resource.Type.AmbariConfiguration,
+ Collections.singletonMap(Resource.Type.AmbariConfiguration, configurationId)));
+ }
+
+ @PUT
+ @Produces(MediaType.TEXT_PLAIN)
+ @ApiOperation(value = "Update ambari configuration resources")
+ public Response updateAmbariConfiguration() {
+ throw new UnsupportedOperationException("Not yet implemented");
+ }
+
+ @DELETE
+ @Path("{configurationId}")
+ @Produces(MediaType.TEXT_PLAIN)
+ @ApiOperation(value = "Deletes an ambari configuration resource")
+ @ApiResponses({
+ @ApiResponse(code = HttpStatus.SC_OK, message = MSG_SUCCESSFUL_OPERATION),
+ @ApiResponse(code = HttpStatus.SC_NOT_FOUND, message = MSG_RESOURCE_NOT_FOUND),
+ @ApiResponse(code = HttpStatus.SC_UNAUTHORIZED, message = MSG_NOT_AUTHENTICATED),
+ @ApiResponse(code = HttpStatus.SC_FORBIDDEN, message = MSG_PERMISSION_DENIED),
+ @ApiResponse(code = HttpStatus.SC_INTERNAL_SERVER_ERROR, message = MSG_SERVER_ERROR),
+ })
+ public Response deleteAmbariConfiguration(String body, @Context HttpHeaders headers, @Context UriInfo uri,
+ @PathParam("configurationId") String configurationId) {
+ return handleRequest(headers, body, uri, Request.Type.DELETE, createResource(Resource.Type.AmbariConfiguration,
+ Collections.singletonMap(Resource.Type.AmbariConfiguration, configurationId)));
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/47350522/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AbstractProviderModule.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AbstractProviderModule.java b/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AbstractProviderModule.java
index 1cd2d10..1501a01 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AbstractProviderModule.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AbstractProviderModule.java
@@ -224,7 +224,7 @@ public abstract class AbstractProviderModule implements ProviderModule,
* are going to work unless refactoring is complete.
*/
@Inject
- AmbariManagementController managementController;
+ protected AmbariManagementController managementController;
@Inject
TimelineMetricCacheProvider metricCacheProvider;
http://git-wip-us.apache.org/repos/asf/ambari/blob/47350522/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AmbariConfigurationResourceProvider.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AmbariConfigurationResourceProvider.java b/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AmbariConfigurationResourceProvider.java
new file mode 100644
index 0000000..5e5af9e
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AmbariConfigurationResourceProvider.java
@@ -0,0 +1,247 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.controller.internal;
+
+import java.util.Calendar;
+import java.util.Collections;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import javax.inject.Inject;
+
+import org.apache.ambari.server.AmbariException;
+import org.apache.ambari.server.StaticallyInject;
+import org.apache.ambari.server.controller.spi.NoSuchParentResourceException;
+import org.apache.ambari.server.controller.spi.NoSuchResourceException;
+import org.apache.ambari.server.controller.spi.Predicate;
+import org.apache.ambari.server.controller.spi.Request;
+import org.apache.ambari.server.controller.spi.RequestStatus;
+import org.apache.ambari.server.controller.spi.Resource;
+import org.apache.ambari.server.controller.spi.ResourceAlreadyExistsException;
+import org.apache.ambari.server.controller.spi.SystemException;
+import org.apache.ambari.server.controller.spi.UnsupportedPropertyException;
+import org.apache.ambari.server.controller.utilities.PredicateHelper;
+import org.apache.ambari.server.orm.dao.AmbariConfigurationDAO;
+import org.apache.ambari.server.orm.entities.AmbariConfigurationEntity;
+import org.apache.ambari.server.orm.entities.ConfigurationBaseEntity;
+import org.apache.ambari.server.security.authorization.RoleAuthorization;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.collect.Sets;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+
+/**
+ * Resource provider for AmbariConfiguration resources.
+ */
+@StaticallyInject
+public class AmbariConfigurationResourceProvider extends AbstractAuthorizedResourceProvider {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(AmbariConfigurationResourceProvider.class);
+ private static final String DEFAULT_VERSION_TAG = "Default version";
+ private static final Integer DEFAULT_VERSION = 1;
+
+ /**
+ * Resource property id constants.
+ */
+ private enum ResourcePropertyId {
+
+ ID("AmbariConfiguration/id"),
+ TYPE("AmbariConfiguration/type"),
+ VERSION("AmbariConfiguration/version"),
+ VERSION_TAG("AmbariConfiguration/version_tag"),
+ DATA("AmbariConfiguration/data");
+
+ private String propertyId;
+
+ ResourcePropertyId(String propertyId) {
+ this.propertyId = propertyId;
+ }
+
+ String getPropertyId() {
+ return this.propertyId;
+ }
+
+ public static ResourcePropertyId fromString(String propertyIdStr) {
+ ResourcePropertyId propertyIdFromStr = null;
+
+ for (ResourcePropertyId id : ResourcePropertyId.values()) {
+ if (id.getPropertyId().equals(propertyIdStr)) {
+ propertyIdFromStr = id;
+ break;
+ }
+ }
+
+ if (propertyIdFromStr == null) {
+ throw new IllegalArgumentException("Unsupported property type: " + propertyIdStr);
+ }
+
+ return propertyIdFromStr;
+
+ }
+ }
+
+ private static Set<String> properties = Sets.newHashSet(
+ ResourcePropertyId.ID.getPropertyId(),
+ ResourcePropertyId.TYPE.getPropertyId(),
+ ResourcePropertyId.VERSION.getPropertyId(),
+ ResourcePropertyId.VERSION_TAG.getPropertyId(),
+ ResourcePropertyId.DATA.getPropertyId());
+
+ private static Map<Resource.Type, String> pkPropertyMap = Collections.unmodifiableMap(
+ new HashMap<Resource.Type, String>() {{
+ put(Resource.Type.AmbariConfiguration, ResourcePropertyId.ID.getPropertyId());
+ }}
+ );
+
+
+ @Inject
+ private static AmbariConfigurationDAO ambariConfigurationDAO;
+
+ private Gson gson;
+
+ protected AmbariConfigurationResourceProvider() {
+ super(properties, pkPropertyMap);
+ setRequiredCreateAuthorizations(EnumSet.of(RoleAuthorization.AMBARI_MANAGE_CONFIGURATION));
+ setRequiredDeleteAuthorizations(EnumSet.of(RoleAuthorization.AMBARI_MANAGE_CONFIGURATION));
+
+ gson = new GsonBuilder().create();
+ }
+
+ @Override
+ protected Set<String> getPKPropertyIds() {
+ return Sets.newHashSet("AmbariConfiguration/id");
+ }
+
+ @Override
+ public RequestStatus createResourcesAuthorized(Request request) throws SystemException, UnsupportedPropertyException,
+ ResourceAlreadyExistsException, NoSuchParentResourceException {
+
+ LOGGER.info("Creating new ambari configuration resource ...");
+ AmbariConfigurationEntity ambariConfigurationEntity = getEntityFromRequest(request);
+
+ LOGGER.info("Persisting new ambari configuration: {} ", ambariConfigurationEntity);
+ ambariConfigurationDAO.persist(ambariConfigurationEntity);
+
+ return getRequestStatus(null);
+ }
+
+
+ @Override
+ protected Set<Resource> getResourcesAuthorized(Request request, Predicate predicate) throws SystemException,
+ UnsupportedPropertyException, NoSuchResourceException, NoSuchParentResourceException {
+ Set<Resource> resources = Sets.newHashSet();
+
+ List<AmbariConfigurationEntity> ambariConfigurationEntities = ambariConfigurationDAO.findAll();
+ for (AmbariConfigurationEntity ambariConfigurationEntity : ambariConfigurationEntities) {
+ try {
+ resources.add(toResource(ambariConfigurationEntity, getPropertyIds()));
+ } catch (AmbariException e) {
+ LOGGER.error("Error while retrieving ambari configuration", e);
+ }
+ }
+ return resources;
+ }
+
+ @Override
+ protected RequestStatus deleteResourcesAuthorized(Request request, Predicate predicate) throws SystemException,
+ UnsupportedPropertyException, NoSuchResourceException, NoSuchParentResourceException {
+
+ Long idFromRequest = Long.valueOf((String) PredicateHelper.getProperties(predicate).get(ResourcePropertyId.ID.getPropertyId()));
+
+ if (null == idFromRequest) {
+ LOGGER.debug("No resource id provided in the request");
+ } else {
+ LOGGER.debug("Deleting amari configuration with id: {}", idFromRequest);
+ try {
+ ambariConfigurationDAO.deleteById(idFromRequest);
+ } catch (IllegalStateException e) {
+ throw new NoSuchResourceException(e.getMessage());
+ }
+
+ }
+
+ return getRequestStatus(null);
+
+ }
+
+ private Resource toResource(AmbariConfigurationEntity entity, Set<String> requestedIds) throws AmbariException {
+ Resource resource = new ResourceImpl(Resource.Type.AmbariConfiguration);
+ Set<Map<String, String>> configurationSet = gson.fromJson(entity.getConfigurationBaseEntity().getConfigurationData(), Set.class);
+
+ setResourceProperty(resource, ResourcePropertyId.ID.getPropertyId(), entity.getId(), requestedIds);
+ setResourceProperty(resource, ResourcePropertyId.TYPE.getPropertyId(), entity.getConfigurationBaseEntity().getType(), requestedIds);
+ setResourceProperty(resource, ResourcePropertyId.DATA.getPropertyId(), configurationSet, requestedIds);
+
+ return resource;
+ }
+
+ private AmbariConfigurationEntity getEntityFromRequest(Request request) {
+
+ AmbariConfigurationEntity ambariConfigurationEntity = new AmbariConfigurationEntity();
+ ambariConfigurationEntity.setConfigurationBaseEntity(new ConfigurationBaseEntity());
+
+
+ for (ResourcePropertyId resourcePropertyId : ResourcePropertyId.values()) {
+ Object requestValue = getValueFromRequest(resourcePropertyId, request);
+
+ switch (resourcePropertyId) {
+ case DATA:
+ if (requestValue == null) {
+ throw new IllegalArgumentException("No configuration data is provided in the request");
+ }
+
+ ambariConfigurationEntity.getConfigurationBaseEntity().setConfigurationData(gson.toJson(requestValue));
+ break;
+ case TYPE:
+ ambariConfigurationEntity.getConfigurationBaseEntity().setType((String) requestValue);
+ break;
+
+ case VERSION:
+ Integer version = (requestValue == null) ? DEFAULT_VERSION : Integer.valueOf((Integer) requestValue);
+ ambariConfigurationEntity.getConfigurationBaseEntity().setVersion((version));
+ break;
+ case VERSION_TAG:
+ String versionTag = requestValue == null ? DEFAULT_VERSION_TAG : (String) requestValue;
+ ambariConfigurationEntity.getConfigurationBaseEntity().setVersionTag(versionTag);
+ break;
+ default:
+ LOGGER.debug("Ignored property in the request: {}", resourcePropertyId);
+ break;
+ }
+ }
+ ambariConfigurationEntity.getConfigurationBaseEntity().setCreateTimestamp(Calendar.getInstance().getTimeInMillis());
+ return ambariConfigurationEntity;
+
+ }
+
+ private Object getValueFromRequest(ResourcePropertyId resourcePropertyIdEnum, Request request) {
+ LOGGER.debug("Locating resource property [{}] in the request ...", resourcePropertyIdEnum);
+ Object requestValue = null;
+ for (Map<String, Object> propertyMap : request.getProperties()) {
+ if (propertyMap.containsKey(resourcePropertyIdEnum.getPropertyId())) {
+ requestValue = propertyMap.get(resourcePropertyIdEnum.getPropertyId());
+ LOGGER.debug("Found resource property {} in the request, value: {} ...", resourcePropertyIdEnum, requestValue);
+ break;
+ }
+ }
+ return requestValue;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/47350522/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/DefaultProviderModule.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/DefaultProviderModule.java b/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/DefaultProviderModule.java
index 43779a3..fdf4a97 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/DefaultProviderModule.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/DefaultProviderModule.java
@@ -21,20 +21,18 @@ package org.apache.ambari.server.controller.internal;
import java.util.Map;
import java.util.Set;
-import org.apache.ambari.server.controller.AmbariManagementController;
-import org.apache.ambari.server.controller.AmbariServer;
import org.apache.ambari.server.controller.spi.Resource;
import org.apache.ambari.server.controller.spi.ResourceProvider;
import org.apache.ambari.server.controller.utilities.PropertyHelper;
-
-import com.google.inject.Inject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* The default provider module implementation.
*/
public class DefaultProviderModule extends AbstractProviderModule {
- @Inject
- private AmbariManagementController managementController;
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(DefaultProviderModule.class);
// ----- Constructors ------------------------------------------------------
@@ -42,9 +40,7 @@ public class DefaultProviderModule extends AbstractProviderModule {
* Create a default provider module.
*/
public DefaultProviderModule() {
- if (managementController == null) {
- managementController = AmbariServer.getController();
- }
+ super();
}
@@ -52,8 +48,10 @@ public class DefaultProviderModule extends AbstractProviderModule {
@Override
protected ResourceProvider createResourceProvider(Resource.Type type) {
- Set<String> propertyIds = PropertyHelper.getPropertyIds(type);
- Map<Resource.Type,String> keyPropertyIds = PropertyHelper.getKeyPropertyIds(type);
+
+ LOGGER.debug("Creating resource provider for the type: {}", type);
+ Set<String> propertyIds = PropertyHelper.getPropertyIds(type);
+ Map<Resource.Type, String> keyPropertyIds = PropertyHelper.getKeyPropertyIds(type);
switch (type.getInternalType()) {
case Workflow:
@@ -118,10 +116,12 @@ public class DefaultProviderModule extends AbstractProviderModule {
return new ArtifactResourceProvider(managementController);
case RemoteCluster:
return new RemoteClusterResourceProvider();
-
+ case AmbariConfiguration:
+ return new AmbariConfigurationResourceProvider();
default:
+ LOGGER.debug("Delegating creation of resource provider for: {} to the AbstractControllerResourceProvider", type.getInternalType());
return AbstractControllerResourceProvider.getResourceProvider(type, propertyIds,
- keyPropertyIds, managementController);
+ keyPropertyIds, managementController);
}
}
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/47350522/ambari-server/src/main/java/org/apache/ambari/server/controller/spi/Resource.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/controller/spi/Resource.java b/ambari-server/src/main/java/org/apache/ambari/server/controller/spi/Resource.java
index 362b4e6..7835373 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/controller/spi/Resource.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/controller/spi/Resource.java
@@ -160,7 +160,8 @@ public interface Resource {
VersionDefinition,
ClusterKerberosDescriptor,
LoggingQuery,
- RemoteCluster;
+ RemoteCluster,
+ AmbariConfiguration;
/**
* Get the {@link Type} that corresponds to this InternalType.
@@ -282,6 +283,8 @@ public interface Resource {
public static final Type ClusterKerberosDescriptor = InternalType.ClusterKerberosDescriptor.getType();
public static final Type LoggingQuery = InternalType.LoggingQuery.getType();
public static final Type RemoteCluster = InternalType.RemoteCluster.getType();
+ public static final Type AmbariConfiguration = InternalType.AmbariConfiguration.getType();
+
/**
* The type name.
http://git-wip-us.apache.org/repos/asf/ambari/blob/47350522/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/AmbariConfigurationDAO.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/AmbariConfigurationDAO.java b/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/AmbariConfigurationDAO.java
new file mode 100644
index 0000000..dea37eb
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/AmbariConfigurationDAO.java
@@ -0,0 +1,92 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.orm.dao;
+
+import java.util.List;
+
+import javax.inject.Inject;
+import javax.inject.Provider;
+import javax.inject.Singleton;
+import javax.persistence.EntityManager;
+import javax.persistence.TypedQuery;
+
+import org.apache.ambari.server.orm.RequiresSession;
+import org.apache.ambari.server.orm.entities.AmbariConfigurationEntity;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.inject.persist.Transactional;
+
+/**
+ * DAO dealing with ambari configuration related JPA operations.
+ */
+
+@Singleton
+// todo extend CrudDao (amend crud dao to handle NPEs)
+public class AmbariConfigurationDAO {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(AmbariConfigurationDAO.class);
+
+ @Inject
+ private Provider<EntityManager> entityManagerProvider;
+
+ /**
+ * DAO utilities for dealing mostly with {@link TypedQuery} results.
+ */
+ @Inject
+ private DaoUtils daoUtils;
+
+ public AmbariConfigurationEntity findByid(Long id) {
+ return entityManagerProvider.get().find(AmbariConfigurationEntity.class, id);
+ }
+
+ @RequiresSession
+ @Transactional
+ public void persist(AmbariConfigurationEntity entity) {
+ LOGGER.debug("Persisting ambari configuration: {}", entity);
+ entityManagerProvider.get().persist(entity);
+ }
+
+ @RequiresSession
+ public List<AmbariConfigurationEntity> findAll() {
+ TypedQuery<AmbariConfigurationEntity> query = entityManagerProvider.get().createNamedQuery(
+ "AmbariConfigurationEntity.findAll", AmbariConfigurationEntity.class);
+ return daoUtils.selectList(query);
+ }
+
+
+ @RequiresSession
+ @Transactional
+ public void deleteById(Long ambariConfigurationId) {
+
+ if (ambariConfigurationId == null) {
+ throw new IllegalArgumentException("No Ambari Configuration id provided.");
+ }
+
+ LOGGER.debug("Removing Ambari Configuration with id :{}", ambariConfigurationId);
+
+ AmbariConfigurationEntity ambariConfigurationEntity = findByid(ambariConfigurationId);
+ if (ambariConfigurationEntity == null) {
+ String msg = String.format("No Ambari Configuration found with id: %s", ambariConfigurationId);
+ LOGGER.debug(msg);
+ throw new IllegalStateException(msg);
+ }
+
+ entityManagerProvider.get().remove(ambariConfigurationEntity);
+ LOGGER.debug("Ambari Configuration with id: {}", ambariConfigurationId);
+ }
+
+
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/47350522/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/AmbariConfigurationEntity.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/AmbariConfigurationEntity.java b/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/AmbariConfigurationEntity.java
new file mode 100644
index 0000000..34fa221
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/AmbariConfigurationEntity.java
@@ -0,0 +1,70 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.orm.entities;
+
+import javax.persistence.CascadeType;
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.JoinColumn;
+import javax.persistence.MapsId;
+import javax.persistence.NamedQueries;
+import javax.persistence.NamedQuery;
+import javax.persistence.OneToOne;
+import javax.persistence.Table;
+
+@Entity
+@Table(name = "ambari_configuration")
+@NamedQueries({
+ @NamedQuery(
+ name = "AmbariConfigurationEntity.findAll",
+ query = "select ace from AmbariConfigurationEntity ace")
+})
+
+public class AmbariConfigurationEntity {
+
+ @Id
+ @Column(name = "id")
+ private Long id;
+
+ @OneToOne(cascade = CascadeType.ALL)
+ @MapsId
+ @JoinColumn(name = "id")
+ private ConfigurationBaseEntity configurationBaseEntity;
+
+ public Long getId() {
+ return id;
+ }
+
+ public void setId(Long id) {
+ this.id = id;
+ }
+
+ public ConfigurationBaseEntity getConfigurationBaseEntity() {
+ return configurationBaseEntity;
+ }
+
+ public void setConfigurationBaseEntity(ConfigurationBaseEntity configurationBaseEntity) {
+ this.configurationBaseEntity = configurationBaseEntity;
+ }
+
+ @Override
+ public String toString() {
+ return "AmbariConfigurationEntity{" +
+ "id=" + id +
+ ", configurationBaseEntity=" + configurationBaseEntity +
+ '}';
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/47350522/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/ConfigurationBaseEntity.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/ConfigurationBaseEntity.java b/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/ConfigurationBaseEntity.java
new file mode 100644
index 0000000..9ad30d7
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/orm/entities/ConfigurationBaseEntity.java
@@ -0,0 +1,159 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.orm.entities;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
+import javax.persistence.Id;
+import javax.persistence.Table;
+import javax.persistence.TableGenerator;
+
+import org.apache.commons.lang3.builder.EqualsBuilder;
+import org.apache.commons.lang3.builder.HashCodeBuilder;
+
+@Table(name = "configuration_base")
+@TableGenerator(
+ name = "configuration_id_generator",
+ table = "ambari_sequences",
+ pkColumnName = "sequence_name",
+ valueColumnName = "sequence_value",
+ pkColumnValue = "configuration_id_seq",
+ initialValue = 1
+)
+@Entity
+public class ConfigurationBaseEntity {
+
+ @Id
+ @Column(name = "id")
+ @GeneratedValue(strategy = GenerationType.TABLE, generator = "configuration_id_generator")
+ private Long id;
+
+ @Column(name = "version")
+ private Integer version;
+
+ @Column(name = "version_tag")
+ private String versionTag;
+
+ @Column(name = "type")
+ private String type;
+
+ @Column(name = "data")
+ private String configurationData;
+
+ @Column(name = "attributes")
+ private String configurationAttributes;
+
+ @Column(name = "create_timestamp")
+ private Long createTimestamp;
+
+ public Long getId() {
+ return id;
+ }
+
+ public Integer getVersion() {
+ return version;
+ }
+
+ public void setVersion(Integer version) {
+ this.version = version;
+ }
+
+ public String getVersionTag() {
+ return versionTag;
+ }
+
+ public void setVersionTag(String versionTag) {
+ this.versionTag = versionTag;
+ }
+
+ public String getType() {
+ return type;
+ }
+
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ public String getConfigurationData() {
+ return configurationData;
+ }
+
+ public void setConfigurationData(String configurationData) {
+ this.configurationData = configurationData;
+ }
+
+ public String getConfigurationAttributes() {
+ return configurationAttributes;
+ }
+
+ public void setConfigurationAttributes(String configurationAttributes) {
+ this.configurationAttributes = configurationAttributes;
+ }
+
+ public Long getCreateTimestamp() {
+ return createTimestamp;
+ }
+
+ public void setCreateTimestamp(Long createTimestamp) {
+ this.createTimestamp = createTimestamp;
+ }
+
+ @Override
+ public String toString() {
+ return "ConfigurationBaseEntity{" +
+ "id=" + id +
+ ", version=" + version +
+ ", versionTag='" + versionTag + '\'' +
+ ", type='" + type + '\'' +
+ ", configurationData='" + configurationData + '\'' +
+ ", configurationAttributes='" + configurationAttributes + '\'' +
+ ", createTimestamp=" + createTimestamp +
+ '}';
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+
+ if (o == null || getClass() != o.getClass()) return false;
+
+ ConfigurationBaseEntity that = (ConfigurationBaseEntity) o;
+
+ return new EqualsBuilder()
+ .append(id, that.id)
+ .append(version, that.version)
+ .append(versionTag, that.versionTag)
+ .append(type, that.type)
+ .append(configurationData, that.configurationData)
+ .append(configurationAttributes, that.configurationAttributes)
+ .append(createTimestamp, that.createTimestamp)
+ .isEquals();
+ }
+
+ @Override
+ public int hashCode() {
+ return new HashCodeBuilder(17, 37)
+ .append(id)
+ .append(version)
+ .append(versionTag)
+ .append(type)
+ .append(configurationData)
+ .append(configurationAttributes)
+ .append(createTimestamp)
+ .toHashCode();
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/47350522/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/RoleAuthorization.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/RoleAuthorization.java b/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/RoleAuthorization.java
index cd35c2c..3c50628 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/RoleAuthorization.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/security/authorization/RoleAuthorization.java
@@ -39,6 +39,7 @@ public enum RoleAuthorization {
AMBARI_MANAGE_VIEWS("AMBARI.MANAGE_VIEWS"),
AMBARI_RENAME_CLUSTER("AMBARI.RENAME_CLUSTER"),
AMBARI_RUN_CUSTOM_COMMAND("AMBARI.RUN_CUSTOM_COMMAND"),
+ AMBARI_MANAGE_CONFIGURATION("AMBARI.MANAGE_CONFIGURATION"),
CLUSTER_MANAGE_CREDENTIALS("CLUSTER.MANAGE_CREDENTIALS"),
CLUSTER_MODIFY_CONFIGS("CLUSTER.MODIFY_CONFIGS"),
CLUSTER_MANAGE_CONFIG_GROUPS("CLUSTER.MANAGE_CONFIG_GROUPS"),
@@ -84,58 +85,58 @@ public enum RoleAuthorization {
VIEW_USE("VIEW.USE");
public static final Set<RoleAuthorization> AUTHORIZATIONS_VIEW_CLUSTER = EnumSet.of(
- CLUSTER_VIEW_STATUS_INFO,
- CLUSTER_VIEW_ALERTS,
- CLUSTER_VIEW_CONFIGS,
- CLUSTER_VIEW_METRICS,
- CLUSTER_VIEW_STACK_DETAILS,
- CLUSTER_MODIFY_CONFIGS,
- CLUSTER_MANAGE_CONFIG_GROUPS,
- CLUSTER_TOGGLE_ALERTS,
- CLUSTER_TOGGLE_KERBEROS,
- CLUSTER_UPGRADE_DOWNGRADE_STACK);
+ CLUSTER_VIEW_STATUS_INFO,
+ CLUSTER_VIEW_ALERTS,
+ CLUSTER_VIEW_CONFIGS,
+ CLUSTER_VIEW_METRICS,
+ CLUSTER_VIEW_STACK_DETAILS,
+ CLUSTER_MODIFY_CONFIGS,
+ CLUSTER_MANAGE_CONFIG_GROUPS,
+ CLUSTER_TOGGLE_ALERTS,
+ CLUSTER_TOGGLE_KERBEROS,
+ CLUSTER_UPGRADE_DOWNGRADE_STACK);
public static final Set<RoleAuthorization> AUTHORIZATIONS_UPDATE_CLUSTER = EnumSet.of(
- CLUSTER_TOGGLE_ALERTS,
- CLUSTER_TOGGLE_KERBEROS,
- CLUSTER_UPGRADE_DOWNGRADE_STACK,
- CLUSTER_MODIFY_CONFIGS,
- CLUSTER_MANAGE_AUTO_START,
- SERVICE_MODIFY_CONFIGS);
+ CLUSTER_TOGGLE_ALERTS,
+ CLUSTER_TOGGLE_KERBEROS,
+ CLUSTER_UPGRADE_DOWNGRADE_STACK,
+ CLUSTER_MODIFY_CONFIGS,
+ CLUSTER_MANAGE_AUTO_START,
+ SERVICE_MODIFY_CONFIGS);
public static final Set<RoleAuthorization> AUTHORIZATIONS_VIEW_SERVICE = EnumSet.of(
- SERVICE_VIEW_ALERTS,
- SERVICE_VIEW_CONFIGS,
- SERVICE_VIEW_METRICS,
- SERVICE_VIEW_STATUS_INFO,
- SERVICE_COMPARE_CONFIGS,
- SERVICE_ADD_DELETE_SERVICES,
- SERVICE_DECOMMISSION_RECOMMISSION,
- SERVICE_ENABLE_HA,
- SERVICE_MANAGE_CONFIG_GROUPS,
- SERVICE_MODIFY_CONFIGS,
- SERVICE_START_STOP,
- SERVICE_TOGGLE_MAINTENANCE,
- SERVICE_TOGGLE_ALERTS,
- SERVICE_MOVE,
- SERVICE_RUN_CUSTOM_COMMAND,
- SERVICE_RUN_SERVICE_CHECK);
+ SERVICE_VIEW_ALERTS,
+ SERVICE_VIEW_CONFIGS,
+ SERVICE_VIEW_METRICS,
+ SERVICE_VIEW_STATUS_INFO,
+ SERVICE_COMPARE_CONFIGS,
+ SERVICE_ADD_DELETE_SERVICES,
+ SERVICE_DECOMMISSION_RECOMMISSION,
+ SERVICE_ENABLE_HA,
+ SERVICE_MANAGE_CONFIG_GROUPS,
+ SERVICE_MODIFY_CONFIGS,
+ SERVICE_START_STOP,
+ SERVICE_TOGGLE_MAINTENANCE,
+ SERVICE_TOGGLE_ALERTS,
+ SERVICE_MOVE,
+ SERVICE_RUN_CUSTOM_COMMAND,
+ SERVICE_RUN_SERVICE_CHECK);
public static final Set<RoleAuthorization> AUTHORIZATIONS_UPDATE_SERVICE = EnumSet.of(
- SERVICE_ADD_DELETE_SERVICES,
- SERVICE_DECOMMISSION_RECOMMISSION,
- SERVICE_ENABLE_HA,
- SERVICE_MANAGE_CONFIG_GROUPS,
- SERVICE_MODIFY_CONFIGS,
- SERVICE_START_STOP,
- SERVICE_TOGGLE_MAINTENANCE,
- SERVICE_TOGGLE_ALERTS,
- SERVICE_MOVE,
- SERVICE_RUN_CUSTOM_COMMAND,
- SERVICE_RUN_SERVICE_CHECK,
- SERVICE_MANAGE_ALERTS,
- SERVICE_MANAGE_AUTO_START,
- SERVICE_SET_SERVICE_USERS_GROUPS);
+ SERVICE_ADD_DELETE_SERVICES,
+ SERVICE_DECOMMISSION_RECOMMISSION,
+ SERVICE_ENABLE_HA,
+ SERVICE_MANAGE_CONFIG_GROUPS,
+ SERVICE_MODIFY_CONFIGS,
+ SERVICE_START_STOP,
+ SERVICE_TOGGLE_MAINTENANCE,
+ SERVICE_TOGGLE_ALERTS,
+ SERVICE_MOVE,
+ SERVICE_RUN_CUSTOM_COMMAND,
+ SERVICE_RUN_SERVICE_CHECK,
+ SERVICE_MANAGE_ALERTS,
+ SERVICE_MANAGE_AUTO_START,
+ SERVICE_SET_SERVICE_USERS_GROUPS);
private final String id;
@@ -162,7 +163,7 @@ public enum RoleAuthorization {
/**
* Safely translates a role authorization Id to a RoleAuthorization
*
- * @param authenticationId an authentication id
+ * @param authenticationId an authentication id
* @return a RoleAuthorization or null if no translation can be made
*/
public static RoleAuthorization translate(String authenticationId) {
http://git-wip-us.apache.org/repos/asf/ambari/blob/47350522/ambari-server/src/main/resources/Ambari-DDL-Postgres-CREATE.sql
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/resources/Ambari-DDL-Postgres-CREATE.sql b/ambari-server/src/main/resources/Ambari-DDL-Postgres-CREATE.sql
index 634db95..01b3324 100644
--- a/ambari-server/src/main/resources/Ambari-DDL-Postgres-CREATE.sql
+++ b/ambari-server/src/main/resources/Ambari-DDL-Postgres-CREATE.sql
@@ -62,8 +62,26 @@ CREATE TABLE clusters (
desired_cluster_state VARCHAR(255) NOT NULL,
desired_stack_id BIGINT NOT NULL,
CONSTRAINT PK_clusters PRIMARY KEY (cluster_id),
- CONSTRAINT FK_clusters_desired_stack_id FOREIGN KEY (desired_stack_id) REFERENCES stack(stack_id),
- CONSTRAINT FK_clusters_resource_id FOREIGN KEY (resource_id) REFERENCES adminresource(resource_id));
+ CONSTRAINT FK_clusters_desired_stack_id FOREIGN KEY (desired_stack_id) REFERENCES stack (stack_id),
+ CONSTRAINT FK_clusters_resource_id FOREIGN KEY (resource_id) REFERENCES adminresource (resource_id)
+);
+
+CREATE TABLE configuration_base (
+ id BIGINT NOT NULL,
+ version_tag VARCHAR(255) NOT NULL,
+ version BIGINT NOT NULL,
+ type VARCHAR(255) NOT NULL,
+ data TEXT NOT NULL,
+ attributes TEXT,
+ create_timestamp BIGINT NOT NULL,
+ CONSTRAINT PK_configuration_base PRIMARY KEY (id)
+);
+
+CREATE TABLE ambari_configuration (
+ id BIGINT NOT NULL,
+ CONSTRAINT PK_ambari_configuration PRIMARY KEY (id),
+ CONSTRAINT FK_ambari_configuration_configuration_base FOREIGN KEY (id) REFERENCES configuration_base (id)
+);
CREATE TABLE clusterconfig (
config_id BIGINT NOT NULL,
@@ -1090,6 +1108,7 @@ INSERT INTO ambari_sequences (sequence_name, sequence_value) VALUES
('remote_cluster_id_seq', 0),
('remote_cluster_service_id_seq', 0),
('servicecomponent_version_id_seq', 0),
+ ('configuration_id_seq', 0),
('hostcomponentdesiredstate_id_seq', 0);
INSERT INTO adminresourcetype (resource_type_id, resource_type_name) VALUES
@@ -1174,6 +1193,7 @@ INSERT INTO roleauthorization(authorization_id, authorization_name)
SELECT 'AMBARI.ADD_DELETE_CLUSTERS', 'Create new clusters' UNION ALL
SELECT 'AMBARI.RENAME_CLUSTER', 'Rename clusters' UNION ALL
SELECT 'AMBARI.MANAGE_SETTINGS', 'Manage administrative settings' UNION ALL
+ SELECT 'AMBARI.MANAGE_CONFIGURATION', 'Manage ambari configuration' UNION ALL
SELECT 'AMBARI.MANAGE_USERS', 'Manage users' UNION ALL
SELECT 'AMBARI.MANAGE_GROUPS', 'Manage groups' UNION ALL
SELECT 'AMBARI.MANAGE_VIEWS', 'Manage Ambari Views' UNION ALL
@@ -1379,6 +1399,7 @@ INSERT INTO permission_roleauthorization(permission_id, authorization_id)
SELECT permission_id, 'AMBARI.ADD_DELETE_CLUSTERS' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
SELECT permission_id, 'AMBARI.RENAME_CLUSTER' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
SELECT permission_id, 'AMBARI.MANAGE_SETTINGS' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
+ SELECT permission_id, 'AMBARI.MANAGE_CONFIGURATION' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
SELECT permission_id, 'AMBARI.MANAGE_USERS' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
SELECT permission_id, 'AMBARI.MANAGE_GROUPS' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
SELECT permission_id, 'AMBARI.MANAGE_VIEWS' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
http://git-wip-us.apache.org/repos/asf/ambari/blob/47350522/ambari-server/src/main/resources/META-INF/persistence.xml
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/resources/META-INF/persistence.xml b/ambari-server/src/main/resources/META-INF/persistence.xml
index e4045ef..0f8e964 100644
--- a/ambari-server/src/main/resources/META-INF/persistence.xml
+++ b/ambari-server/src/main/resources/META-INF/persistence.xml
@@ -96,6 +96,8 @@
<class>org.apache.ambari.server.orm.entities.KerberosDescriptorEntity</class>
<class>org.apache.ambari.server.orm.entities.RemoteAmbariClusterEntity</class>
<class>org.apache.ambari.server.orm.entities.RemoteAmbariClusterServiceEntity</class>
+ <class>org.apache.ambari.server.orm.entities.ConfigurationBaseEntity</class>
+ <class>org.apache.ambari.server.orm.entities.AmbariConfigurationEntity</class>
<properties>
<property name="eclipselink.cache.size.default" value="10000" />
[11/33] ambari git commit: AMBARI-21307 Draft implementation of the
group related attributes
Posted by lp...@apache.org.
AMBARI-21307 Draft implementation of the group related attributes
Project: http://git-wip-us.apache.org/repos/asf/ambari/repo
Commit: http://git-wip-us.apache.org/repos/asf/ambari/commit/86e105f8
Tree: http://git-wip-us.apache.org/repos/asf/ambari/tree/86e105f8
Diff: http://git-wip-us.apache.org/repos/asf/ambari/diff/86e105f8
Branch: refs/heads/feature-branch-AMBARI-21307
Commit: 86e105f8d7ae76318132f2e3ff8f3833c0af14b2
Parents: 8d2e134
Author: lpuskas <lp...@apache.org>
Authored: Tue Aug 8 13:54:29 2017 +0200
Committer: lpuskas <lp...@apache.org>
Committed: Fri Oct 13 17:20:49 2017 +0200
----------------------------------------------------------------------
.../server/ldap/AmbariLdapConfiguration.java | 22 +-
.../ldap/LdapConfigurationValidatorService.java | 34 +--
.../apache/ambari/server/ldap/LdapModule.java | 4 +-
.../server/ldap/service/AmbariLdapFacade.java | 25 +-
.../ldap/service/LdapConnectionService.java | 35 +++
.../ambari/server/ldap/service/LdapFacade.java | 9 +-
.../ad/AdLdapConfigurationValidatorService.java | 177 --------------
...efaultLdapConfigurationValidatorService.java | 232 +++++++++++++++++++
.../ad/DefaultLdapConnectionService.java | 63 +++++
.../service/ad/LdapConfigurationConverter.java | 50 ----
...AdLdapConfigurationValidatorServiceTest.java | 129 -----------
...ltLdapConfigurationValidatorServiceTest.java | 156 +++++++++++++
12 files changed, 552 insertions(+), 384 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/ambari/blob/86e105f8/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
index 519f400..a6ff80b 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/AmbariLdapConfiguration.java
@@ -53,7 +53,7 @@ public class AmbariLdapConfiguration {
GROUP_OBJECT_CLASS("ambari.ldap.group.object.class"),
GROUP_NAME_ATTRIBUTE("ambari.ldap.group.name.attribute"),
GROUP_MEMBER_ATTRIBUTE("ambari.ldap.group.member.attribute"),
- GROUP_SEARCH_BASE("ambari.ldap.group.member.attribute"),
+ GROUP_SEARCH_BASE("ambari.ldap.group.search.base"),
DN_ATTRIBUTE("authentication.ldap.dnAttribute");
private String propertyName;
@@ -126,4 +126,24 @@ public class AmbariLdapConfiguration {
return (String) configurationValue(LdapConfigProperty.USER_NAME_ATTRIBUTE);
}
+ public String userSearchBase() {
+ return (String) configurationValue(LdapConfigProperty.USER_SEARCH_BASE);
+ }
+
+ public String groupObjectClass() {
+ return (String) configurationValue(LdapConfigProperty.GROUP_OBJECT_CLASS);
+ }
+
+ public String groupNameAttribute() {
+ return (String) configurationValue(LdapConfigProperty.GROUP_NAME_ATTRIBUTE);
+ }
+
+ public String groupMemberAttribute() {
+ return (String) configurationValue(LdapConfigProperty.GROUP_MEMBER_ATTRIBUTE);
+ }
+
+ public String groupSearchBase() {
+ return (String) configurationValue(LdapConfigProperty.GROUP_SEARCH_BASE);
+ }
+
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/86e105f8/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationValidatorService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationValidatorService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationValidatorService.java
index 4667721..7efa3b7 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationValidatorService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapConfigurationValidatorService.java
@@ -14,8 +14,11 @@
package org.apache.ambari.server.ldap;
+import java.util.Set;
+
import org.apache.ambari.server.AmbariException;
import org.apache.ambari.server.ldap.service.AmbariLdapException;
+import org.apache.directory.ldap.client.api.LdapConnection;
/**
* Collection of operations for validating ldap configuration.
@@ -26,27 +29,32 @@ public interface LdapConfigurationValidatorService {
/**
* Tests the connection based on the provided configuration.
*
- * @param configuration the ambari ldap configuration instance
+ * @param ldapConnection connection instance
+ * @param configuration the ambari ldap configuration instance
* @throws AmbariLdapException if the connection is not possible
*/
- void checkConnection(AmbariLdapConfiguration configuration) throws AmbariLdapException;
+ void checkConnection(LdapConnection ldapConnection, AmbariLdapConfiguration configuration) throws AmbariLdapException;
+
/**
- * Checks whether the group related LDAP attributes in the configuration are correct.
+ * Implements LDAP user related configuration settings validation logic.
+ * Implementers communicate with the LDAP server (search, bind) to validate attributes in the provided configuration
+ * instance
*
- * @param configuration the configuration instance holding the available properties
- * @throws AmbariException if the attributes are not valid
+ * @param ldapConnection connection instance used to connect to the LDAP server
+ * @param testUserName the test username
+ * @param testPassword the test password
+ * @param configuration the available ldap configuration
+ * @return The DN of the found user entry
+ * @throws AmbariException if the connection couldn't be estabilisheds
*/
- void checkGroupAttributes(AmbariLdapConfiguration configuration) throws AmbariException;
+ String checkUserAttributes(LdapConnection ldapConnection, String testUserName, String testPassword, AmbariLdapConfiguration configuration) throws AmbariLdapException;
/**
- * Tries to connect to the LDAP server with the given credentials.
- * Primarily used for testing the user before performing other operations (eg. attribute detection)s
+ * Checks whether the group related LDAP attributes in the configuration are correct.
*
- * @param username the username
- * @param password the password
- * @param configuration the available ldap configuration
- * @throws AmbariException if the connection couldn't be estabilished
+ * @throws AmbariException if the attributes are not valid
*/
- void checkUserAttributes(String username, String password, AmbariLdapConfiguration configuration) throws AmbariException;
+ Set<String> checkGroupAttributes(LdapConnection ldapConnection, String userDn, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException;
+
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/86e105f8/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
index 625ce8b..545f220 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/LdapModule.java
@@ -17,7 +17,7 @@ package org.apache.ambari.server.ldap;
import org.apache.ambari.server.ldap.service.AmbariLdapFacade;
import org.apache.ambari.server.ldap.service.LdapFacade;
-import org.apache.ambari.server.ldap.service.ad.AdLdapConfigurationValidatorService;
+import org.apache.ambari.server.ldap.service.ad.DefaultLdapConfigurationValidatorService;
import com.google.inject.AbstractModule;
import com.google.inject.assistedinject.FactoryModuleBuilder;
@@ -30,7 +30,7 @@ public class LdapModule extends AbstractModule {
@Override
protected void configure() {
bind(LdapFacade.class).to(AmbariLdapFacade.class);
- bind(LdapConfigurationValidatorService.class).to(AdLdapConfigurationValidatorService.class);
+ bind(LdapConfigurationValidatorService.class).to(DefaultLdapConfigurationValidatorService.class);
install(new FactoryModuleBuilder().build(LdapConfigurationFactory.class));
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/86e105f8/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
index abd028a..abb464b 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapFacade.java
@@ -16,13 +16,14 @@
package org.apache.ambari.server.ldap.service;
import java.util.Map;
+import java.util.Set;
import javax.inject.Inject;
import javax.inject.Singleton;
-import org.apache.ambari.server.AmbariException;
import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
import org.apache.ambari.server.ldap.LdapConfigurationValidatorService;
+import org.apache.directory.ldap.client.api.LdapConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -51,17 +52,21 @@ public class AmbariLdapFacade implements LdapFacade {
private LdapConfigurationValidatorService ldapConfigurationValidatorService;
@Inject
+ private LdapConnectionService ldapConnectionService;
+
+ @Inject
public AmbariLdapFacade() {
}
@Override
- public void checkConnection(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariException {
+ public void checkConnection(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
try {
LOGGER.info("Validating LDAP connection related configuration based on: {}", ambariLdapConfiguration);
- ldapConfigurationValidatorService.checkConnection(ambariLdapConfiguration);
+ LdapConnection connection = ldapConnectionService.createLdapConnection(ambariLdapConfiguration);
+ ldapConfigurationValidatorService.checkConnection(connection, ambariLdapConfiguration);
} catch (AmbariLdapException e) {
LOGGER.error("Validating LDAP connection configuration failed", e);
- throw new AmbariException("Validating LDAP connection configuration failed", e);
+ throw e;
}
LOGGER.info("Validating LDAP connection related configuration: SUCCESS");
}
@@ -74,7 +79,7 @@ public class AmbariLdapFacade implements LdapFacade {
}
@Override
- public void checkLdapAttibutes(Map<String, Object> parameters, AmbariLdapConfiguration ldapConfiguration) throws AmbariException {
+ public void checkLdapAttibutes(Map<String, Object> parameters, AmbariLdapConfiguration ldapConfiguration) throws AmbariLdapException {
String userName = getTestUserNameFromParameters(parameters);
String testUserPass = getTestUserPasswordFromParameters(parameters);
@@ -82,8 +87,14 @@ public class AmbariLdapFacade implements LdapFacade {
throw new IllegalArgumentException("No test user available for testing LDAP attributes");
}
- LOGGER.info("Testing LDAP attributes with test user: {}", userName);
- ldapConfigurationValidatorService.checkUserAttributes(userName, testUserPass, ldapConfiguration);
+ LdapConnection ldapConnection = ldapConnectionService.createLdapConnection(ldapConfiguration);
+
+ LOGGER.info("Testing LDAP user attributes with test user: {}", userName);
+ String userDn = ldapConfigurationValidatorService.checkUserAttributes(ldapConnection, userName, testUserPass, ldapConfiguration);
+
+ LOGGER.info("Testing LDAP group attributes with test user dn: {}", userDn);
+ Set<String> groups = ldapConfigurationValidatorService.checkGroupAttributes(ldapConnection, userDn, ldapConfiguration);
+
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/86e105f8/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConnectionService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConnectionService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConnectionService.java
new file mode 100644
index 0000000..50ee8ed
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapConnectionService.java
@@ -0,0 +1,35 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service;
+
+import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
+import org.apache.directory.ldap.client.api.LdapNetworkConnection;
+
+/**
+ * Contract defining factory methods for creating LDAP connection instances.
+ * Implementers contain the logic of creating different connection instances and the afferent boilerplate code.
+ */
+public interface LdapConnectionService {
+
+ /**
+ * Creates an LdapConnection instance based on the provided configuration
+ *
+ * @param ambariLdapConfiguration configuration instance with information for creating the connection instance
+ * @return a set up LdapConnection instance
+ */
+ LdapNetworkConnection createLdapConnection(AmbariLdapConfiguration ambariLdapConfiguration);
+
+
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/86e105f8/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java
index 38553f0..7bb1198 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/LdapFacade.java
@@ -16,7 +16,6 @@ package org.apache.ambari.server.ldap.service;
import java.util.Map;
-import org.apache.ambari.server.AmbariException;
import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
/**
@@ -29,9 +28,9 @@ public interface LdapFacade {
* Tests the connection to the LDAP server based on the provided configuration.
*
* @param ambariLdapConfiguration the available ldap related configuration
- * @throws AmbariException if the connection fails or other problems occur during the operation
+ * @throws AmbariLdapException if the connection fails or other problems occur during the operation
*/
- void checkConnection(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariException;
+ void checkConnection(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException;
/**
@@ -46,7 +45,7 @@ public interface LdapFacade {
*
* @param parameters a map of property name and value pairs holding information to facilitate checking the attributes
* @param ambariLdapConfiguration configutration instance with available attributes
- * @throws AmbariException if the attribute checking fails
+ * @throws AmbariLdapException if the attribute checking fails
*/
- void checkLdapAttibutes(Map<String, Object> parameters, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariException;
+ void checkLdapAttibutes(Map<String, Object> parameters, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException;
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/86e105f8/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/AdLdapConfigurationValidatorService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/AdLdapConfigurationValidatorService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/AdLdapConfigurationValidatorService.java
deleted file mode 100644
index 11e8655..0000000
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/AdLdapConfigurationValidatorService.java
+++ /dev/null
@@ -1,177 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.ambari.server.ldap.service.ad;
-
-import java.io.IOException;
-import java.util.List;
-
-import javax.inject.Inject;
-import javax.inject.Singleton;
-
-import org.apache.ambari.server.AmbariException;
-import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
-import org.apache.ambari.server.ldap.LdapConfigurationValidatorService;
-import org.apache.ambari.server.ldap.service.AmbariLdapException;
-import org.apache.directory.api.ldap.model.cursor.EntryCursor;
-import org.apache.directory.api.ldap.model.cursor.SearchCursor;
-import org.apache.directory.api.ldap.model.entry.Entry;
-import org.apache.directory.api.ldap.model.message.SearchScope;
-import org.apache.directory.api.ldap.model.name.Dn;
-import org.apache.directory.ldap.client.api.LdapConnectionConfig;
-import org.apache.directory.ldap.client.api.LdapNetworkConnection;
-import org.apache.directory.ldap.client.api.search.FilterBuilder;
-import org.apache.directory.shared.ldap.constants.SchemaConstants;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.Lists;
-
-/**
- * Implementation of the validation logic using the Apache Directory API.
- */
-@Singleton
-public class AdLdapConfigurationValidatorService implements LdapConfigurationValidatorService {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(AdLdapConfigurationValidatorService.class);
-
- @Inject
- private LdapConfigurationConverter ldapConfigurationConverter;
-
- /**
- * Facilitating the instantiation
- */
- @Inject
- public AdLdapConfigurationValidatorService() {
- }
-
- @Override
- public void checkConnection(AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
- try {
- LOGGER.info("Testing the connection based on the configuration: {}", ambariLdapConfiguration);
-
- LdapConnectionConfig connectionConfig = ldapConfigurationConverter.getLdapConnectionConfig(ambariLdapConfiguration);
- LdapNetworkConnection connection = new LdapNetworkConnection(connectionConfig);
-
- if (ambariLdapConfiguration.bindAnonimously()) {
- LOGGER.debug("Binding anonimously ...");
- connection.bind();
- } else {
- LOGGER.debug("Binding with manager DN and manager password ...");
- connection.bind(ambariLdapConfiguration.managerDn(), ambariLdapConfiguration.managerPassword());
- }
-
- if (connection.isConnected()) {
- LOGGER.info("Successfully connected to the LDAP server.");
- }
-
- connection.close();
-
- } catch (Exception e) {
- LOGGER.warn("Could not bind to the LDAP server base don the provided configuration ...");
- throw new AmbariLdapException(e);
- }
- }
-
-
- /**
- * Checks the user attributes provided in the configuration instance by issuing a search for a (known) test user in the LDAP.
- * Attributes are considered correct if there is at least one entry found.
- *
- * Invalid attributes are signaled by throwing an exception.
- *
- * @param username the username
- * @param password the password
- * @param ambariLdapConfiguration configuration instance holding ldap configuration details
- * @throws AmbariException if the attributes are not valid or any errors occurs
- */
- @Override
- public void checkUserAttributes(String username, String password, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariException {
- LdapNetworkConnection connection = null;
- SearchCursor searchCursor = null;
- try {
- LOGGER.info("Checking user attributes for user {} r ...", username);
-
- LdapConnectionConfig connectionConfig = ldapConfigurationConverter.getLdapConnectionConfig(ambariLdapConfiguration);
- connection = new LdapNetworkConnection(connectionConfig);
-
-
- if (!ambariLdapConfiguration.bindAnonimously()) {
- LOGGER.debug("Anonimous binding not supported, binding with the manager detailas...");
- connection.bind(ambariLdapConfiguration.managerDn(), ambariLdapConfiguration.managerPassword());
- } else {
- LOGGER.debug("Binding anonimously ...");
- connection.bind();
- }
-
- if (!connection.isConnected()) {
- LOGGER.error("Not connected to the LDAP server. Connection instance: {}", connection);
- throw new IllegalStateException("The connection to the LDAP server is not alive");
- }
-
- // set up a filter based on the provided attributes
- String filter = FilterBuilder.and(
- FilterBuilder.equal(SchemaConstants.OBJECT_CLASS_AT, ambariLdapConfiguration.userObjectClass()),
- FilterBuilder.equal(ambariLdapConfiguration.userNameAttribute(), username))
- .toString();
-
- LOGGER.info("Searching for the user: {} using the search filter: {}", username, filter);
- EntryCursor entryCursor = connection.search(new Dn(ambariLdapConfiguration.baseDn()), filter, SearchScope.SUBTREE);
-
- // collecting search result entries
- List<Entry> users = Lists.newArrayList();
- for (Entry entry : entryCursor) {
- users.add(entry);
- }
-
- // there should be at least one user found
- if (users.isEmpty()) {
- String msg = String.format("There are no users found using the filter: [ %s ]. Try changing the attribute values", filter);
- LOGGER.error(msg);
- throw new Exception(msg);
- }
-
- LOGGER.info("Attibute validation succeeded. Filter: {}", filter);
-
- } catch (Exception e) {
-
- LOGGER.error("Error while checking user attributes.");
- throw new AmbariException("Error while checking user attributes", e);
-
- } finally {
-
- LOGGER.debug("Closing the connection and searchresult ...");
-
- if (null != searchCursor) {
- searchCursor.close();
- }
-
- if (null != connection) {
- try {
- connection.close();
- } catch (IOException e) {
- LOGGER.error("Exception occurred while closing the connection", e);
- }
- }
-
- }
- }
-
- @Override
- public void checkGroupAttributes(AmbariLdapConfiguration configuration) throws AmbariException {
-
- }
-
-
-}
http://git-wip-us.apache.org/repos/asf/ambari/blob/86e105f8/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConfigurationValidatorService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConfigurationValidatorService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConfigurationValidatorService.java
new file mode 100644
index 0000000..838ef4c
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConfigurationValidatorService.java
@@ -0,0 +1,232 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service.ad;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Set;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+import org.apache.ambari.server.AmbariException;
+import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.LdapConfigurationValidatorService;
+import org.apache.ambari.server.ldap.service.AmbariLdapException;
+import org.apache.ambari.server.ldap.service.LdapConnectionService;
+import org.apache.directory.api.ldap.codec.decorators.SearchResultEntryDecorator;
+import org.apache.directory.api.ldap.model.cursor.EntryCursor;
+import org.apache.directory.api.ldap.model.cursor.SearchCursor;
+import org.apache.directory.api.ldap.model.entry.Entry;
+import org.apache.directory.api.ldap.model.exception.LdapException;
+import org.apache.directory.api.ldap.model.message.Response;
+import org.apache.directory.api.ldap.model.message.SearchRequest;
+import org.apache.directory.api.ldap.model.message.SearchRequestImpl;
+import org.apache.directory.api.ldap.model.message.SearchScope;
+import org.apache.directory.api.ldap.model.name.Dn;
+import org.apache.directory.ldap.client.api.LdapConnection;
+import org.apache.directory.ldap.client.api.LdapNetworkConnection;
+import org.apache.directory.ldap.client.api.search.FilterBuilder;
+import org.apache.directory.shared.ldap.constants.SchemaConstants;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+
+/**
+ * Implementation of the validation logic using the Apache Directory API.
+ */
+@Singleton
+public class DefaultLdapConfigurationValidatorService implements LdapConfigurationValidatorService {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(DefaultLdapConfigurationValidatorService.class);
+
+ @Inject
+ private LdapConnectionService ldapConnectionService;
+
+ /**
+ * Facilitating the instantiation
+ */
+ @Inject
+ public DefaultLdapConfigurationValidatorService() {
+ }
+
+ @Override
+ public void checkConnection(LdapConnection ldapConnection, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
+ try {
+ bind(ambariLdapConfiguration, ldapConnection);
+ } catch (LdapException e) {
+ LOGGER.error("Could not connect to the LDAP server", e);
+ throw new AmbariLdapException(e);
+ }
+ }
+
+
+ /**
+ * Checks the user attributes provided in the configuration instance by issuing a search for a (known) test user in the LDAP.
+ * Attributes are considered correct if there is at least one entry found.
+ *
+ * Invalid attributes are signaled by throwing an exception.
+ *
+ * @param testUserName the test username
+ * @param testPassword the test password
+ * @param ambariLdapConfiguration configuration instance holding ldap configuration details
+ * @throws AmbariException if the attributes are not valid or any errors occurs
+ */
+ @Override
+ public String checkUserAttributes(LdapConnection ldapConnection, String testUserName, String testPassword, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
+ LdapNetworkConnection connection = null;
+ SearchCursor searchCursor = null;
+ String userDn = null;
+ try {
+ LOGGER.info("Checking user attributes for user {} r ...", testUserName);
+
+ // bind anonimously or with manager data
+ bind(ambariLdapConfiguration, connection);
+
+ // set up a filter based on the provided attributes
+ String filter = FilterBuilder.and(
+ FilterBuilder.equal(SchemaConstants.OBJECT_CLASS_AT, ambariLdapConfiguration.userObjectClass()),
+ FilterBuilder.equal(ambariLdapConfiguration.userNameAttribute(), testUserName))
+ .toString();
+
+ LOGGER.info("Searching for the user: {} using the search filter: {}", testUserName, filter);
+ EntryCursor entryCursor = connection.search(new Dn(ambariLdapConfiguration.userSearchBase()), filter, SearchScope.SUBTREE);
+
+ // collecting search result entries
+ List<Entry> users = Lists.newArrayList();
+ for (Entry entry : entryCursor) {
+ users.add(entry);
+ userDn = entry.getDn().getNormName();
+ }
+
+ // there should be at least one user found
+ if (users.isEmpty()) {
+ String msg = String.format("There are no users found using the filter: [ %s ]. Try changing the attribute values", filter);
+ LOGGER.error(msg);
+ throw new Exception(msg);
+ }
+
+ LOGGER.info("Attibute validation succeeded. Filter: {}", filter);
+
+ } catch (Exception e) {
+
+ LOGGER.error("User attributes validation failed.", e);
+ throw new AmbariLdapException(e.getMessage(), e);
+
+ } finally {
+ closeResources(connection, searchCursor);
+ }
+ return userDn;
+ }
+
+
+ @Override
+ public Set<String> checkGroupAttributes(LdapConnection ldapConnection, String userDn, AmbariLdapConfiguration ambariLdapConfiguration) throws AmbariLdapException {
+ SearchCursor searchCursor = null;
+ Set<Response> groupResponses = Sets.newHashSet();
+
+ try {
+ LOGGER.info("Checking group attributes for user dn {} ...", userDn);
+
+ bind(ambariLdapConfiguration, ldapConnection);
+
+ // set up a filter based on the provided attributes
+ String filter = FilterBuilder.and(
+ FilterBuilder.equal(SchemaConstants.OBJECT_CLASS_AT, ambariLdapConfiguration.groupObjectClass()),
+ FilterBuilder.equal(ambariLdapConfiguration.groupMemberAttribute(), userDn)
+ ).toString();
+
+ LOGGER.info("Searching for the groups the user dn: {} is member of using the search filter: {}", userDn, filter);
+
+ // assemble a search request
+ SearchRequest searchRequest = new SearchRequestImpl();
+ searchRequest.setFilter(filter);
+ searchRequest.setBase(new Dn(ambariLdapConfiguration.groupSearchBase()));
+ searchRequest.setScope(SearchScope.SUBTREE);
+ searchRequest.addAttributes(ambariLdapConfiguration.groupMemberAttribute(), ambariLdapConfiguration.groupNameAttribute());
+
+ // perform the search
+ searchCursor = ldapConnection.search(searchRequest);
+
+ for (Response response : searchCursor) {
+ groupResponses.add(response);
+ }
+
+ } catch (Exception e) {
+
+ LOGGER.error("User attributes validation failed.", e);
+ throw new AmbariLdapException(e.getMessage(), e);
+
+ } finally {
+
+ closeResources(ldapConnection, searchCursor);
+
+ }
+
+ return processGroupResults(groupResponses, ambariLdapConfiguration);
+ }
+
+ private void bind(AmbariLdapConfiguration ambariLdapConfiguration, LdapConnection connection) throws LdapException {
+ LOGGER.info("Connecting to LDAP ....");
+ if (!ambariLdapConfiguration.bindAnonimously()) {
+ LOGGER.debug("Anonimous binding not supported, binding with the manager detailas...");
+ connection.bind(ambariLdapConfiguration.managerDn(), ambariLdapConfiguration.managerPassword());
+ } else {
+ LOGGER.debug("Binding anonimously ...");
+ connection.bind();
+ }
+
+ if (!connection.isConnected()) {
+ LOGGER.error("Not connected to the LDAP server. Connection instance: {}", connection);
+ throw new IllegalStateException("The connection to the LDAP server is not alive");
+ }
+ LOGGER.info("Connected to LDAP.");
+ }
+
+
+ private Set<String> processGroupResults(Set<Response> groupResponses, AmbariLdapConfiguration ambariLdapConfiguration) {
+ Set<String> groupStrSet = Sets.newHashSet();
+ for (Response response : groupResponses) {
+ Entry entry = ((SearchResultEntryDecorator) response).getEntry();
+ groupStrSet.add(entry.get(ambariLdapConfiguration.groupNameAttribute()).get().getString());
+ }
+
+ LOGGER.debug("Extracted group names from group search responses: {}", groupStrSet);
+ return groupStrSet;
+ }
+
+ private void closeResources(LdapConnection connection, SearchCursor searchCursor) {
+ LOGGER.debug("Housekeeping: closing the connection and the search cursor ...");
+
+ if (null != searchCursor) {
+ // this method is idempotent
+ searchCursor.close();
+ }
+
+ if (null != connection) {
+ try {
+ connection.close();
+ } catch (IOException e) {
+ LOGGER.error("Exception occurred while closing the connection", e);
+ }
+ }
+ }
+
+}
+
+
+
http://git-wip-us.apache.org/repos/asf/ambari/blob/86e105f8/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConnectionService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConnectionService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConnectionService.java
new file mode 100644
index 0000000..b5559d9
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConnectionService.java
@@ -0,0 +1,63 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service.ad;
+
+import javax.inject.Singleton;
+
+import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.service.LdapConnectionService;
+import org.apache.directory.ldap.client.api.LdapConnectionConfig;
+import org.apache.directory.ldap.client.api.LdapNetworkConnection;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Singleton
+public class DefaultLdapConnectionService implements LdapConnectionService {
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(DefaultLdapConnectionService.class);
+
+ @Override
+ public LdapNetworkConnection createLdapConnection(AmbariLdapConfiguration ambariLdapConfiguration) {
+ LOGGER.debug("Creating ldap connection instance from: {}", ambariLdapConfiguration);
+ return new LdapNetworkConnection(getLdapConnectionConfig(ambariLdapConfiguration));
+ }
+
+ private LdapConnectionConfig getLdapConnectionConfig(AmbariLdapConfiguration ambariAmbariLdapConfiguration) {
+ LOGGER.debug("Creating a configuration instance based on the ambari configuration: {}", ambariAmbariLdapConfiguration);
+
+ LdapConnectionConfig ldapConnectionConfig = new LdapConnectionConfig();
+ ldapConnectionConfig.setLdapHost(ambariAmbariLdapConfiguration.ldapServerHost());
+ ldapConnectionConfig.setLdapPort(ambariAmbariLdapConfiguration.ldapServerPort());
+ ldapConnectionConfig.setUseSsl(ambariAmbariLdapConfiguration.useSSL());
+
+ //todo set the other values as required
+ return ldapConnectionConfig;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/86e105f8/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/LdapConfigurationConverter.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/LdapConfigurationConverter.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/LdapConfigurationConverter.java
deleted file mode 100644
index a8839f1..0000000
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ad/LdapConfigurationConverter.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.ambari.server.ldap.service.ad;
-
-import javax.inject.Singleton;
-
-import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
-import org.apache.directory.ldap.client.api.LdapConnectionConfig;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Converts between ambari specific ldap types and the 3rd party ldap library
- */
-@Singleton
-public class LdapConfigurationConverter {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(LdapConfigurationConverter.class);
-
- /**
- * Creates a {@link LdapConnectionConfig} instance based on the provided ambari specific configurations
- *
- * @param ambariAmbariLdapConfiguration
- * @return
- */
- public LdapConnectionConfig getLdapConnectionConfig(AmbariLdapConfiguration ambariAmbariLdapConfiguration) {
- LOGGER.debug("Creating a configuration instance based on the ambari configuration: {}", ambariAmbariLdapConfiguration);
-
- LdapConnectionConfig ldapConnectionConfig = new LdapConnectionConfig();
- ldapConnectionConfig.setLdapHost(ambariAmbariLdapConfiguration.ldapServerHost());
- ldapConnectionConfig.setLdapPort(ambariAmbariLdapConfiguration.ldapServerPort());
- ldapConnectionConfig.setUseSsl(ambariAmbariLdapConfiguration.useSSL());
-
- //todo set the other values as required
- return ldapConnectionConfig;
- }
-
-}
http://git-wip-us.apache.org/repos/asf/ambari/blob/86e105f8/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ad/AdLdapConfigurationValidatorServiceTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ad/AdLdapConfigurationValidatorServiceTest.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ad/AdLdapConfigurationValidatorServiceTest.java
deleted file mode 100644
index 0f57099..0000000
--- a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ad/AdLdapConfigurationValidatorServiceTest.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.ambari.server.ldap.service.ad;
-
-import static org.junit.Assert.assertNotNull;
-
-import java.util.Map;
-
-import org.apache.ambari.server.AmbariException;
-import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
-import org.apache.ambari.server.ldap.LdapConfigurationValidatorService;
-import org.apache.directory.api.ldap.model.cursor.EntryCursor;
-import org.apache.directory.api.ldap.model.cursor.SearchCursor;
-import org.apache.directory.api.ldap.model.entry.Entry;
-import org.apache.directory.api.ldap.model.message.Response;
-import org.apache.directory.api.ldap.model.message.SearchRequest;
-import org.apache.directory.api.ldap.model.message.SearchRequestImpl;
-import org.apache.directory.api.ldap.model.message.SearchResultEntry;
-import org.apache.directory.api.ldap.model.message.SearchScope;
-import org.apache.directory.api.ldap.model.name.Dn;
-import org.apache.directory.ldap.client.api.LdapConnection;
-import org.apache.directory.ldap.client.api.LdapConnectionConfig;
-import org.apache.directory.ldap.client.api.LdapNetworkConnection;
-import org.apache.directory.ldap.client.api.search.FilterBuilder;
-import org.apache.directory.shared.ldap.constants.SchemaConstants;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.Maps;
-
-public class AdLdapConfigurationValidatorServiceTest {
- private static final Logger LOGGER = LoggerFactory.getLogger(AdLdapConfigurationValidatorService.class);
- private static final String TEST_USER = "Jocika10";
-
- LdapConfigurationValidatorService ldapConfigurationValidatorService = new AdLdapConfigurationValidatorService();
-
-
- @Test
- public void testCheckAttributes() throws Exception {
-
- // WHEN
- LdapConnectionConfig config = new LdapConnectionConfig();
- config.setLdapHost("localhost");
- config.setLdapPort(389);
- LdapConnection connection = new LdapNetworkConnection(config);
-
- // THEN
- connection.anonymousBind();
-
-
- EntryCursor cursor = connection.search("dc=dev,dc=local", "(objectclass=*)", SearchScope.ONELEVEL);
-
- for (Entry entry : cursor) {
- assertNotNull(entry);
- System.out.println(entry);
- }
-
- cursor.close();
-
- }
-
- @Test
- public void testCheckUserAttributes() throws Exception {
- Map<String, Object> ldapPropsMap = Maps.newHashMap();
-
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.BIND_ANONIMOUSLY.propertyName(), true);
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.LDAP_SERVER_HOST.propertyName(), "localhost");
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.LDAP_SERVER_PORT.propertyName(), "389");
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.BASE_DN.propertyName(), "dc=dev,dc=local");
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.USER_OBJECT_CLASS.propertyName(), SchemaConstants.PERSON_OC);
- ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.USER_NAME_ATTRIBUTE.propertyName(), SchemaConstants.UID_AT);
-
- AmbariLdapConfiguration ambariLdapConfiguration = new AmbariLdapConfiguration(ldapPropsMap);
-
-
- try {
- LOGGER.info("Authenticating user {} against the LDAP server ...", TEST_USER);
- LdapConfigurationConverter ldapConfigurationConverter = new LdapConfigurationConverter();
-
- LdapConnectionConfig connectionConfig = ldapConfigurationConverter.getLdapConnectionConfig(ambariLdapConfiguration);
- LdapNetworkConnection connection = new LdapNetworkConnection(connectionConfig);
-
- String filter = FilterBuilder.and(
- FilterBuilder.equal(SchemaConstants.OBJECT_CLASS_AT, ambariLdapConfiguration.userObjectClass()),
- FilterBuilder.equal(ambariLdapConfiguration.userNameAttribute(), TEST_USER))
- .toString();
-
- SearchRequest searchRequest = new SearchRequestImpl();
- searchRequest.setBase(new Dn(ambariLdapConfiguration.baseDn()));
- searchRequest.setFilter(filter);
- searchRequest.setScope(SearchScope.SUBTREE);
-
- LOGGER.info("loking up user: {} based on the filtr: {}", TEST_USER, filter);
-
- connection.bind();
- SearchCursor searchCursor = connection.search(searchRequest);
-
- while (searchCursor.next()) {
- Response response = searchCursor.get();
-
- // process the SearchResultEntry
- if (response instanceof SearchResultEntry) {
- Entry resultEntry = ((SearchResultEntry) response).getEntry();
- System.out.println(resultEntry);
- }
- }
-
- searchCursor.close();
-
- } catch (Exception e) {
- throw new AmbariException("Error during user authentication check", e);
- }
-
- }
-
-}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/ambari/blob/86e105f8/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConfigurationValidatorServiceTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConfigurationValidatorServiceTest.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConfigurationValidatorServiceTest.java
new file mode 100644
index 0000000..5c9d304
--- /dev/null
+++ b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ad/DefaultLdapConfigurationValidatorServiceTest.java
@@ -0,0 +1,156 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.service.ad;
+
+import static org.junit.Assert.assertNotNull;
+
+import java.util.Map;
+
+import org.apache.ambari.server.AmbariException;
+import org.apache.ambari.server.ldap.AmbariLdapConfiguration;
+import org.apache.ambari.server.ldap.LdapConfigurationValidatorService;
+import org.apache.ambari.server.ldap.service.LdapConnectionService;
+import org.apache.directory.api.ldap.model.cursor.EntryCursor;
+import org.apache.directory.api.ldap.model.cursor.SearchCursor;
+import org.apache.directory.api.ldap.model.entry.Entry;
+import org.apache.directory.api.ldap.model.message.Response;
+import org.apache.directory.api.ldap.model.message.SearchRequest;
+import org.apache.directory.api.ldap.model.message.SearchRequestImpl;
+import org.apache.directory.api.ldap.model.message.SearchResultEntry;
+import org.apache.directory.api.ldap.model.message.SearchScope;
+import org.apache.directory.api.ldap.model.name.Dn;
+import org.apache.directory.ldap.client.api.LdapConnection;
+import org.apache.directory.ldap.client.api.LdapConnectionConfig;
+import org.apache.directory.ldap.client.api.LdapNetworkConnection;
+import org.apache.directory.ldap.client.api.search.FilterBuilder;
+import org.apache.directory.shared.ldap.constants.SchemaConstants;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.collect.Maps;
+
+public class DefaultLdapConfigurationValidatorServiceTest {
+ private static final Logger LOGGER = LoggerFactory.getLogger(DefaultLdapConfigurationValidatorService.class);
+ private static final String TEST_USER = "einstein";
+
+ LdapConfigurationValidatorService ldapConfigurationValidatorService = new DefaultLdapConfigurationValidatorService();
+
+
+ @Test
+ public void testCheckAttributes() throws Exception {
+
+ // WHEN
+ LdapConnectionConfig config = new LdapConnectionConfig();
+ config.setLdapHost("localhost");
+ config.setLdapPort(389);
+ LdapConnection connection = new LdapNetworkConnection(config);
+
+ // THEN
+ connection.anonymousBind();
+
+
+ EntryCursor cursor = connection.search("dc=dev,dc=local", "(objectclass=*)", SearchScope.ONELEVEL);
+
+ for (Entry entry : cursor) {
+ assertNotNull(entry);
+ System.out.println(entry);
+ }
+
+ cursor.close();
+
+ }
+
+ @Test
+ public void testCheckUserAttributes() throws Exception {
+ Map<String, Object> ldapPropsMap = Maps.newHashMap();
+
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.BIND_ANONIMOUSLY.propertyName(), false);
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.LDAP_SERVER_HOST.propertyName(), "ldap.forumsys.com");
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.LDAP_SERVER_PORT.propertyName(), "389");
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.BASE_DN.propertyName(), "dc=example,dc=com");
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.USER_OBJECT_CLASS.propertyName(), SchemaConstants.PERSON_OC);
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.GROUP_OBJECT_CLASS.propertyName(), SchemaConstants.GROUP_OF_UNIQUE_NAMES_OC);
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.GROUP_NAME_ATTRIBUTE.propertyName(), SchemaConstants.CN_AT);
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.GROUP_MEMBER_ATTRIBUTE.propertyName(), SchemaConstants.UNIQUE_MEMBER_AT);
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.USER_NAME_ATTRIBUTE.propertyName(), SchemaConstants.UID_AT);
+
+ AmbariLdapConfiguration ambariLdapConfiguration = new AmbariLdapConfiguration(ldapPropsMap);
+
+
+ try {
+ LOGGER.info("Authenticating user {} against the LDAP server ...", TEST_USER);
+ LdapConnectionService connectionService = new DefaultLdapConnectionService();
+ LdapNetworkConnection connection = connectionService.createLdapConnection(ambariLdapConfiguration);
+
+ String filter = FilterBuilder.and(
+ FilterBuilder.equal(SchemaConstants.OBJECT_CLASS_AT, ambariLdapConfiguration.userObjectClass()),
+ FilterBuilder.equal(ambariLdapConfiguration.userNameAttribute(), TEST_USER))
+ .toString();
+
+ SearchRequest searchRequest = new SearchRequestImpl();
+ searchRequest.setBase(new Dn(ambariLdapConfiguration.baseDn()));
+ searchRequest.setFilter(filter);
+ searchRequest.setScope(SearchScope.SUBTREE);
+
+ LOGGER.info("loking up user: {} based on the filtr: {}", TEST_USER, filter);
+
+ connection.bind();
+ SearchCursor searchCursor = connection.search(searchRequest);
+
+ while (searchCursor.next()) {
+ Response response = searchCursor.get();
+
+ // process the SearchResultEntry
+ if (response instanceof SearchResultEntry) {
+ Entry resultEntry = ((SearchResultEntry) response).getEntry();
+ System.out.println(resultEntry);
+ }
+ }
+
+ searchCursor.close();
+
+ } catch (Exception e) {
+ throw new AmbariException("Error during user authentication check", e);
+ }
+
+ }
+
+ @Test
+ public void testRetrieveGorupsForuser() throws Exception {
+ // GIVEN
+ Map<String, Object> ldapPropsMap = Maps.newHashMap();
+
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.BIND_ANONIMOUSLY.propertyName(), "true");
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.LDAP_SERVER_HOST.propertyName(), "ldap.forumsys.com");
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.LDAP_SERVER_PORT.propertyName(), "389");
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.BASE_DN.propertyName(), "dc=example,dc=com");
+
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.USER_OBJECT_CLASS.propertyName(), SchemaConstants.PERSON_OC);
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.USER_NAME_ATTRIBUTE.propertyName(), SchemaConstants.UID_AT);
+
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.GROUP_OBJECT_CLASS.propertyName(), SchemaConstants.GROUP_OF_UNIQUE_NAMES_OC);
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.GROUP_NAME_ATTRIBUTE.propertyName(), SchemaConstants.CN_AT);
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.GROUP_MEMBER_ATTRIBUTE.propertyName(), SchemaConstants.UNIQUE_MEMBER_AT);
+ ldapPropsMap.put(AmbariLdapConfiguration.LdapConfigProperty.GROUP_SEARCH_BASE.propertyName(), "dc=example,dc=com");
+
+
+ AmbariLdapConfiguration ambariLdapConfiguration = new AmbariLdapConfiguration(ldapPropsMap);
+ LdapConnectionService connectionService = new DefaultLdapConnectionService();
+ LdapNetworkConnection ldapConnection = connectionService.createLdapConnection(ambariLdapConfiguration);
+
+ ldapConfigurationValidatorService.checkGroupAttributes(ldapConnection, "uid=einstein,dc=example,dc=com", ambariLdapConfiguration);
+ }
+}
\ No newline at end of file
[08/33] ambari git commit: AMBARI-21307 Added new resource related
changes to the db creation ddl-s
Posted by lp...@apache.org.
AMBARI-21307 Added new resource related changes to the db creation ddl-s
Project: http://git-wip-us.apache.org/repos/asf/ambari/repo
Commit: http://git-wip-us.apache.org/repos/asf/ambari/commit/4d2425b5
Tree: http://git-wip-us.apache.org/repos/asf/ambari/tree/4d2425b5
Diff: http://git-wip-us.apache.org/repos/asf/ambari/diff/4d2425b5
Branch: refs/heads/feature-branch-AMBARI-21307
Commit: 4d2425b5e9203d1bec7c2715110dba102cf8836b
Parents: 4735052
Author: lpuskas <lp...@apache.org>
Authored: Thu Jul 6 18:15:18 2017 +0200
Committer: lpuskas <lp...@apache.org>
Committed: Fri Oct 13 17:20:48 2017 +0200
----------------------------------------------------------------------
.../AmbariConfigurationResourceProvider.java | 12 ++--
.../server/orm/dao/AmbariConfigurationDAO.java | 65 ++------------------
.../apache/ambari/server/orm/dao/DaoUtils.java | 13 +---
.../main/resources/Ambari-DDL-Derby-CREATE.sql | 21 +++++++
.../main/resources/Ambari-DDL-MySQL-CREATE.sql | 20 ++++++
.../main/resources/Ambari-DDL-Oracle-CREATE.sql | 20 ++++++
.../resources/Ambari-DDL-Postgres-CREATE.sql | 14 ++---
.../resources/Ambari-DDL-SQLAnywhere-CREATE.sql | 20 ++++++
.../resources/Ambari-DDL-SQLServer-CREATE.sql | 20 ++++++
9 files changed, 120 insertions(+), 85 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/ambari/blob/4d2425b5/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AmbariConfigurationResourceProvider.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AmbariConfigurationResourceProvider.java b/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AmbariConfigurationResourceProvider.java
index 5e5af9e..e8f186d 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AmbariConfigurationResourceProvider.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/controller/internal/AmbariConfigurationResourceProvider.java
@@ -97,14 +97,14 @@ public class AmbariConfigurationResourceProvider extends AbstractAuthorizedResou
}
}
- private static Set<String> properties = Sets.newHashSet(
+ private static Set<String> PROPERTIES = Sets.newHashSet(
ResourcePropertyId.ID.getPropertyId(),
ResourcePropertyId.TYPE.getPropertyId(),
ResourcePropertyId.VERSION.getPropertyId(),
ResourcePropertyId.VERSION_TAG.getPropertyId(),
ResourcePropertyId.DATA.getPropertyId());
- private static Map<Resource.Type, String> pkPropertyMap = Collections.unmodifiableMap(
+ private static Map<Resource.Type, String> PK_PROPERTY_MAP = Collections.unmodifiableMap(
new HashMap<Resource.Type, String>() {{
put(Resource.Type.AmbariConfiguration, ResourcePropertyId.ID.getPropertyId());
}}
@@ -117,7 +117,7 @@ public class AmbariConfigurationResourceProvider extends AbstractAuthorizedResou
private Gson gson;
protected AmbariConfigurationResourceProvider() {
- super(properties, pkPropertyMap);
+ super(PROPERTIES, PK_PROPERTY_MAP);
setRequiredCreateAuthorizations(EnumSet.of(RoleAuthorization.AMBARI_MANAGE_CONFIGURATION));
setRequiredDeleteAuthorizations(EnumSet.of(RoleAuthorization.AMBARI_MANAGE_CONFIGURATION));
@@ -126,7 +126,7 @@ public class AmbariConfigurationResourceProvider extends AbstractAuthorizedResou
@Override
protected Set<String> getPKPropertyIds() {
- return Sets.newHashSet("AmbariConfiguration/id");
+ return Sets.newHashSet(ResourcePropertyId.ID.getPropertyId());
}
@Override
@@ -137,7 +137,7 @@ public class AmbariConfigurationResourceProvider extends AbstractAuthorizedResou
AmbariConfigurationEntity ambariConfigurationEntity = getEntityFromRequest(request);
LOGGER.info("Persisting new ambari configuration: {} ", ambariConfigurationEntity);
- ambariConfigurationDAO.persist(ambariConfigurationEntity);
+ ambariConfigurationDAO.create(ambariConfigurationEntity);
return getRequestStatus(null);
}
@@ -170,7 +170,7 @@ public class AmbariConfigurationResourceProvider extends AbstractAuthorizedResou
} else {
LOGGER.debug("Deleting amari configuration with id: {}", idFromRequest);
try {
- ambariConfigurationDAO.deleteById(idFromRequest);
+ ambariConfigurationDAO.removeByPK(idFromRequest);
} catch (IllegalStateException e) {
throw new NoSuchResourceException(e.getMessage());
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/4d2425b5/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/AmbariConfigurationDAO.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/AmbariConfigurationDAO.java b/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/AmbariConfigurationDAO.java
index dea37eb..c29a423 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/AmbariConfigurationDAO.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/AmbariConfigurationDAO.java
@@ -14,79 +14,24 @@
package org.apache.ambari.server.orm.dao;
-import java.util.List;
-
import javax.inject.Inject;
-import javax.inject.Provider;
import javax.inject.Singleton;
-import javax.persistence.EntityManager;
-import javax.persistence.TypedQuery;
-import org.apache.ambari.server.orm.RequiresSession;
import org.apache.ambari.server.orm.entities.AmbariConfigurationEntity;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.inject.persist.Transactional;
/**
* DAO dealing with ambari configuration related JPA operations.
*/
@Singleton
-// todo extend CrudDao (amend crud dao to handle NPEs)
-public class AmbariConfigurationDAO {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(AmbariConfigurationDAO.class);
-
- @Inject
- private Provider<EntityManager> entityManagerProvider;
+public class AmbariConfigurationDAO extends CrudDAO<AmbariConfigurationEntity, Long> {
- /**
- * DAO utilities for dealing mostly with {@link TypedQuery} results.
- */
@Inject
- private DaoUtils daoUtils;
-
- public AmbariConfigurationEntity findByid(Long id) {
- return entityManagerProvider.get().find(AmbariConfigurationEntity.class, id);
- }
-
- @RequiresSession
- @Transactional
- public void persist(AmbariConfigurationEntity entity) {
- LOGGER.debug("Persisting ambari configuration: {}", entity);
- entityManagerProvider.get().persist(entity);
+ public AmbariConfigurationDAO() {
+ super(AmbariConfigurationEntity.class);
}
- @RequiresSession
- public List<AmbariConfigurationEntity> findAll() {
- TypedQuery<AmbariConfigurationEntity> query = entityManagerProvider.get().createNamedQuery(
- "AmbariConfigurationEntity.findAll", AmbariConfigurationEntity.class);
- return daoUtils.selectList(query);
+ public void create(AmbariConfigurationEntity entity) {
+ super.create(entity);
}
-
-
- @RequiresSession
- @Transactional
- public void deleteById(Long ambariConfigurationId) {
-
- if (ambariConfigurationId == null) {
- throw new IllegalArgumentException("No Ambari Configuration id provided.");
- }
-
- LOGGER.debug("Removing Ambari Configuration with id :{}", ambariConfigurationId);
-
- AmbariConfigurationEntity ambariConfigurationEntity = findByid(ambariConfigurationId);
- if (ambariConfigurationEntity == null) {
- String msg = String.format("No Ambari Configuration found with id: %s", ambariConfigurationId);
- LOGGER.debug(msg);
- throw new IllegalStateException(msg);
- }
-
- entityManagerProvider.get().remove(ambariConfigurationEntity);
- LOGGER.debug("Ambari Configuration with id: {}", ambariConfigurationId);
- }
-
-
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/4d2425b5/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/DaoUtils.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/DaoUtils.java b/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/DaoUtils.java
index cd3faf0..e6112ad 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/DaoUtils.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/orm/dao/DaoUtils.java
@@ -18,8 +18,6 @@
package org.apache.ambari.server.orm.dao;
-import static org.apache.ambari.server.orm.DBAccessor.DbType;
-
import java.util.Collections;
import java.util.List;
@@ -31,19 +29,10 @@ import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
-import org.apache.ambari.server.orm.DBAccessor;
-
-import com.google.inject.Inject;
import com.google.inject.Singleton;
@Singleton
public class DaoUtils {
- @Inject
- private DBAccessor dbAccessor;
-
- public DbType getDbType() {
- return dbAccessor.getDbType();
- }
public <T> List<T> selectAll(EntityManager entityManager, Class<T> entityClass) {
CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
@@ -92,7 +81,7 @@ public class DaoUtils {
public void setParameters(Query query, Object... parameters) {
for (int i = 0; i < parameters.length; i++) {
- query.setParameter(i+1, parameters[i]);
+ query.setParameter(i + 1, parameters[i]);
}
}
}
http://git-wip-us.apache.org/repos/asf/ambari/blob/4d2425b5/ambari-server/src/main/resources/Ambari-DDL-Derby-CREATE.sql
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/resources/Ambari-DDL-Derby-CREATE.sql b/ambari-server/src/main/resources/Ambari-DDL-Derby-CREATE.sql
index 614af1e..cebd33e 100644
--- a/ambari-server/src/main/resources/Ambari-DDL-Derby-CREATE.sql
+++ b/ambari-server/src/main/resources/Ambari-DDL-Derby-CREATE.sql
@@ -84,6 +84,23 @@ CREATE TABLE clusterconfig (
CONSTRAINT UQ_config_type_tag UNIQUE (version_tag, type_name, cluster_id),
CONSTRAINT UQ_config_type_version UNIQUE (cluster_id, type_name, version));
+CREATE TABLE configuration_base (
+ id BIGINT NOT NULL,
+ version_tag VARCHAR(255) NOT NULL,
+ version BIGINT NOT NULL,
+ type VARCHAR(255) NOT NULL,
+ data VARCHAR(3000) NOT NULL,
+ attributes VARCHAR(3000),
+ create_timestamp BIGINT NOT NULL,
+ CONSTRAINT PK_configuration_base PRIMARY KEY (id)
+);
+
+CREATE TABLE ambari_configuration (
+ id BIGINT NOT NULL,
+ CONSTRAINT PK_ambari_configuration PRIMARY KEY (id),
+ CONSTRAINT FK_ambari_configuration_configuration_base FOREIGN KEY (id) REFERENCES configuration_base (id)
+);
+
CREATE TABLE serviceconfig (
service_config_id BIGINT NOT NULL,
cluster_id BIGINT NOT NULL,
@@ -1146,6 +1163,8 @@ INSERT INTO ambari_sequences (sequence_name, sequence_value)
union all
select 'servicecomponent_version_id_seq', 0 FROM SYSIBM.SYSDUMMY1
union all
+ select 'configuration_id_seq', 0 FROM SYSIBM.SYSDUMMY1
+ union all
select 'hostcomponentdesiredstate_id_seq', 0 FROM SYSIBM.SYSDUMMY1;
@@ -1246,6 +1265,7 @@ INSERT INTO roleauthorization(authorization_id, authorization_name)
SELECT 'AMBARI.ADD_DELETE_CLUSTERS', 'Create new clusters' FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT 'AMBARI.RENAME_CLUSTER', 'Rename clusters' FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT 'AMBARI.MANAGE_SETTINGS', 'Manage settings' FROM SYSIBM.SYSDUMMY1 UNION ALL
+ SELECT 'AMBARI.MANAGE_CONFIGURATION', 'Manage ambari configurations' FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT 'AMBARI.MANAGE_USERS', 'Manage users' FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT 'AMBARI.MANAGE_GROUPS', 'Manage groups' FROM SYSIBM.SYSDUMMY1 UNION ALL
SELECT 'AMBARI.MANAGE_VIEWS', 'Manage Ambari Views' FROM SYSIBM.SYSDUMMY1 UNION ALL
@@ -1447,6 +1467,7 @@ INSERT INTO permission_roleauthorization(permission_id, authorization_id)
SELECT permission_id, 'AMBARI.ADD_DELETE_CLUSTERS' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
SELECT permission_id, 'AMBARI.RENAME_CLUSTER' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
SELECT permission_id, 'AMBARI.MANAGE_SETTINGS' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
+ SELECT permission_id, 'AMBARI.MANAGE_CONFIGURATION' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
SELECT permission_id, 'AMBARI.MANAGE_USERS' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
SELECT permission_id, 'AMBARI.MANAGE_GROUPS' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
SELECT permission_id, 'AMBARI.MANAGE_VIEWS' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
http://git-wip-us.apache.org/repos/asf/ambari/blob/4d2425b5/ambari-server/src/main/resources/Ambari-DDL-MySQL-CREATE.sql
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/resources/Ambari-DDL-MySQL-CREATE.sql b/ambari-server/src/main/resources/Ambari-DDL-MySQL-CREATE.sql
index 530411a..b8b506a 100644
--- a/ambari-server/src/main/resources/Ambari-DDL-MySQL-CREATE.sql
+++ b/ambari-server/src/main/resources/Ambari-DDL-MySQL-CREATE.sql
@@ -104,6 +104,23 @@ CREATE TABLE clusterconfig (
CONSTRAINT UQ_config_type_tag UNIQUE (cluster_id, type_name, version_tag),
CONSTRAINT UQ_config_type_version UNIQUE (cluster_id, type_name, version));
+CREATE TABLE configuration_base (
+ id BIGINT NOT NULL,
+ version_tag VARCHAR(100) NOT NULL,
+ version BIGINT NOT NULL,
+ type VARCHAR(100) NOT NULL,
+ data LONGTEXT NOT NULL,
+ attributes LONGTEXT,
+ create_timestamp BIGINT NOT NULL,
+ CONSTRAINT PK_configuration_base PRIMARY KEY (id)
+);
+
+CREATE TABLE ambari_configuration (
+ id BIGINT NOT NULL,
+ CONSTRAINT PK_ambari_configuration PRIMARY KEY (id),
+ CONSTRAINT FK_ambari_configuration_configuration_base FOREIGN KEY (id) REFERENCES configuration_base (id)
+);
+
CREATE TABLE serviceconfig (
service_config_id BIGINT NOT NULL,
cluster_id BIGINT NOT NULL,
@@ -1110,6 +1127,7 @@ INSERT INTO ambari_sequences(sequence_name, sequence_value) VALUES
('remote_cluster_id_seq', 0),
('remote_cluster_service_id_seq', 0),
('servicecomponent_version_id_seq', 0),
+ ('configuration_id_seq', 0),
('hostcomponentdesiredstate_id_seq', 0);
INSERT INTO adminresourcetype (resource_type_id, resource_type_name) VALUES
@@ -1194,6 +1212,7 @@ INSERT INTO roleauthorization(authorization_id, authorization_name)
SELECT 'AMBARI.ADD_DELETE_CLUSTERS', 'Create new clusters' UNION ALL
SELECT 'AMBARI.RENAME_CLUSTER', 'Rename clusters' UNION ALL
SELECT 'AMBARI.MANAGE_SETTINGS', 'Manage administrative settings' UNION ALL
+ SELECT 'AMBARI.MANAGE_CONFIGURATION', 'Manage ambari configuration' UNION ALL
SELECT 'AMBARI.MANAGE_USERS', 'Manage users' UNION ALL
SELECT 'AMBARI.MANAGE_GROUPS', 'Manage groups' UNION ALL
SELECT 'AMBARI.MANAGE_VIEWS', 'Manage Ambari Views' UNION ALL
@@ -1399,6 +1418,7 @@ INSERT INTO permission_roleauthorization(permission_id, authorization_id)
SELECT permission_id, 'AMBARI.ADD_DELETE_CLUSTERS' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
SELECT permission_id, 'AMBARI.RENAME_CLUSTER' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
SELECT permission_id, 'AMBARI.MANAGE_SETTINGS' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
+ SELECT permission_id, 'AMBARI.MANAGE_CONFIGURATION' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
SELECT permission_id, 'AMBARI.MANAGE_USERS' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
SELECT permission_id, 'AMBARI.MANAGE_GROUPS' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
SELECT permission_id, 'AMBARI.MANAGE_VIEWS' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
http://git-wip-us.apache.org/repos/asf/ambari/blob/4d2425b5/ambari-server/src/main/resources/Ambari-DDL-Oracle-CREATE.sql
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/resources/Ambari-DDL-Oracle-CREATE.sql b/ambari-server/src/main/resources/Ambari-DDL-Oracle-CREATE.sql
index ebe5f12..1e90426 100644
--- a/ambari-server/src/main/resources/Ambari-DDL-Oracle-CREATE.sql
+++ b/ambari-server/src/main/resources/Ambari-DDL-Oracle-CREATE.sql
@@ -84,6 +84,23 @@ CREATE TABLE clusterconfig (
CONSTRAINT UQ_config_type_tag UNIQUE (cluster_id, type_name, version_tag),
CONSTRAINT UQ_config_type_version UNIQUE (cluster_id, type_name, version));
+CREATE TABLE configuration_base (
+ id NUMBER(19) NOT NULL,
+ version_tag VARCHAR(255) NOT NULL,
+ version NUMBER(19) NOT NULL,
+ type VARCHAR(255) NOT NULL,
+ data CLOB NOT NULL,
+ attributes CLOB,
+ create_timestamp NUMBER(19) NOT NULL,
+ CONSTRAINT PK_configuration_base PRIMARY KEY (id)
+);
+
+CREATE TABLE ambari_configuration (
+ id NUMBER(19) NOT NULL,
+ CONSTRAINT PK_ambari_configuration PRIMARY KEY (id),
+ CONSTRAINT FK_ambari_configuration_configuration_base FOREIGN KEY (id) REFERENCES configuration_base (id)
+);
+
CREATE TABLE serviceconfig (
service_config_id NUMBER(19) NOT NULL,
cluster_id NUMBER(19) NOT NULL,
@@ -1089,6 +1106,7 @@ INSERT INTO ambari_sequences(sequence_name, sequence_value) values ('ambari_oper
INSERT INTO ambari_sequences(sequence_name, sequence_value) values ('remote_cluster_id_seq', 0);
INSERT INTO ambari_sequences(sequence_name, sequence_value) values ('remote_cluster_service_id_seq', 0);
INSERT INTO ambari_sequences(sequence_name, sequence_value) values ('servicecomponent_version_id_seq', 0);
+INSERT INTO ambari_sequences(sequence_name, sequence_value) values ('configuration_id_seq', 0);
INSERT INTO ambari_sequences(sequence_name, sequence_value) values ('hostcomponentdesiredstate_id_seq', 0);
INSERT INTO metainfo("metainfo_key", "metainfo_value") values ('version', '${ambariSchemaVersion}');
@@ -1192,6 +1210,7 @@ INSERT INTO roleauthorization(authorization_id, authorization_name)
SELECT 'AMBARI.ADD_DELETE_CLUSTERS', 'Create new clusters' FROM dual UNION ALL
SELECT 'AMBARI.RENAME_CLUSTER', 'Rename clusters' FROM dual UNION ALL
SELECT 'AMBARI.MANAGE_SETTINGS', 'Manage settings' FROM dual UNION ALL
+ SELECT 'AMBARI.MANAGE_CONFIGURATION', 'Manage ambari configuration' FROM dual UNION ALL
SELECT 'AMBARI.MANAGE_USERS', 'Manage users' FROM dual UNION ALL
SELECT 'AMBARI.MANAGE_GROUPS', 'Manage groups' FROM dual UNION ALL
SELECT 'AMBARI.MANAGE_VIEWS', 'Manage Ambari Views' FROM dual UNION ALL
@@ -1397,6 +1416,7 @@ INSERT INTO permission_roleauthorization(permission_id, authorization_id)
SELECT permission_id, 'AMBARI.ADD_DELETE_CLUSTERS' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
SELECT permission_id, 'AMBARI.RENAME_CLUSTER' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
SELECT permission_id, 'AMBARI.MANAGE_SETTINGS' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
+ SELECT permission_id, 'AMBARI.MANAGE_CONFIGURATION' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
SELECT permission_id, 'AMBARI.MANAGE_USERS' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
SELECT permission_id, 'AMBARI.MANAGE_GROUPS' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
SELECT permission_id, 'AMBARI.MANAGE_VIEWS' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
http://git-wip-us.apache.org/repos/asf/ambari/blob/4d2425b5/ambari-server/src/main/resources/Ambari-DDL-Postgres-CREATE.sql
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/resources/Ambari-DDL-Postgres-CREATE.sql b/ambari-server/src/main/resources/Ambari-DDL-Postgres-CREATE.sql
index 01b3324..583a51b 100644
--- a/ambari-server/src/main/resources/Ambari-DDL-Postgres-CREATE.sql
+++ b/ambari-server/src/main/resources/Ambari-DDL-Postgres-CREATE.sql
@@ -67,13 +67,13 @@ CREATE TABLE clusters (
);
CREATE TABLE configuration_base (
- id BIGINT NOT NULL,
- version_tag VARCHAR(255) NOT NULL,
- version BIGINT NOT NULL,
- type VARCHAR(255) NOT NULL,
- data TEXT NOT NULL,
- attributes TEXT,
- create_timestamp BIGINT NOT NULL,
+ id BIGINT NOT NULL,
+ version_tag VARCHAR(255) NOT NULL,
+ version BIGINT NOT NULL,
+ type VARCHAR(255) NOT NULL,
+ data TEXT NOT NULL,
+ attributes TEXT,
+ create_timestamp BIGINT NOT NULL,
CONSTRAINT PK_configuration_base PRIMARY KEY (id)
);
http://git-wip-us.apache.org/repos/asf/ambari/blob/4d2425b5/ambari-server/src/main/resources/Ambari-DDL-SQLAnywhere-CREATE.sql
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/resources/Ambari-DDL-SQLAnywhere-CREATE.sql b/ambari-server/src/main/resources/Ambari-DDL-SQLAnywhere-CREATE.sql
index f64ff80..2104b2d 100644
--- a/ambari-server/src/main/resources/Ambari-DDL-SQLAnywhere-CREATE.sql
+++ b/ambari-server/src/main/resources/Ambari-DDL-SQLAnywhere-CREATE.sql
@@ -83,6 +83,23 @@ CREATE TABLE clusterconfig (
CONSTRAINT UQ_config_type_tag UNIQUE (cluster_id, type_name, version_tag),
CONSTRAINT UQ_config_type_version UNIQUE (cluster_id, type_name, version));
+CREATE TABLE configuration_base (
+ id NUMERIC(19) NOT NULL,
+ version_tag VARCHAR(255) NOT NULL,
+ version NUMERIC(19) NOT NULL,
+ type VARCHAR(255) NOT NULL,
+ data TEXT NOT NULL,
+ attributes TEXT,
+ create_timestamp NUMERIC(19) NOT NULL,
+ CONSTRAINT PK_configuration_base PRIMARY KEY (id)
+);
+
+CREATE TABLE ambari_configuration (
+ id NUMERIC(19) NOT NULL,
+ CONSTRAINT PK_ambari_configuration PRIMARY KEY (id),
+ CONSTRAINT FK_ambari_configuration_configuration_base FOREIGN KEY (id) REFERENCES configuration_base (id)
+);
+
CREATE TABLE serviceconfig (
service_config_id NUMERIC(19) NOT NULL,
cluster_id NUMERIC(19) NOT NULL,
@@ -1088,6 +1105,7 @@ INSERT INTO ambari_sequences(sequence_name, sequence_value) values ('remote_clus
INSERT INTO ambari_sequences(sequence_name, sequence_value) values ('remote_cluster_service_id_seq', 0);
INSERT INTO ambari_sequences(sequence_name, sequence_value) values ('servicecomponent_version_id_seq', 0);
INSERT INTO ambari_sequences(sequence_name, sequence_value) values ('hostcomponentdesiredstate_id_seq', 0);
+INSERT INTO ambari_sequences(sequence_name, sequence_value) values ('configuration_id_seq', 0);
insert into adminresourcetype (resource_type_id, resource_type_name)
select 1, 'AMBARI'
@@ -1188,6 +1206,7 @@ insert into adminpermission(permission_id, permission_name, resource_type_id, pe
SELECT 'AMBARI.ADD_DELETE_CLUSTERS', 'Create new clusters' UNION ALL
SELECT 'AMBARI.RENAME_CLUSTER', 'Rename clusters' UNION ALL
SELECT 'AMBARI.MANAGE_SETTINGS', 'Manage settings' UNION ALL
+ SELECT 'AMBARI.MANAGE_CONFIGURATION', 'Manage ambari configuration' UNION ALL
SELECT 'AMBARI.MANAGE_USERS', 'Manage users' UNION ALL
SELECT 'AMBARI.MANAGE_GROUPS', 'Manage groups' UNION ALL
SELECT 'AMBARI.MANAGE_VIEWS', 'Manage Ambari Views' UNION ALL
@@ -1393,6 +1412,7 @@ insert into adminpermission(permission_id, permission_name, resource_type_id, pe
SELECT permission_id, 'AMBARI.ADD_DELETE_CLUSTERS' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
SELECT permission_id, 'AMBARI.RENAME_CLUSTER' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
SELECT permission_id, 'AMBARI.MANAGE_SETTINGS' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
+ SELECT permission_id, 'AMBARI.MANAGE_CONFIGURATION' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
SELECT permission_id, 'AMBARI.MANAGE_USERS' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
SELECT permission_id, 'AMBARI.MANAGE_GROUPS' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
SELECT permission_id, 'AMBARI.MANAGE_VIEWS' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
http://git-wip-us.apache.org/repos/asf/ambari/blob/4d2425b5/ambari-server/src/main/resources/Ambari-DDL-SQLServer-CREATE.sql
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/resources/Ambari-DDL-SQLServer-CREATE.sql b/ambari-server/src/main/resources/Ambari-DDL-SQLServer-CREATE.sql
index 7a3feaf..7d248b6 100644
--- a/ambari-server/src/main/resources/Ambari-DDL-SQLServer-CREATE.sql
+++ b/ambari-server/src/main/resources/Ambari-DDL-SQLServer-CREATE.sql
@@ -97,6 +97,23 @@ CREATE TABLE clusterconfig (
CONSTRAINT UQ_config_type_tag UNIQUE (cluster_id, type_name, version_tag),
CONSTRAINT UQ_config_type_version UNIQUE (cluster_id, type_name, version));
+CREATE TABLE configuration_base (
+ id BIGINT NOT NULL,
+ version_tag VARCHAR(255) NOT NULL,
+ version BIGINT NOT NULL,
+ type VARCHAR(255) NOT NULL,
+ data VARCHAR(MAX) NOT NULL,
+ attributes VARCHAR(MAX),
+ create_timestamp BIGINT NOT NULL,
+ CONSTRAINT PK_configuration_base PRIMARY KEY (id)
+);
+
+CREATE TABLE ambari_configuration (
+ id BIGINT NOT NULL,
+ CONSTRAINT PK_ambari_configuration PRIMARY KEY (id),
+ CONSTRAINT FK_ambari_configuration_configuration_base FOREIGN KEY (id) REFERENCES configuration_base (id)
+);
+
CREATE TABLE serviceconfig (
service_config_id BIGINT NOT NULL,
cluster_id BIGINT NOT NULL,
@@ -1113,6 +1130,7 @@ BEGIN TRANSACTION
('remote_cluster_id_seq', 0),
('remote_cluster_service_id_seq', 0),
('servicecomponent_version_id_seq', 0),
+ ('configuration_id_seq', 0),
('hostcomponentdesiredstate_id_seq', 0);
insert into adminresourcetype (resource_type_id, resource_type_name)
@@ -1201,6 +1219,7 @@ BEGIN TRANSACTION
SELECT 'AMBARI.ADD_DELETE_CLUSTERS', 'Create new clusters' UNION ALL
SELECT 'AMBARI.RENAME_CLUSTER', 'Rename clusters' UNION ALL
SELECT 'AMBARI.MANAGE_SETTINGS', 'Manage settings' UNION ALL
+ SELECT 'AMBARI.MANAGE_CONFIGURATION', 'Manage ambari configuration' UNION ALL
SELECT 'AMBARI.MANAGE_USERS', 'Manage users' UNION ALL
SELECT 'AMBARI.MANAGE_GROUPS', 'Manage groups' UNION ALL
SELECT 'AMBARI.MANAGE_VIEWS', 'Manage Ambari Views' UNION ALL
@@ -1406,6 +1425,7 @@ BEGIN TRANSACTION
SELECT permission_id, 'AMBARI.ADD_DELETE_CLUSTERS' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
SELECT permission_id, 'AMBARI.RENAME_CLUSTER' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
SELECT permission_id, 'AMBARI.MANAGE_SETTINGS' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
+ SELECT permission_id, 'AMBARI.MANAGE_CONFIGURATION' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
SELECT permission_id, 'AMBARI.MANAGE_USERS' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
SELECT permission_id, 'AMBARI.MANAGE_GROUPS' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
SELECT permission_id, 'AMBARI.MANAGE_VIEWS' FROM adminpermission WHERE permission_name='AMBARI.ADMINISTRATOR' UNION ALL
[23/33] ambari git commit: AMBARI-21307 organized code,
fixed build failures
Posted by lp...@apache.org.
AMBARI-21307 organized code, fixed build failures
Project: http://git-wip-us.apache.org/repos/asf/ambari/repo
Commit: http://git-wip-us.apache.org/repos/asf/ambari/commit/b8128f09
Tree: http://git-wip-us.apache.org/repos/asf/ambari/tree/b8128f09
Diff: http://git-wip-us.apache.org/repos/asf/ambari/diff/b8128f09
Branch: refs/heads/feature-branch-AMBARI-21307
Commit: b8128f0922fc54105017b8d5beb40b57ee165960
Parents: 38724b9
Author: lpuskas <lp...@apache.org>
Authored: Thu Sep 14 17:58:59 2017 +0200
Committer: lpuskas <lp...@apache.org>
Committed: Fri Oct 13 17:20:52 2017 +0200
----------------------------------------------------------------------
.../ldap/domain/AmbariLdapConfigKeys.java | 72 ++++++++++++++++++++
.../ldap/domain/AmbariLdapConfiguration.java | 3 -
.../ldap/domain/LdapConfigurationFactory.java | 2 +-
.../ldap/service/AmbariLdapConfigKeys.java | 72 --------------------
.../DefaultLdapAttributeDetectionService.java | 2 +-
.../domain/AmbariLdapConfigurationTest.java | 19 ++++++
.../TestAmbariLdapConfigurationFactory.java | 29 ++++++++
...efaultLdapAttributeDetectionServiceTest.java | 9 ++-
.../DefaultLdapConfigurationServiceTest.java | 19 +++++-
9 files changed, 144 insertions(+), 83 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/ambari/blob/b8128f09/ambari-server/src/main/java/org/apache/ambari/server/ldap/domain/AmbariLdapConfigKeys.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/domain/AmbariLdapConfigKeys.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/domain/AmbariLdapConfigKeys.java
new file mode 100644
index 0000000..b7b41a3
--- /dev/null
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/domain/AmbariLdapConfigKeys.java
@@ -0,0 +1,72 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.domain;
+
+/**
+ * Constants representing supported LDAP related property names
+ * // todo extend this with validation information, description, defaults maybe
+ */
+public enum AmbariLdapConfigKeys {
+
+ LDAP_ENABLED("ambari.ldap.authentication.enabled"),
+ SERVER_HOST("ambari.ldap.connectivity.server.host"),
+ SERVER_PORT("ambari.ldap.connectivity.server.port"),
+ USE_SSL("ambari.ldap.connectivity.use_ssl"),
+
+ TRUST_STORE("ambari.ldap.connectivity.trust_store"),
+ TRUST_STORE_TYPE("ambari.ldap.connectivity.trust_store.type"),
+ TRUST_STORE_PATH("ambari.ldap.connectivity.trust_store.path"),
+ TRUST_STORE_PASSWORD("ambari.ldap.connectivity.trust_store.password"),
+ ANONYMOUS_BIND("ambari.ldap.connectivity.anonymous_bind"),
+
+ BIND_DN("ambari.ldap.connectivity.bind_dn"),
+ BIND_PASSWORD("ambari.ldap.connectivity.bind_password"),
+
+ ATTR_DETECTION("ambari.ldap.attributes.detection"), // manual | auto
+
+ DN_ATTRIBUTE("ambari.ldap.attributes.dn_attr"),
+
+ USER_OBJECT_CLASS("ambari.ldap.attributes.user.object_class"),
+ USER_NAME_ATTRIBUTE("ambari.ldap.attributes.user.name_attr"),
+ USER_GROUP_MEMBER_ATTRIBUTE("ambari.ldap.attributes.user.group_member_attr"),
+ USER_SEARCH_BASE("ambari.ldap.attributes.user.search_base"),
+
+ GROUP_OBJECT_CLASS("ambari.ldap.attributes.group.object_class"),
+ GROUP_NAME_ATTRIBUTE("ambari.ldap.attributes.group.name_attr"),
+ GROUP_MEMBER_ATTRIBUTE("ambari.ldap.attributes.group.member_attr"),
+ GROUP_SEARCH_BASE("ambari.ldap.attributes.group.search_base"),
+
+ USER_SEARCH_FILTER("ambari.ldap.advanced.user_search_filter"),
+ USER_MEMBER_REPLACE_PATTERN("ambari.ldap.advanced.user_member_replace_pattern"),
+ USER_MEMBER_FILTER("ambari.ldap.advanced.user_member_filter"),
+
+ GROUP_SEARCH_FILTER("ambari.ldap.advanced.group_search_filter"),
+ GROUP_MEMBER_REPLACE_PATTERN("ambari.ldap.advanced.group_member_replace_pattern"),
+ GROUP_MEMBER_FILTER("ambari.ldap.advanced.group_member_filter"),
+
+ FORCE_LOWERCASE_USERNAMES("ambari.ldap.advanced.force_lowercase_usernames"),
+ REFERRAL_HANDLING("ambari.ldap.advanced.referrals"), // folow
+ PAGINATION_ENABLED("ambari.ldap.advanced.pagination_enabled"); // true | false
+
+ private String propertyName;
+
+ AmbariLdapConfigKeys(String propName) {
+ this.propertyName = propName;
+ }
+
+ public String key() {
+ return this.propertyName;
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/b8128f09/ambari-server/src/main/java/org/apache/ambari/server/ldap/domain/AmbariLdapConfiguration.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/domain/AmbariLdapConfiguration.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/domain/AmbariLdapConfiguration.java
index 072393a..d071ebe 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/domain/AmbariLdapConfiguration.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/domain/AmbariLdapConfiguration.java
@@ -18,9 +18,7 @@ package org.apache.ambari.server.ldap.domain;
import java.util.Map;
import javax.inject.Inject;
-import javax.inject.Singleton;
-import org.apache.ambari.server.ldap.service.AmbariLdapConfigKeys;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -29,7 +27,6 @@ import com.google.inject.assistedinject.Assisted;
/**
* This class is an immutable representation of all the LDAP related configurationMap entries.
*/
-@Singleton
public class AmbariLdapConfiguration {
private static final Logger LOGGER = LoggerFactory.getLogger(AmbariLdapConfiguration.class);
http://git-wip-us.apache.org/repos/asf/ambari/blob/b8128f09/ambari-server/src/main/java/org/apache/ambari/server/ldap/domain/LdapConfigurationFactory.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/domain/LdapConfigurationFactory.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/domain/LdapConfigurationFactory.java
index f9a74da..bf8f825 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/domain/LdapConfigurationFactory.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/domain/LdapConfigurationFactory.java
@@ -18,7 +18,7 @@ import java.util.Map;
/**
* Factory interface for AmbariLdapConfiguration instances.
- * It's registered as a factory in the GUICE context ( so no implementations required)
+ * It's registered as a factory in the GUICE context (so no implementations required)
*
* To be extended with other factory methods upon needs.
*/
http://git-wip-us.apache.org/repos/asf/ambari/blob/b8128f09/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapConfigKeys.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapConfigKeys.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapConfigKeys.java
deleted file mode 100644
index 9cf4e56..0000000
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/AmbariLdapConfigKeys.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.ambari.server.ldap.service;
-
-/**
- * Constants representing supported LDAP related property names
- * // todo extend this with validation information, description, defaults maybe
- */
-public enum AmbariLdapConfigKeys {
-
- LDAP_ENABLED("ambari.ldap.authentication.enabled"),
- SERVER_HOST("ambari.ldap.connectivity.server.host"),
- SERVER_PORT("ambari.ldap.connectivity.server.port"),
- USE_SSL("ambari.ldap.connectivity.use_ssl"),
-
- TRUST_STORE("ambari.ldap.connectivity.trust_store"),
- TRUST_STORE_TYPE("ambari.ldap.connectivity.trust_store.type"),
- TRUST_STORE_PATH("ambari.ldap.connectivity.trust_store.path"),
- TRUST_STORE_PASSWORD("ambari.ldap.connectivity.trust_store.password"),
- ANONYMOUS_BIND("ambari.ldap.connectivity.anonymous_bind"),
-
- BIND_DN("ambari.ldap.connectivity.bind_dn"),
- BIND_PASSWORD("ambari.ldap.connectivity.bind_password"),
-
- ATTR_DETECTION("ambari.ldap.attributes.detection"), // manual | auto
-
- DN_ATTRIBUTE("ambari.ldap.attributes.dn_attr"),
-
- USER_OBJECT_CLASS("ambari.ldap.attributes.user.object_class"),
- USER_NAME_ATTRIBUTE("ambari.ldap.attributes.user.name_attr"),
- USER_GROUP_MEMBER_ATTRIBUTE("ambari.ldap.attributes.user.group_member_attr"),
- USER_SEARCH_BASE("ambari.ldap.attributes.user.search_base"),
-
- GROUP_OBJECT_CLASS("ambari.ldap.attributes.group.object_class"),
- GROUP_NAME_ATTRIBUTE("ambari.ldap.attributes.group.name_attr"),
- GROUP_MEMBER_ATTRIBUTE("ambari.ldap.attributes.group.member_attr"),
- GROUP_SEARCH_BASE("ambari.ldap.attributes.group.search_base"),
-
- USER_SEARCH_FILTER("ambari.ldap.advanced.user_search_filter"),
- USER_MEMBER_REPLACE_PATTERN("ambari.ldap.advanced.user_member_replace_pattern"),
- USER_MEMBER_FILTER("ambari.ldap.advanced.user_member_filter"),
-
- GROUP_SEARCH_FILTER("ambari.ldap.advanced.group_search_filter"),
- GROUP_MEMBER_REPLACE_PATTERN("ambari.ldap.advanced.group_member_replace_pattern"),
- GROUP_MEMBER_FILTER("ambari.ldap.advanced.group_member_filter"),
-
- FORCE_LOWERCASE_USERNAMES("ambari.ldap.advanced.force_lowercase_usernames"),
- REFERRAL_HANDLING("ambari.ldap.advanced.referrals"), // folow
- PAGINATION_ENABLED("ambari.ldap.advanced.pagination_enabled"); // true | false
-
- private String propertyName;
-
- AmbariLdapConfigKeys(String propName) {
- this.propertyName = propName;
- }
-
- public String key() {
- return this.propertyName;
- }
-}
http://git-wip-us.apache.org/repos/asf/ambari/blob/b8128f09/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionService.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionService.java b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionService.java
index ed24015..cddb952 100644
--- a/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionService.java
+++ b/ambari-server/src/main/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionService.java
@@ -17,8 +17,8 @@ package org.apache.ambari.server.ldap.service.ads;
import javax.inject.Inject;
import javax.inject.Singleton;
+import org.apache.ambari.server.ldap.domain.AmbariLdapConfigKeys;
import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
-import org.apache.ambari.server.ldap.service.AmbariLdapConfigKeys;
import org.apache.ambari.server.ldap.service.AmbariLdapException;
import org.apache.ambari.server.ldap.service.LdapAttributeDetectionService;
import org.apache.ambari.server.ldap.service.ads.detectors.GroupMemberAttrDetector;
http://git-wip-us.apache.org/repos/asf/ambari/blob/b8128f09/ambari-server/src/test/java/org/apache/ambari/server/ldap/domain/AmbariLdapConfigurationTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/domain/AmbariLdapConfigurationTest.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/domain/AmbariLdapConfigurationTest.java
new file mode 100644
index 0000000..0d02a0e
--- /dev/null
+++ b/ambari-server/src/test/java/org/apache/ambari/server/ldap/domain/AmbariLdapConfigurationTest.java
@@ -0,0 +1,19 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.domain;
+
+public class AmbariLdapConfigurationTest {
+
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/ambari/blob/b8128f09/ambari-server/src/test/java/org/apache/ambari/server/ldap/domain/TestAmbariLdapConfigurationFactory.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/domain/TestAmbariLdapConfigurationFactory.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/domain/TestAmbariLdapConfigurationFactory.java
new file mode 100644
index 0000000..ec86568
--- /dev/null
+++ b/ambari-server/src/test/java/org/apache/ambari/server/ldap/domain/TestAmbariLdapConfigurationFactory.java
@@ -0,0 +1,29 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.ambari.server.ldap.domain;
+
+
+import java.util.Map;
+
+/**
+ * Implementation used for testing purposes only!
+ */
+public class TestAmbariLdapConfigurationFactory implements LdapConfigurationFactory {
+
+ @Override
+ public AmbariLdapConfiguration createLdapConfiguration(Map<String, Object> configuration) {
+ return new AmbariLdapConfiguration(configuration);
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/b8128f09/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionServiceTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionServiceTest.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionServiceTest.java
index 2920588..878d1f0 100644
--- a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionServiceTest.java
+++ b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapAttributeDetectionServiceTest.java
@@ -17,8 +17,9 @@ package org.apache.ambari.server.ldap.service.ads;
import java.util.Map;
+import org.apache.ambari.server.ldap.domain.AmbariLdapConfigKeys;
import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
-import org.apache.ambari.server.ldap.service.AmbariLdapConfigKeys;
+import org.apache.ambari.server.ldap.domain.TestAmbariLdapConfigurationFactory;
import org.apache.ambari.server.ldap.service.LdapConnectionService;
import org.apache.directory.api.ldap.model.constants.SchemaConstants;
import org.apache.directory.ldap.client.api.LdapConnection;
@@ -43,6 +44,8 @@ public class DefaultLdapAttributeDetectionServiceTest {
public EasyMockRule mocks = new EasyMockRule(this);
private AmbariLdapConfiguration testLdapConfiguration;
+ private TestAmbariLdapConfigurationFactory ldapConfigurationFactory = new TestAmbariLdapConfigurationFactory();
+
private LdapConnection connection;
@TestSubject
@@ -53,7 +56,7 @@ public class DefaultLdapAttributeDetectionServiceTest {
Map<String, Object> initialProps = Maps.newHashMap();
initialProps.put(AmbariLdapConfigKeys.BIND_DN.key(), "");
- testLdapConfiguration = new AmbariLdapConfiguration(initialProps);
+ testLdapConfiguration = ldapConfigurationFactory.createLdapConfiguration(initialProps);
}
@Test
@@ -74,7 +77,7 @@ public class DefaultLdapAttributeDetectionServiceTest {
@Test
public void functionalTest() throws Exception {
// GIVEN
- AmbariLdapConfiguration ambariLdapConfiguration = new AmbariLdapConfiguration(getTestPropertiesMap());
+ AmbariLdapConfiguration ambariLdapConfiguration = ldapConfigurationFactory.createLdapConfiguration(getTestPropertiesMap());
LdapConnectionService connectionService = new DefaultLdapConnectionService();
LdapConnection ldapConnection = connectionService.createLdapConnection(ambariLdapConfiguration);
http://git-wip-us.apache.org/repos/asf/ambari/blob/b8128f09/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java
----------------------------------------------------------------------
diff --git a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java
index 449d003..2844054 100644
--- a/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java
+++ b/ambari-server/src/test/java/org/apache/ambari/server/ldap/service/ads/DefaultLdapConfigurationServiceTest.java
@@ -18,8 +18,9 @@ import static org.junit.Assert.assertNotNull;
import java.util.Map;
+import org.apache.ambari.server.ldap.domain.AmbariLdapConfigKeys;
import org.apache.ambari.server.ldap.domain.AmbariLdapConfiguration;
-import org.apache.ambari.server.ldap.service.AmbariLdapConfigKeys;
+import org.apache.ambari.server.ldap.domain.TestAmbariLdapConfigurationFactory;
import org.apache.ambari.server.ldap.service.LdapConfigurationService;
import org.apache.ambari.server.ldap.service.LdapConnectionService;
import org.apache.directory.api.ldap.model.constants.SchemaConstants;
@@ -40,6 +41,8 @@ public class DefaultLdapConfigurationServiceTest {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultLdapConfigurationService.class);
private static final String TEST_USER = "einstein";
+ private TestAmbariLdapConfigurationFactory ldapConfigurationFactory = new TestAmbariLdapConfigurationFactory();
+
LdapConfigurationService ldapConfigurationService = new DefaultLdapConfigurationService();
@@ -85,7 +88,7 @@ public class DefaultLdapConfigurationServiceTest {
ldapPropsMap.put(AmbariLdapConfigKeys.USER_SEARCH_BASE.key(), "dc=example,dc=com");
- AmbariLdapConfiguration ambariLdapConfiguration = new AmbariLdapConfiguration(ldapPropsMap);
+ AmbariLdapConfiguration ambariLdapConfiguration = ldapConfigurationFactory.createLdapConfiguration(ldapPropsMap);
LdapConnectionService connectionService = new DefaultLdapConnectionService();
LdapConnection ldapConnection = connectionService.createLdapConnection(ambariLdapConfiguration);
@@ -107,10 +110,20 @@ public class DefaultLdapConfigurationServiceTest {
ldapPropsMap.put(AmbariLdapConfigKeys.USER_SEARCH_BASE.key(), "dc=example,dc=com");
- AmbariLdapConfiguration ambariLdapConfiguration = new AmbariLdapConfiguration(ldapPropsMap);
+ AmbariLdapConfiguration ambariLdapConfiguration = ldapConfigurationFactory.createLdapConfiguration(ldapPropsMap);
LdapConnectionService connectionService = new DefaultLdapConnectionService();
LdapConnection ldapConnection = connectionService.createLdapConnection(ambariLdapConfiguration);
ldapConfigurationService.checkGroupAttributes(ldapConnection, "uid=einstein,dc=example,dc=com", ambariLdapConfiguration);
}
+
+ @Test
+ public void testListSupportedProperties(){
+ StringBuilder sb = new StringBuilder().append(System.lineSeparator());
+ for (AmbariLdapConfigKeys configKey : AmbariLdapConfigKeys.values()) {
+ sb.append(configKey.key()).append(System.lineSeparator());
+ }
+ LOGGER.info(sb.toString());
+
+ }
}
\ No newline at end of file