Example usage for javax.management.remote JMXPrincipal JMXPrincipal

List of usage examples for javax.management.remote JMXPrincipal JMXPrincipal

Introduction

In this page you can find the example usage for javax.management.remote JMXPrincipal JMXPrincipal.

Prototype

public JMXPrincipal(String name) 

Source Link

Document

Creates a JMXPrincipal for a given identity.

Usage

From source file:gateway.test.AlertTriggerTests.java

/**
 * Initialize mock objects.//ww w  .  j  a  va 2 s. c o  m
 */
@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
    MockitoAnnotations.initMocks(gatewayUtil);

    // Mock a user
    user = new JMXPrincipal("Test User");
}

From source file:eu.openanalytics.rsb.security.JmxSecurityAuthenticator.java

@Override
public Subject authenticate(final Object credentials) {
    try {/*from  www .  j a  va  2s  .c  om*/
        final String[] info = (String[]) credentials;

        final Authentication authentication = authenticationManager
                .authenticate(new UsernamePasswordAuthenticationToken(info[0], info[1]));

        final User authenticatedUser = (User) authentication.getPrincipal();

        if ((isRsbAdminPrincipal(authenticatedUser)) || (isRsbAdminRole(authenticatedUser))) {
            final Subject s = new Subject();
            s.getPrincipals().add(new JMXPrincipal(authentication.getName()));
            return s;
        } else {
            throw new SecurityException("Authenticated user " + authenticatedUser + " is not an RSB admin");
        }
    } catch (final Exception e) {
        LOGGER.error("Error when trying to authenticate JMX credentials of type: " + credentials.getClass(), e);

        throw new SecurityException(e);
    }
}

From source file:gateway.test.UtilTests.java

/**
 * Tests getting the username from the Principal.
 *//*from w  ww.  j  a v a  2 s.  co m*/
@Test
public void testUserName() {
    assertEquals("Test User", gatewayUtil.getPrincipalName(new JMXPrincipal("Test User")));
    assertEquals("UNAUTHENTICATED", gatewayUtil.getPrincipalName(null));
}

From source file:gateway.test.DeploymentTests.java

/**
 * Initialize mock objects./*w w w.j  a  va  2s  .co  m*/
 */
@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
    MockitoAnnotations.initMocks(gatewayUtil);

    // Mock a common error we can use to test
    mockError = new ErrorResponse("Error!", "Test");

    // Mock a user
    user = new JMXPrincipal("Test User");

    // Mock some deployment
    mockDeployment = new Deployment("123456", "654321", "localhost", "8080", "layer",
            "http://localhost:8080/layer?request=GetCapabilities");

    // Mock the Kafka response that Producers will send. This will always
    // return a Future that completes immediately and simply returns true.
    when(producer.send(isA(ProducerRecord.class))).thenAnswer(new Answer<Future<Boolean>>() {
        @Override
        public Future<Boolean> answer(InvocationOnMock invocation) throws Throwable {
            Future<Boolean> future = mock(FutureTask.class);
            when(future.isDone()).thenReturn(true);
            when(future.get()).thenReturn(true);
            return future;
        }
    });

    when(gatewayUtil.getErrorResponse(anyString())).thenCallRealMethod();
}

From source file:gateway.test.ServiceTests.java

/**
 * Initialize mock objects.//from   ww w.ja  v a 2s  .  c o  m
 */
@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
    MockitoAnnotations.initMocks(gatewayUtil);

    // Mock a common error we can use to test
    mockError = new ErrorResponse("Error!", "Test");

    // Mock a Service to use
    mockService = new Service();
    mockService.setServiceId("123456");
    mockService.setUrl("service.com");
    mockService.setResourceMetadata(new ResourceMetadata());
    mockService.getResourceMetadata().setName("Test");

    // Mock a user
    user = new JMXPrincipal("Test User");

    // Mock the Kafka response that Producers will send. This will always
    // return a Future that completes immediately and simply returns true.
    when(producer.send(isA(ProducerRecord.class))).thenAnswer(new Answer<Future<Boolean>>() {
        @Override
        public Future<Boolean> answer(InvocationOnMock invocation) throws Throwable {
            Future<Boolean> future = mock(FutureTask.class);
            when(future.isDone()).thenReturn(true);
            when(future.get()).thenReturn(true);
            return future;
        }
    });

    when(gatewayUtil.getErrorResponse(anyString())).thenCallRealMethod();
}

