Example usage for org.apache.commons.lang RandomStringUtils randomAlphanumeric

List of usage examples for org.apache.commons.lang RandomStringUtils randomAlphanumeric

Introduction

In this page you can find the example usage for org.apache.commons.lang RandomStringUtils randomAlphanumeric.

Prototype

public static String randomAlphanumeric(int count) 

Source Link

Document

Creates a random string whose length is the number of characters specified.

Characters will be chosen from the set of alpha-numeric characters.

Usage

From source file:com.xtructure.xutil.valid.UTestValidateUtils.java

public void validateStateWithOnePredicateBehavesAsExpected() {
    String objectName = RandomStringUtils.randomAlphanumeric(10);
    boolean valid = validateState(objectName, new Object(), isNotNull());
    if (!valid) {
        throw new AssertionError();
    }//from  w  w w  . j  ava2 s .  c om
    try {
        validateState(objectName, null, isNotNull());
    } catch (IllegalStateException e) {
        if (!String.format("%s (%s): %s", objectName, null, isNotNull()).equals(e.getMessage())) {
            throw new AssertionError();
        }
    }
}

From source file:it.user.RailsExternalAuthenticationTest.java

/**
 * SONAR-1334 (createUsers=false)/*  ww  w.j  a  v  a2s.c o  m*/
 */
@Test
public void shouldNotCreateNewUsers() {
    // Given clean Sonar installation and no users in external system
    setServerProperty(orchestrator, "sonar.authenticator.createUsers", "false");
    // Use a random user name because if we use existing disabled user then it doesn't work because rails doesn't handle this case
    // (it's using User.find_by_login to know if user exists or not
    String username = RandomStringUtils.randomAlphanumeric(20);
    String password = "1234567";
    Map<String, String> users = Maps.newHashMap();

    // When user not exists in external system
    // Then
    assertThat(loginAttempt(username, password)).isEqualTo(NOT_AUTHORIZED);

    // When user created in external system
    users.put(username + ".password", password);
    updateUsersInExtAuth(users);
    // Then
    assertThat(loginAttempt(username, password)).isEqualTo(NOT_AUTHORIZED);
}

From source file:com.evolveum.midpoint.common.policy.ValuePolicyGenerator.java

public static String generate(StringPolicyType policy, int defaultLength, boolean generateMinimalSize,
        OperationResult inputResult) {//  ww  w. j  a va2  s . co m

    if (null == policy) {
        throw new IllegalArgumentException("Provided password policy can not be null.");
    }

    if (null == inputResult) {
        throw new IllegalArgumentException("Provided operation result cannot be null");
    }
    // Define result from generator
    OperationResult generatorResult = new OperationResult(
            "Password generator running policy :" + policy.getDescription());
    inputResult.addSubresult(generatorResult);

    // if (policy.getLimitations() != null &&
    // policy.getLimitations().getMinLength() != null){
    // generateMinimalSize = true;
    // }
    // setup default values where missing
    // PasswordPolicyUtils.normalize(pp);

    // Optimize usage of limits ass hashmap of limitas and key is set of
    // valid chars for each limitation
    HashMap<StringLimitType, ArrayList<String>> lims = new HashMap<StringLimitType, ArrayList<String>>();
    for (StringLimitType l : policy.getLimitations().getLimit()) {
        if (null != l.getCharacterClass().getValue()) {
            lims.put(l, StringPolicyUtils.stringTokenizer(l.getCharacterClass().getValue()));
        } else {
            lims.put(l, StringPolicyUtils.stringTokenizer(StringPolicyUtils
                    .collectCharacterClass(policy.getCharacterClass(), l.getCharacterClass().getRef())));
        }
    }

    // Get global limitations
    int minLen = policy.getLimitations().getMinLength() == null ? 0
            : policy.getLimitations().getMinLength().intValue();
    if (minLen != 0 && minLen > defaultLength) {
        defaultLength = minLen;
    }
    int maxLen = (policy.getLimitations().getMaxLength() == null ? 0
            : policy.getLimitations().getMaxLength().intValue());
    int unique = policy.getLimitations().getMinUniqueChars() == null ? minLen
            : policy.getLimitations().getMinUniqueChars().intValue();

    // test correctness of definition
    if (unique > minLen) {
        minLen = unique;
        OperationResult reportBug = new OperationResult("Global limitation check");
        reportBug.recordWarning(
                "There is more required uniq characters then definied minimum. Raise minimum to number of required uniq chars.");
    }

    if (minLen == 0 && maxLen == 0) {
        minLen = defaultLength;
        maxLen = defaultLength;
        generateMinimalSize = true;
    }

    if (maxLen == 0) {
        if (minLen > defaultLength) {
            maxLen = minLen;
        } else {
            maxLen = defaultLength;
        }
    }

    // Initialize generator
    StringBuilder password = new StringBuilder();

    /* **********************************
     * Try to find best characters to be first in password
     */
    HashMap<StringLimitType, ArrayList<String>> mustBeFirst = new HashMap<StringLimitType, ArrayList<String>>();
    for (StringLimitType l : lims.keySet()) {
        if (l.isMustBeFirst() != null && l.isMustBeFirst()) {
            mustBeFirst.put(l, lims.get(l));
        }
    }

    // If any limitation was found to be first
    if (!mustBeFirst.isEmpty()) {
        HashMap<Integer, ArrayList<String>> posibleFirstChars = cardinalityCounter(mustBeFirst, null, false,
                false, generatorResult);
        int intersectionCardinality = mustBeFirst.keySet().size();
        ArrayList<String> intersectionCharacters = posibleFirstChars.get(intersectionCardinality);
        // If no intersection was found then raise error
        if (null == intersectionCharacters || intersectionCharacters.size() == 0) {
            generatorResult
                    .recordFatalError("No intersection for required first character sets in password policy:"
                            + policy.getDescription());
            // Log error
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error(
                        "Unable to generate password: No intersection for required first character sets in password policy: ["
                                + policy.getDescription()
                                + "] following character limitation and sets are used:");
                for (StringLimitType l : mustBeFirst.keySet()) {
                    StrBuilder tmp = new StrBuilder();
                    tmp.appendSeparator(", ");
                    tmp.appendAll(mustBeFirst.get(l));
                    LOGGER.error("L:" + l.getDescription() + " -> [" + tmp + "]");
                }
            }
            // No more processing unrecoverable conflict
            return null; // EXIT
        } else {
            if (LOGGER.isDebugEnabled()) {
                StrBuilder tmp = new StrBuilder();
                tmp.appendSeparator(", ");
                tmp.appendAll(intersectionCharacters);
                LOGGER.trace("Generate first character intersection items [" + tmp + "] into password.");
            }
            // Generate random char into password from intersection
            password.append(intersectionCharacters.get(rand.nextInt(intersectionCharacters.size())));
        }
    }

    /* **************************************
     * Generate rest to fulfill minimal criteria
     */

    boolean uniquenessReached = false;

    // Count cardinality of elements
    HashMap<Integer, ArrayList<String>> chars;
    for (int i = 0; i < minLen; i++) {

        // Check if still unique chars are needed
        if (password.length() >= unique) {
            uniquenessReached = true;
        }
        // Find all usable characters
        chars = cardinalityCounter(lims, StringPolicyUtils.stringTokenizer(password.toString()), false,
                uniquenessReached, generatorResult);
        // If something goes badly then go out
        if (null == chars) {
            return null;
        }

        if (chars.isEmpty()) {
            LOGGER.trace("Minimal criterias was met. No more characters");
            break;
        }
        // Find lowest possible cardinality and then generate char
        for (int card = 1; card < lims.keySet().size(); card++) {
            if (chars.containsKey(card)) {
                ArrayList<String> validChars = chars.get(card);
                password.append(validChars.get(rand.nextInt(validChars.size())));
                //               LOGGER.trace(password.toString());
                break;
            }
        }
    }

    // test if maximum is not exceeded
    if (password.length() > maxLen) {
        generatorResult
                .recordFatalError("Unable to meet minimal criteria and not exceed maximxal size of password.");
        return null;
    }

    /* ***************************************
     * Generate chars to not exceed maximal
     */

    for (int i = 0; i < minLen; i++) {
        // test if max is reached
        if (password.length() == maxLen) {
            // no more characters maximal size is reached
            break;
        }

        if (password.length() >= minLen && generateMinimalSize) {
            // no more characters are needed
            break;
        }

        // Check if still unique chars are needed
        if (password.length() >= unique) {
            uniquenessReached = true;
        }
        // find all usable characters
        chars = cardinalityCounter(lims, StringPolicyUtils.stringTokenizer(password.toString()), true,
                uniquenessReached, generatorResult);

        // If something goes badly then go out
        if (null == chars) {
            // we hope this never happend.
            generatorResult
                    .recordFatalError("No valid characters to generate, but no all limitation are reached");
            return null;
        }

        // if selection is empty then no more characters and we can close
        // our work
        if (chars.isEmpty()) {
            if (i == 0) {
                password.append(RandomStringUtils.randomAlphanumeric(minLen));

            }
            break;
            //            if (!StringUtils.isBlank(password.toString()) && password.length() >= minLen) {
            //               break;
            //            }
            // check uf this is a firs cycle and if we need to user some
            // default (alphanum) character class.

        }

        // Find lowest possible cardinality and then generate char
        for (int card = 1; card <= lims.keySet().size(); card++) {
            if (chars.containsKey(card)) {
                ArrayList<String> validChars = chars.get(card);
                password.append(validChars.get(rand.nextInt(validChars.size())));
                //               LOGGER.trace(password.toString());
                break;
            }
        }
    }

    if (password.length() < minLen) {
        generatorResult.recordFatalError(
                "Unable to generate password and meet minimal size of password. Password lenght: "
                        + password.length() + ", required: " + minLen);
        LOGGER.trace(
                "Unable to generate password and meet minimal size of password. Password lenght: {}, required: {}",
                password.length(), minLen);
        return null;
    }

    generatorResult.recordSuccess();

    // Shuffle output to solve pattern like output
    StrBuilder sb = new StrBuilder(password.substring(0, 1));
    ArrayList<String> shuffleBuffer = StringPolicyUtils.stringTokenizer(password.substring(1));
    Collections.shuffle(shuffleBuffer);
    sb.appendAll(shuffleBuffer);

    return sb.toString();
}