From source file:gateway.test.JobTests.java

/**
 * Initialize mock objects./*from   w  w w .j a  v  a2 s  .  c o  m*/
 */
@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
    MockitoAnnotations.initMocks(gatewayUtil);

    // Mock a common error we can use to test
    mockError = new ErrorResponse("Job Not Found", "Gateway");
    mockJobError = new ResponseEntity<PiazzaResponse>(new JobErrorResponse("1234", "Job Not Found", "Gateway"),
            HttpStatus.NOT_FOUND);

    // Mock a Job
    mockJob = new Job();
    mockJob.setJobId("123456");
    mockJob.jobType = new RepeatJob("654321");
    mockJob.progress = new JobProgress(50);
    mockJob.createdBy = "Test User 2";
    mockJob.status = StatusUpdate.STATUS_RUNNING;

    // Mock a user
    user = new JMXPrincipal("Test User");

    // Mock the Kafka response that Producers will send. This will always
    // return a Future that completes immediately and simply returns true.
    when(producer.send(isA(ProducerRecord.class))).thenAnswer(new Answer<Future<Boolean>>() {
        @Override
        public Future<Boolean> answer(InvocationOnMock invocation) throws Throwable {
            Future<Boolean> future = mock(FutureTask.class);
            when(future.isDone()).thenReturn(true);
            when(future.get()).thenReturn(true);
            return future;
        }
    });

    when(gatewayUtil.getErrorResponse(anyString())).thenCallRealMethod();
}

From source file:gateway.test.DataTests.java

/**
 * Initialize mock objects.//from w  ww. j  a v a2s  .  co  m
 */
@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
    MockitoAnnotations.initMocks(gatewayUtil);

    // Mock a common error we can use to test
    mockError = new ErrorResponse("Error!", "Test");

    // Mock some Data that we can use in our test cases.
    mockData = new DataResource();
    mockData.dataId = "DataID";
    mockData.dataType = new TextDataType();
    ((TextDataType) mockData.dataType).content = "MockData";
    mockData.metadata = new ResourceMetadata();
    mockData.metadata.setName("Test Data");

    // Mock a user
    user = new JMXPrincipal("Test User");

    // Mock the Kafka response that Producers will send. This will always
    // return a Future that completes immediately and simply returns true.
    when(producer.send(isA(ProducerRecord.class))).thenAnswer(new Answer<Future<Boolean>>() {
        @Override
        public Future<Boolean> answer(InvocationOnMock invocation) throws Throwable {
            Future<Boolean> future = mock(FutureTask.class);
            when(future.isDone()).thenReturn(true);
            when(future.get()).thenReturn(true);
            return future;
        }
    });

    when(gatewayUtil.getErrorResponse(anyString())).thenCallRealMethod();
}

From source file:org.mule.management.support.SimplePasswordJmxAuthenticator.java

public Subject authenticate(Object authToken) {
    if (authToken == null) {
        throw new SecurityException("No authentication token available");
    }//from  www  .  j a  v  a 2 s  . c  o m
    if (!(authToken instanceof String[]) || ((String[]) authToken).length != 2) {
        throw new SecurityException("Unsupported credentials format");
    }

    String[] authentication = (String[]) authToken;

    String username = StringUtils.defaultString(authentication[0]);
    String password = StringUtils.defaultString(authentication[1]);

    if (!credentials.containsKey(username)) {
        throw new SecurityException("Unauthenticated user: " + username);
    }

    if (!password.equals(ObjectUtils.toString(credentials.get(username)))) {
        throw new SecurityException("Invalid password");
    }

    Set principals = new HashSet();
    principals.add(new JMXPrincipal(username));
    return new Subject(true, principals, Collections.EMPTY_SET, Collections.EMPTY_SET);
}