From source file:io.kamax.mxisd.invitation.InvitationManager.java

public synchronized IThreePidInviteReply storeInvite(IThreePidInvite invitation) { // TODO better sync
    if (!notifMgr.isMediumSupported(invitation.getMedium())) {
        throw new BadRequestException("Medium type " + invitation.getMedium() + " is not supported");
    }//from  w  ww .ja va 2  s. c o  m

    String invId = getId(invitation);
    log.info("Handling invite for {}:{} from {} in room {}", invitation.getMedium(), invitation.getAddress(),
            invitation.getSender(), invitation.getRoomId());
    IThreePidInviteReply reply = invitations.get(invId);
    if (reply != null) {
        log.info("Invite is already pending for {}:{}, returning data", invitation.getMedium(),
                invitation.getAddress());
        if (!StringUtils.equals(invitation.getRoomId(), reply.getInvite().getRoomId())) {
            log.info("Sending new notification as new invite room {} is different from the original {}",
                    invitation.getRoomId(), reply.getInvite().getRoomId());
            notifMgr.sendForInvite(new ThreePidInviteReply(reply.getId(), invitation, reply.getToken(),
                    reply.getDisplayName()));
        } else {
            // FIXME we should check attempt and send if bigger
        }
        return reply;
    }

    Optional<SingleLookupReply> result = lookup3pid(invitation.getMedium(), invitation.getAddress());
    if (result.isPresent()) {
        log.info("Mapping for {}:{} already exists, refusing to store invite", invitation.getMedium(),
                invitation.getAddress());
        throw new MappingAlreadyExistsException();
    }

    String token = RandomStringUtils.randomAlphanumeric(64);
    String displayName = invitation.getAddress().substring(0, 3) + "...";

    reply = new ThreePidInviteReply(invId, invitation, token, displayName);

    log.info("Performing invite to {}:{}", invitation.getMedium(), invitation.getAddress());
    notifMgr.sendForInvite(reply);

    log.info("Storing invite under ID {}", invId);
    storage.insertInvite(reply);
    invitations.put(invId, reply);
    log.info("A new invite has been created for {}:{} on HS {}", invitation.getMedium(),
            invitation.getAddress(), invitation.getSender().getDomain());

    return reply;
}