From source file:org.mule.module.management.support.SimplePasswordJmxAuthenticator.java

public Subject authenticate(Object authToken) {
    if (authToken == null) {
        throw new SecurityException("No authentication token available");
    }//  w w  w.j  av a  2 s  .co  m
    if (!(authToken instanceof String[]) || ((String[]) authToken).length != 2) {
        throw new SecurityException("Unsupported credentials format");
    }

    String[] authentication = (String[]) authToken;

    String username = StringUtils.defaultString(authentication[0]);
    String password = StringUtils.defaultString(authentication[1]);

    if (!credentials.containsKey(username)) {
        throw new SecurityException("Unauthenticated user: " + username);
    }

    Object pass = credentials.get(username);
    if (!password.equals(pass == null ? "" : pass.toString())) {
        throw new SecurityException("Invalid password");
    }

    Set<Principal> principals = new HashSet<Principal>();
    principals.add(new JMXPrincipal(username));
    return new Subject(true, principals, Collections.EMPTY_SET, Collections.EMPTY_SET);
}

From source file:org.wso2.carbon.core.security.CarbonJMXAuthenticator.java

public Subject authenticate(Object credentials) {
    // Verify that credentials is of type String[].
    ////from w ww.  jav  a 2s  .  c om
    if (!(credentials instanceof String[])) {
        // Special case for null so we get a more informative message
        if (credentials == null) {
            throw new SecurityException("Credentials required");
        }
        throw new SecurityException("Credentials should be String[]");
    }

    // Verify that the array contains username/password
    //
    final String[] aCredentials = (String[]) credentials;
    if (aCredentials.length < 2) {
        throw new SecurityException("Credentials should have at least username & password");
    }

    // Perform authentication
    //
    String userName = aCredentials[0];
    String password = aCredentials[1];

    UserStoreManager authenticator;
    try {
        authenticator = userRealm.getUserStoreManager();
    } catch (UserStoreException e) {
        String msg = "Cannot get authenticator from Realm";
        log.error(msg, e);
        throw new SecurityException(msg, e);
    }

    try {

        // for new cahing, every thread should has its own populated CC. During the deployment time we assume super tenant
        PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
        carbonContext.setTenantDomain(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
        carbonContext.setTenantId(MultitenantConstants.SUPER_TENANT_ID);

        String domainNameFromUserName = extractTenantDomain(userName);
        if (domainNameFromUserName != null
                && domainNameFromUserName.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
            if (log.isDebugEnabled()) {
                log.debug("Authentication Failure..Provided tenant domain name is reserved..");
            }
            throw new SecurityException(
                    "Authentication failed - System error occurred. Tenant domain name is reserved.");
        }
        if (authenticator.authenticate(userName, password)) {

            UserRealmService userRealmService = CarbonCoreDataHolder.getInstance().getRealmService();
            TenantManager tenantManager = userRealmService.getTenantManager();
            String tenantDomain = MultitenantUtils.getTenantDomain(userName);
            int tenantId = tenantManager.getTenantId(tenantDomain);
            carbonContext.setTenantId(tenantId);
            carbonContext.setTenantDomain(tenantDomain);

            audit.info("User " + userName + " successfully authenticated to perform JMX operations.");

            if (authorize(userName)) {

                audit.info("User : " + userName + " successfully authorized to perform JMX operations.");

                return new Subject(true, Collections.singleton(new JMXPrincipal(userName)),
                        Collections.EMPTY_SET, Collections.EMPTY_SET);
            } else {
                throw new SecurityException(
                        "User : " + userName + " not authorized to perform JMX operations.");
            }

        } else {
            throw new SecurityException(
                    "Login failed for user : " + userName + ". Invalid username or password.");
        }
    } catch (SecurityException se) {

        String msg = "Unauthorized access attempt to JMX operation. ";
        audit.warn(msg, se);
        throw new SecurityException(msg, se);

    } catch (Exception e) {

        String msg = "JMX operation failed.";
        log.error(msg, e);
        throw new SecurityException(msg, e);
    }
}