From source file:fr.fg.server.data.Player.java

public void generateSecurityKey() {
    setSecurityKey(RandomStringUtils.randomAlphanumeric(20));
}

From source file:com.xtructure.xutil.valid.UTestValidateUtils.java

public void validateStateWithMultiplePredicatesBehavesAsExpected() {
    String objectName = RandomStringUtils.randomAlphanumeric(10);
    boolean valid = validateState(objectName, new Object(), isNotNull(), isNotNull());
    if (!valid) {
        throw new AssertionError();
    }/*from  ww  w. java2s  .  com*/
    try {
        validateState(objectName, null, isNotNull(), isNotNull());
    } catch (IllegalStateException e) {
        if (!String.format("%s (%s): %s", objectName, null, isNotNull()).equals(e.getMessage())) {
            throw new AssertionError();
        }
    }
}

From source file:com.google.cloud.bigtable.hbase.TestFilters.java

/**
 * Requirement 9.1/*  ww  w.j ava2  s . com*/
 * Requirement 9.2
 */
@Test
@Category(KnownGap.class)
public void testColumnFilterScan() throws Exception {
    // Initialize data
    int numRows = 5;
    int numColumns = 20;
    int numColumnsToFilter = 8;
    int offset = 5;
    Table table = getTable();
    String rowPrefix = "testColumnFilterScan" + RandomStringUtils.randomAlphanumeric(5);
    String endRowKey = "testColumnFilterScan" + "zzzzzzz";
    byte[][] rowKeys = dataHelper.randomData(rowPrefix + "-", numRows);
    byte[][] quals = dataHelper.randomData("testqual-", numColumns);
    byte[][] values = dataHelper.randomData("testvalue-", numColumns);
    for (int i = 0; i < numRows; ++i) {
        Put put = new Put(rowKeys[i]);
        for (int j = 0; j < numColumns; ++j) {
            put.addColumn(COLUMN_FAMILY, quals[j], values[j]);
        }
        table.put(put);
    }

    // Test ColumnCountGetFilter on scan.  ColumnCountGetFilter is not made for scans, and once
    // the column limit has been met, Filter#filterAllRemaining() returns true.
    Filter filter = new ColumnCountGetFilter(numColumnsToFilter);
    Scan scan = new Scan(Bytes.toBytes(rowPrefix), Bytes.toBytes(endRowKey)).setFilter(filter);
    ResultScanner scanner = table.getScanner(scan);
    Result[] results = scanner.next(1000);
    Assert.assertEquals(1, results.length);

    // Test ColumnPaginationFilter on scan
    filter = new ColumnPaginationFilter(numColumnsToFilter, offset);
    scan = new Scan(Bytes.toBytes(rowPrefix), Bytes.toBytes(endRowKey)).setFilter(filter);
    scanner = table.getScanner(scan);
    results = scanner.next(1000);
    Assert.assertEquals(numRows, results.length);
    for (int i = 0; i < numRows; ++i) {
        Result result = results[i];
        Assert.assertEquals("Should have filtered to N columns", numColumnsToFilter, result.size());
    }

    table.close();
}

From source file:com.xtructure.xutil.valid.UTestValidateUtils.java

public void validateStateWithValidationStrategyBehavesAsExpected() {
    String objectName = RandomStringUtils.randomAlphanumeric(10);
    StateValidationStrategy<Object> validationStrategy = new StateValidationStrategy<Object>(isNotNull());
    boolean valid = validateState(objectName, new Object(), validationStrategy);
    if (!valid) {
        throw new AssertionError();
    }//  w  w w .j av a  2  s.  com
    try {
        validateState(objectName, null, validationStrategy);
    } catch (IllegalStateException e) {
        if (!String.format("%s (%s): %s", objectName, null, isNotNull()).equals(e.getMessage())) {
            throw new AssertionError();
        }
    }
}

From source file:fr.xebia.cloud.amazon.aws.iam.AmazonAwsIamAccountCreator.java

/**
 * <p>/*from w  ww  . j  a  v a2 s  .  c om*/
 * Create an Amazon IAM account and send the details by email.
 * </p>
 * <p>
 * Created elements:
 * </p>
 * <ul>
 * <li>password to login to the management console if none exists,</li>
 * <li>accesskey if none is active,</li>
 * <li></li>
 * </ul>
 *
 * @param userName valid email used as userName of the created account.
 */
public void createUser(@Nonnull final String userName, GetGroupResult groupDescriptor, String keyPairName)
        throws Exception {
    Preconditions.checkNotNull(userName, "Given userName can NOT be null");
    logger.info("Process user {}", userName);

    List<String> userAccountChanges = Lists.newArrayList();

    Map<String, String> templatesParams = Maps.newHashMap();
    templatesParams.put("awsCredentialsHome", "~/.aws");
    templatesParams.put("awsCommandLinesHome", "/opt/amazon-aws");

    User user;
    try {
        user = iam.getUser(new GetUserRequest().withUserName(userName)).getUser();
    } catch (NoSuchEntityException e) {
        logger.debug("User {} does not exist, create it", userName, e);
        user = iam.createUser(new CreateUserRequest(userName)).getUser();
        userAccountChanges.add("Create user");
    }

    List<BodyPart> attachments = Lists.newArrayList();

    // AWS WEB MANAGEMENT CONSOLE LOGIN & PASSWORD
    try {
        LoginProfile loginProfile = iam.getLoginProfile(new GetLoginProfileRequest(user.getUserName()))
                .getLoginProfile();
        templatesParams.put("loginUserName", loginProfile.getUserName());
        templatesParams.put("loginPassword", "#your password has already been generated and sent to you#");

        logger.info("Login profile already exists {}", loginProfile);
    } catch (NoSuchEntityException e) {
        // manually add a number to ensure amazon policy is respected
        String password = RandomStringUtils.randomAlphanumeric(10) + random.nextInt(10);
        LoginProfile loginProfile = iam
                .createLoginProfile(new CreateLoginProfileRequest(user.getUserName(), password))
                .getLoginProfile();
        userAccountChanges.add("Create user.login");
        templatesParams.put("loginUserName", loginProfile.getUserName());
        templatesParams.put("loginPassword", password);
    }

    // ADD USER TO GROUP
    Group group = groupDescriptor.getGroup();
    List<User> groupMembers = groupDescriptor.getUsers();

    boolean isUserInGroup = Iterables.any(groupMembers, new Predicate<User>() {
        public boolean apply(User groupMember) {
            return userName.equals(groupMember.getUserName());
        }

        ;
    });

    if (!isUserInGroup) {
        logger.debug("Add user {} to group {}", user, group);
        iam.addUserToGroup(new AddUserToGroupRequest(group.getGroupName(), user.getUserName()));
        groupMembers.add(user);
        userAccountChanges.add("Add user to group");
    }

    // ACCESS KEY
    boolean activeAccessKeyExists = false;
    ListAccessKeysResult listAccessKeysResult = iam
            .listAccessKeys(new ListAccessKeysRequest().withUserName(user.getUserName()));
    for (AccessKeyMetadata accessKeyMetadata : listAccessKeysResult.getAccessKeyMetadata()) {
        StatusType status = StatusType.fromValue(accessKeyMetadata.getStatus());
        if (StatusType.Active.equals(status)) {
            logger.info("Access key {} ({}) is already active, don't create another one.",
                    accessKeyMetadata.getAccessKeyId(), accessKeyMetadata.getCreateDate());
            activeAccessKeyExists = true;
            templatesParams.put("accessKeyId", accessKeyMetadata.getAccessKeyId());
            templatesParams.put("accessKeySecretId",
                    "#accessKey has already been generated and the secretId has been sent to you#");

            break;
        }
    }

    if (!activeAccessKeyExists) {
        AccessKey accessKey = iam.createAccessKey(new CreateAccessKeyRequest().withUserName(user.getUserName()))
                .getAccessKey();
        userAccountChanges.add("Create user.accessKey");
        logger.debug("Created access key {}", accessKey);
        templatesParams.put("accessKeyId", accessKey.getAccessKeyId());
        templatesParams.put("accessKeySecretId", accessKey.getSecretAccessKey());

        // email attachment: aws-credentials.txt
        {
            BodyPart awsCredentialsBodyPart = new MimeBodyPart();
            awsCredentialsBodyPart.setFileName("aws-credentials.txt");
            templatesParams.put("attachedCredentialsFileName", awsCredentialsBodyPart.getFileName());
            String awsCredentials = FreemarkerUtils.generate(templatesParams,
                    "/fr/xebia/cloud/amazon/aws/iam/aws-credentials.txt.ftl");
            awsCredentialsBodyPart.setContent(awsCredentials, "text/plain");
            attachments.add(awsCredentialsBodyPart);
        }

    }

    // SSH KEY PAIR
    if (keyPairName == null) { // If keyPairName is null, generate it from the username
        if (userName.endsWith("@xebia.fr") || userName.endsWith("@xebia.com")) {
            keyPairName = userName.substring(0, userName.indexOf("@xebia."));
        } else {
            keyPairName = userName.replace("@", "_at_").replace(".", "_dot_").replace("+", "_plus_");
        }
    }

    try {
        List<KeyPairInfo> keyPairInfos = ec2
                .describeKeyPairs(new DescribeKeyPairsRequest().withKeyNames(keyPairName)).getKeyPairs();
        KeyPairInfo keyPairInfo = Iterables.getOnlyElement(keyPairInfos);
        logger.info("SSH key {} already exists. Don't overwrite it.", keyPairInfo.getKeyName());
        templatesParams.put("sshKeyName", keyPairInfo.getKeyName());
        templatesParams.put("sshKeyFingerprint", keyPairInfo.getKeyFingerprint());

        String sshKeyFileName = keyPairName + ".pem";
        URL sshKeyFileURL = Thread.currentThread().getContextClassLoader().getResource(sshKeyFileName);
        if (sshKeyFileURL != null) {
            logger.info("SSH Key file {} found.", sshKeyFileName);

            BodyPart keyPairBodyPart = new MimeBodyPart();
            keyPairBodyPart.setFileName(sshKeyFileName);
            templatesParams.put("attachedSshKeyFileName", keyPairBodyPart.getFileName());
            keyPairBodyPart.setContent(Resources.toString(sshKeyFileURL, Charsets.ISO_8859_1),
                    "application/x-x509-ca-cert");
            attachments.add(keyPairBodyPart);
        } else {
            logger.info("SSH Key file {} NOT found.", sshKeyFileName);
        }

    } catch (AmazonServiceException e) {
        if ("InvalidKeyPair.NotFound".equals(e.getErrorCode())) {
            // ssh key does not exist, create it
            KeyPair keyPair = ec2.createKeyPair(new CreateKeyPairRequest(keyPairName)).getKeyPair();
            userAccountChanges.add("Create ssh key");

            logger.info("Created ssh key {}", keyPair);
            templatesParams.put("sshKeyName", keyPair.getKeyName());
            templatesParams.put("sshKeyFingerprint", keyPair.getKeyFingerprint());

            BodyPart keyPairBodyPart = new MimeBodyPart();
            keyPairBodyPart.setFileName(keyPair.getKeyName() + ".pem");
            templatesParams.put("attachedSshKeyFileName", keyPairBodyPart.getFileName());
            keyPairBodyPart.setContent(keyPair.getKeyMaterial(), "application/x-x509-ca-cert");
            attachments.add(keyPairBodyPart);
        } else {
            throw e;
        }
    }

    // X509 SELF SIGNED CERTIFICATE
    Collection<SigningCertificate> certificates = iam
            .listSigningCertificates(new ListSigningCertificatesRequest().withUserName(userName))
            .getCertificates();
    // filter active certificates
    certificates = Collections2.filter(certificates, new Predicate<SigningCertificate>() {
        @Override
        public boolean apply(SigningCertificate signingCertificate) {
            return StatusType.Active.equals(StatusType.fromValue(signingCertificate.getStatus()));
        }
    });

    if (certificates.isEmpty()) {
        java.security.KeyPair x509KeyPair = keyPairGenerator.generateKeyPair();
        X509Certificate x509Certificate = generateSelfSignedX509Certificate(userName, x509KeyPair);
        String x509CertificatePem = Pems.pem(x509Certificate);

        UploadSigningCertificateResult uploadSigningCertificateResult = iam.uploadSigningCertificate( //
                new UploadSigningCertificateRequest(x509CertificatePem).withUserName(user.getUserName()));
        SigningCertificate signingCertificate = uploadSigningCertificateResult.getCertificate();
        templatesParams.put("x509CertificateId", signingCertificate.getCertificateId());
        userAccountChanges.add("Create x509 certificate");

        logger.info("Created x509 certificate {}", signingCertificate);

        // email attachment: x509 private key
        {
            BodyPart x509PrivateKeyBodyPart = new MimeBodyPart();
            x509PrivateKeyBodyPart.setFileName("pk-" + signingCertificate.getCertificateId() + ".pem");
            templatesParams.put("attachedX509PrivateKeyFileName", x509PrivateKeyBodyPart.getFileName());
            String x509privateKeyPem = Pems.pem(x509KeyPair.getPrivate());
            x509PrivateKeyBodyPart.setContent(x509privateKeyPem, "application/x-x509-ca-cert");
            attachments.add(x509PrivateKeyBodyPart);
        }
        // email attachment: x509 certifiate pem
        {
            BodyPart x509CertificateBodyPart = new MimeBodyPart();
            x509CertificateBodyPart.setFileName("cert-" + signingCertificate.getCertificateId() + ".pem");
            templatesParams.put("attachedX509CertificateFileName", x509CertificateBodyPart.getFileName());
            x509CertificateBodyPart.setContent(x509CertificatePem, "application/x-x509-ca-cert");
            attachments.add(x509CertificateBodyPart);
        }

    } else {
        SigningCertificate signingCertificate = Iterables.getFirst(certificates, null);
        logger.info("X509 certificate {} already exists", signingCertificate.getCertificateId());
        templatesParams.put("x509CertificateId", signingCertificate.getCertificateId());
    }

    sendEmail(templatesParams, attachments, userName);
}

From source file:com.google.cloud.bigtable.hbase.TestPut.java

/**
 * This tests particularly odd behavior, where if an error happens on the client-side validation
 * of a list of puts, the commits after the bad put fail.  (This is unlike a server-side error
 * where all the good puts are committed.)
 *///from   w  w w.j a  v a2s .c  o  m
@Test
@Category(KnownGap.class)
public void testClientSideValidationError() throws Exception {
    BufferedMutator mutator = getConnection().getBufferedMutator(TABLE_NAME);
    Table table = getConnection().getTable(TABLE_NAME);
    byte[] rowKey1 = Bytes.toBytes("testrow-" + RandomStringUtils.randomAlphanumeric(8));
    byte[] qual1 = Bytes.toBytes("testQualifier-" + RandomStringUtils.randomAlphanumeric(8));
    byte[] value1 = Bytes.toBytes("testValue-" + RandomStringUtils.randomAlphanumeric(8));
    byte[] rowKey2 = Bytes.toBytes("testrow-" + RandomStringUtils.randomAlphanumeric(8));
    // No column.  This will cause an error during client-side validation.
    byte[] rowKey3 = Bytes.toBytes("testrow-" + RandomStringUtils.randomAlphanumeric(8));
    byte[] qual3 = Bytes.toBytes("testQualifier-" + RandomStringUtils.randomAlphanumeric(8));
    byte[] value3 = Bytes.toBytes("testValue-" + RandomStringUtils.randomAlphanumeric(8));

    List<Put> puts = new ArrayList<>();
    Put put1 = new Put(rowKey1);
    put1.addColumn(COLUMN_FAMILY, qual1, value1);
    puts.add(put1);
    Put put2 = new Put(rowKey2);
    puts.add(put2);
    Put put3 = new Put(rowKey3);
    put3.addColumn(COLUMN_FAMILY, qual3, value3);
    puts.add(put3);
    boolean exceptionThrown = false;
    try {
        mutator.mutate(puts);
    } catch (IllegalArgumentException e) {
        exceptionThrown = true;
    }
    Assert.assertTrue("Exception should have been thrown", exceptionThrown);
    Get get1 = new Get(rowKey1);
    Assert.assertFalse("Row 1 should not exist yet", table.exists(get1));
    mutator.flush();

    Assert.assertTrue("Row 1 should exist", table.exists(get1));
    Get get2 = new Get(rowKey2);
    Assert.assertFalse("Row 2 should not exist", table.exists(get2));
    Get get3 = new Get(rowKey3);
    Assert.assertFalse("Row 3 should not exist", table.exists(get3));

    table.close();
    mutator.close();
}