Example usage for java.util Random nextLong

List of usage examples for java.util Random nextLong

Introduction

In this page you can find the example usage for java.util Random nextLong.

Prototype

public long nextLong() 

Source Link

Document

Returns the next pseudorandom, uniformly distributed long value from this random number generator's sequence.

Usage

From source file:org.openmeetings.app.ldap.LdapLoginManagement.java

/**
 * Ldap Login//from ww w . j  a va2 s .  c o  m
 * 
 * Connection Data is retrieved from ConfigurationFile
 * 
 */
// ----------------------------------------------------------------------------------------
public Object doLdapLogin(String user, String passwd, RoomClient currentClient, String SID, String domain) {
    log.debug("LdapLoginmanagement.doLdapLogin");

    // Retrieve Configuration Data
    HashMap<String, String> configData;

    try {
        configData = getLdapConfigData(domain);
    } catch (Exception e) {
        log.error("Error on LdapAuth : " + e.getMessage());
        return null;
    }

    if (configData == null || configData.size() < 1) {
        log.error("Error on LdapLogin : Configurationdata couldnt be retrieved!");
        return null;
    }

    // Connection URL
    String ldap_url = configData.get(CONFIGKEY_LDAP_URL);

    // for OpenLDAP only
    // LDAP SERVER TYPE to search accordingly
    String ldap_server_type = configData.get(CONFIGKEY_LDAP_SERVER_TYPE);

    // Username for LDAP SERVER himself
    String ldap_admin_dn = configData.get(CONFIGKEY_LDAP_ADMIN_DN);

    // Password for LDAP SERVER himself
    String ldap_passwd = configData.get(CONFIGKEY_LDAP_ADMIN_PASSWD);

    // SearchScope for retrievment of userdata
    String ldap_search_scope = configData.get(CONFIGKEY_LDAP_SEARCH_SCOPE);

    // FieldName for Users's Principal Name
    String ldap_fieldname_user_principal = configData.get(CONFIGKEY_LDAP_FIELDNAME_USER_PRINCIPAL);

    // Wether or not we'll store Ldap passwd into OM db
    String ldap_sync_passwd_to_om = configData.get(CONFIGKEY_LDAP_SYNC_PASSWD_OM);

    /***
     * for future use (lemeur) // Ldap user filter to refine the search
     * String ldap_user_extrafilter =
     * configData.get(CONFIGKEY_LDAP_USER_EXTRAFILTER);
     * 
     * // Count of Ldap group filters String ldap_group_filter_num =
     * configData.get(CONFIGKEY_LDAP_GROUP_FILTER_NUM);
     * 
     * // Prefix name of Ldap group filter name String
     * ldap_group_filter_name_prefix =
     * configData.get(CONFIGKEY_LDAP_GROUP_FILTER_NAME_PREFIX);
     * 
     * // Prefix name of Ldap group filter base String
     * ldap_group_filter_base_prefix =
     * configData.get(CONFIGKEY_LDAP_GROUP_FILTER_NAME_PREFIX);
     * 
     * // Prefix name of Ldap group filter type String
     * ldap_group_filter_type_prefix =
     * configData.get(CONFIGKEY_LDAP_GROUP_FILTER_TYPE_PREFIX);
     * 
     * // Prefix name of Ldap group filter text String
     * ldap_group_filter_text_prefix =
     * configData.get(CONFIGKEY_LDAP_GROUP_FILTER_TEXT_PREFIX);
     ***/

    // Get custom Ldap attributes mapping
    String ldap_user_attr_lastname = configData.get(CONFIGKEY_LDAP_KEY_LASTNAME);
    String ldap_user_attr_firstname = configData.get(CONFIGKEY_LDAP_KEY_FIRSTNAME);
    String ldap_user_attr_mail = configData.get(CONFIGKEY_LDAP_KEY_MAIL);
    String ldap_user_attr_street = configData.get(CONFIGKEY_LDAP_KEY_STREET);
    String ldap_user_attr_additional_name = configData.get(CONFIGKEY_LDAP_KEY_ADDITIONAL_NAME);
    String ldap_user_attr_fax = configData.get(CONFIGKEY_LDAP_KEY_FAX);
    String ldap_user_attr_zip = configData.get(CONFIGKEY_LDAP_KEY_ZIP);
    String ldap_user_attr_country = configData.get(CONFIGKEY_LDAP_KEY_COUNTRY);
    String ldap_user_attr_town = configData.get(CONFIGKEY_LDAP_KEY_TOWN);
    String ldap_user_attr_phone = configData.get(CONFIGKEY_LDAP_KEY_PHONE);
    String ldap_user_attr_timezone = configData.get(CONFIGKEY_LDAP_TIMEZONE_NAME);
    String ldap_use_lower_case = configData.get(CONFIGKEY_LDAP_USE_LOWER_CASE);

    if (ldap_use_lower_case != null && ldap_use_lower_case.equals("true")) {
        user = user.toLowerCase();
    }

    if (ldap_user_attr_lastname == null) {
        ldap_user_attr_lastname = LDAP_KEY_LASTNAME;
    }
    if (ldap_user_attr_firstname == null) {
        ldap_user_attr_firstname = LDAP_KEY_FIRSTNAME;
    }
    if (ldap_user_attr_mail == null) {
        ldap_user_attr_mail = LDAP_KEY_MAIL;
    }
    if (ldap_user_attr_street == null) {
        ldap_user_attr_street = LDAP_KEY_STREET;
    }
    if (ldap_user_attr_additional_name == null) {
        ldap_user_attr_additional_name = LDAP_KEY_ADDITIONAL_NAME;
    }
    if (ldap_user_attr_fax == null) {
        ldap_user_attr_fax = LDAP_KEY_FAX;
    }
    if (ldap_user_attr_zip == null) {
        ldap_user_attr_zip = LDAP_KEY_ZIP;
    }
    if (ldap_user_attr_country == null) {
        ldap_user_attr_country = LDAP_KEY_COUNTRY;
    }
    if (ldap_user_attr_town == null) {
        ldap_user_attr_town = LDAP_KEY_TOWN;
    }
    if (ldap_user_attr_phone == null) {
        ldap_user_attr_phone = LDAP_KEY_PHONE;
    }
    if (ldap_user_attr_timezone == null) {
        ldap_user_attr_timezone = LDAP_KEY_TIMEZONE;
    }

    // Auth Type
    String ldap_auth_type = configData.get(CONFIGKEY_LDAP_AUTH_TYPE);

    if (ldap_auth_type == null)
        ldap_auth_type = "";

    if (!isValidAuthType(ldap_auth_type)) {
        log.error("ConfigKey in Ldap Config contains invalid auth type : '" + ldap_auth_type
                + "' -> Defaulting to " + LdapAuthBase.LDAP_AUTH_TYPE_SIMPLE);
        ldap_auth_type = LdapAuthBase.LDAP_AUTH_TYPE_SIMPLE;
    }

    // Filter for Search of UserData
    String ldap_search_filter = "(" + ldap_fieldname_user_principal + "=" + user + ")";

    log.debug("Searching userdata with LDAP Search Filter :" + ldap_search_filter);

    // replace : -> in config = are replaced by : to be able to build valid
    // key=value pairs
    ldap_search_scope = ldap_search_scope.replaceAll(":", "=");
    ldap_admin_dn = ldap_admin_dn.replaceAll(":", "=");

    LdapAuthBase lAuth = new LdapAuthBase(ldap_url, ldap_admin_dn, ldap_passwd, ldap_auth_type);

    log.debug("authenticating admin...");
    lAuth.authenticateUser(ldap_admin_dn, ldap_passwd);

    log.debug("Checking server type...");
    // for OpenLDAP only
    if (ldap_server_type.equalsIgnoreCase("OpenLDAP")) {
        String ldapUserDN = user;
        log.debug("LDAP server is OpenLDAP");
        log.debug("LDAP search base: " + ldap_search_scope);
        HashMap<String, String> uidCnDictionary = lAuth.getUidCnHashMap(ldap_search_scope, ldap_search_filter,
                ldap_fieldname_user_principal);
        if (uidCnDictionary.get(user) != null) {
            ldapUserDN = uidCnDictionary.get(user) + "," + ldap_search_scope;
            log.debug("Authentication with DN: " + ldapUserDN);
        }
        try {
            if (!lAuth.authenticateUser(ldapUserDN, passwd)) {
                log.error(ldapUserDN + " not authenticated.");
                return new Long(-11);
            }
        } catch (Exception e) {
            log.error("Error on LdapAuth : " + e.getMessage());
            return null;
        }
    } else {
        try {
            if (!lAuth.authenticateUser(user, passwd))
                return new Long(-11);
        } catch (Exception e) {
            log.error("Error on LdapAuth : " + e.getMessage());
            return null;
        }
    }

    // check if user already exists

    Users u = null;

    try {
        u = userManagement.getUserByLogin(user);

    } catch (Exception e) {
        log.error("Error retrieving Userdata : " + e.getMessage());
    }

    // User not existant in local database -> take over data for referential
    // integrity
    if (u == null) {
        log.debug("user doesnt exist local -> create new");

        // Attributes to retrieve from ldap
        List<String> attributes = new ArrayList<String>();
        attributes.add(ldap_user_attr_lastname); // Lastname
        attributes.add(ldap_user_attr_firstname); // Firstname
        attributes.add(ldap_user_attr_mail);// mail
        attributes.add(ldap_user_attr_street); // Street
        attributes.add(ldap_user_attr_additional_name); // Additional name
        attributes.add(ldap_user_attr_fax); // Fax
        attributes.add(ldap_user_attr_zip); // ZIP
        attributes.add(ldap_user_attr_country); // Country
        attributes.add(ldap_user_attr_town); // Town
        attributes.add(ldap_user_attr_phone); // Phone
        attributes.add(ldap_user_attr_timezone); // Phone

        HashMap<String, String> ldapAttrs = new HashMap<String, String>();
        ldapAttrs.put("lastnameAttr", ldap_user_attr_lastname);
        ldapAttrs.put("firstnameAttr", ldap_user_attr_firstname);
        ldapAttrs.put("mailAttr", ldap_user_attr_mail);
        ldapAttrs.put("streetAttr", ldap_user_attr_street);
        ldapAttrs.put("additionalNameAttr", ldap_user_attr_additional_name);
        ldapAttrs.put("faxAttr", ldap_user_attr_fax);
        ldapAttrs.put("zipAttr", ldap_user_attr_zip);
        ldapAttrs.put("countryAttr", ldap_user_attr_country);
        ldapAttrs.put("townAttr", ldap_user_attr_town);
        ldapAttrs.put("phoneAttr", ldap_user_attr_phone);
        ldapAttrs.put("phoneAttr", ldap_user_attr_phone);
        ldapAttrs.put("timezoneAttr", ldap_user_attr_timezone);

        Vector<HashMap<String, String>> result = lAuth.getData(ldap_search_scope, ldap_search_filter,
                attributes);

        if (result == null || result.size() < 1) {
            log.error("Error on Ldap request - no result for user " + user);
            return new Long(-10);
        }

        if (result.size() > 1) {
            log.error("Error on Ldap request - more than one result for user " + user);
            return null;
        }

        HashMap<String, String> userData = result.get(0);

        try {
            // Create User with LdapData
            Long userid;
            if (ldap_sync_passwd_to_om != null && ldap_sync_passwd_to_om.equals("no")) {
                Random r = new Random();
                String token = Long.toString(Math.abs(r.nextLong()), 36);
                log.debug("Synching Ldap user to OM DB with RANDOM password: " + token);
                userid = createUserFromLdapData(userData, token, user, ldapAttrs);
            } else {
                log.debug("Synching Ldap user to OM DB with password");
                userid = createUserFromLdapData(userData, passwd, user, ldapAttrs);
            }
            log.debug("New User ID : " + userid);

            // If invoked via SOAP this is NULL
            if (currentClient != null) {
                currentClient.setUser_id(userid);
            }

            // Update Session
            Boolean bool = sessionManagement.updateUser(SID, userid);

            if (bool == null) {
                // Exception
                log.error("Error on Updating Session");
                return new Long(-1);
            } else if (!bool) {
                // invalid Session-Object
                log.error("Invalid Session Object");
                return new Long(-35);
            }

            // Return UserObject
            Users u2 = userManagement.getUserById(userid);

            if (u2 == null)
                return new Long(-1);

            u2.setExternalUserType(EXTERNAL_USER_TYPE_LDAP); // TIBO

            // initialize lazy collection
            userManagement.refreshUserObject(u2);

            log.debug("getUserbyId : " + userid + " : " + u2.getLogin());

            return u2;

        } catch (Exception e) {
            log.error("Error on Working Userdata : ", e);
            return new Long(-1);
        }
    } else {
        // User exists, just update necessary values
        log.debug("User already exists -> Update of current passwd");

        // If invoked via SOAP this is NULL
        if (currentClient != null) {
            currentClient.setUser_id(u.getUser_id());
        }

        // Update Session
        Boolean bool = sessionManagement.updateUser(SID, u.getUser_id());

        if (bool == null) {
            // Exception
            log.error("Error on Updating Session");
            return new Long(-1);
        } else if (!bool) {
            // invalid Session-Object
            log.error("Invalid Session Object");
            return new Long(-35);
        }

        // Update password (could have changed in LDAP)
        if (ldap_sync_passwd_to_om == null || !ldap_sync_passwd_to_om.equals("no")) {
            u.setPassword(passwd);
        }
        try {
            userManagement.updateUserObject(u, true);
        } catch (Exception e) {
            log.error("Error updating user : " + e.getMessage());
            return new Long(-1);
        }

        return u;

    }
}

From source file:com.aiatss.coast.pmm.application.service.agreement.PolicyServiceTest.java

private String genPolicyNO() {
    Random r = new Random();
    Long a = r.nextLong();
    return String.valueOf(a).substring(1, 11);
}

From source file:com.siemens.industrialbenchmark.util.RandomNumberExpectedValueTest.java

@Test
public void testExpectedValues() {

    long seed = 0;
    Random rand = new Random(seed);
    RandomDataGenerator randomData = new RandomDataGenerator();

    double uniformAverage = 0.0;
    double binomialAverage = 0.0;
    double normalAverage = 0.0;
    double exponentialAverage = 0.0;

    for (int i = 0; i < 1e6; i++) {

        // set current seed
        randomData.reSeed(seed);/*  w  w w  .j  a va 2 s. co  m*/

        // draw random numbers
        double n = randomData.nextGaussian(0, 1);
        double u = randomData.nextUniform(0, 1);
        double b = randomData.nextBinomial(1, 0.5);
        double e = randomData.nextExponential(0.25);

        // average mean random number
        uniformAverage += (1. / (1. + i)) * (u - uniformAverage);
        binomialAverage += (1. / (1. + i)) * (b - binomialAverage);
        normalAverage += (1. / (1. + i)) * (n - normalAverage);
        exponentialAverage += (1. / (1. + i)) * (e - exponentialAverage);

        // draw new seed from global random generator
        seed = rand.nextLong();
    }

    assertEquals(0.5, uniformAverage, 0.001);
    assertEquals(0.5, binomialAverage, 0.001);
    assertEquals(0.0, normalAverage, 0.001);
    assertEquals(0.25, exponentialAverage, 0.001);
}

From source file:org.gbif.dwca.action.ValidateAction.java

private boolean storeReport() {
    if (reportId == null) {
        // create random report id
        Random rnd = new Random();
        reportId = String.format("%Tj-%d", new Date(), Math.abs(rnd.nextLong()));
    }// w  ww  .j  a va 2s  .  c o m
    File report = new File(cfg.getProperty(REPORTS_DIR_KEY), reportId + ".html");
    reportUrl = cfg.getProperty(REPORTS_WWW_KEY) + "/" + reportId + ".html";
    log.debug("Writing validation report to " + report.getAbsolutePath());
    try {
        BeansWrapper wrapper = new StrutsBeanWrapper(true);
        wrapper.setExposureLevel(0);
        fm.setObjectWrapper(wrapper);
        FreemarkerUtils.writeUtf8File(fm, report, "/WEB-INF/pages/validate_report.ftl", this);
    } catch (TemplateException e) {
        log.error("Cannot find template for validation report", e);
        return false;
    } catch (IOException e) {
        log.error("Cannot write validation report", e);
        return false;
    }
    return true;
}

From source file:com.agiletec.plugins.jpnewsletter.aps.system.services.newsletter.NewsletterManager.java

protected String createToken(String word) throws NoSuchAlgorithmException {
    Random random = new Random();
    StringBuilder salt = new StringBuilder();
    long rndLong = random.nextLong();
    salt.append(rndLong);/*from  ww  w.  ja v a  2  s. c om*/
    String date = DateConverter.getFormattedDate(new Date(), "SSSmmyyyy-SSS-MM:ssddmmHHmmEEE");
    salt.append(date);
    rndLong = random.nextLong();
    salt.append(rndLong);
    // genero il token in base a username e salt
    String token = ShaEncoder.encodeWord(word, salt.toString());
    return token;
}

From source file:org.apache.marmotta.kiwi.test.PersistenceTest.java

/**
 * Test storing and loading string literals (with type and without language).
 *
 * @throws SQLException/*from w  w  w. ja v a 2  s .  c  o m*/
 */
@Test
public void testStoreIntLiteral() throws SQLException {
    KiWiConnection connection = persistence.getConnection();
    try {
        KiWiUriResource uri = new KiWiUriResource(Namespaces.NS_XSD + "integer");

        Random rnd = new Random();
        long value = rnd.nextLong();

        // add a new URI to the triple store and check if it exists afterwards, before and after commit
        KiWiIntLiteral literal = new KiWiIntLiteral(value, uri);
        connection.storeNode(literal);

        // check if it then has a database ID
        Assert.assertTrue(literal.getId() >= 0);

        KiWiNode testLiteral1 = connection.loadNodeById(literal.getId());

        // needs to be equal, and should also be the identical object!
        Assert.assertEquals(literal, testLiteral1);
        Assert.assertEquals(uri, ((KiWiLiteral) testLiteral1).getType());
        //Assert.assertTrue(literal == testLiteral1);

        connection.commit();

        KiWiNode testLiteral2 = connection.loadNodeById(literal.getId());

        // needs to be equal, and should also be the identical object!
        Assert.assertEquals(literal, testLiteral2);
        Assert.assertEquals(uri, ((KiWiLiteral) testLiteral2).getType());
        //Assert.assertTrue(literal == testLiteral2);

        KiWiNode testLiteral3 = connection.loadLiteral(literal.stringValue(), null, uri);

        // needs to be equal, and should also be the identical object!
        Assert.assertEquals(literal, testLiteral3);
        Assert.assertEquals(uri, ((KiWiLiteral) testLiteral3).getType());
        //Assert.assertTrue(literal == testLiteral3);

        // load by integer value
        KiWiNode testLiteral6 = connection.loadLiteral(value);

        // needs to be equal, and should also be the identical object!
        Assert.assertEquals(literal, testLiteral6);
        Assert.assertEquals(uri, ((KiWiLiteral) testLiteral6).getType());
        //Assert.assertTrue(literal == testLiteral6);

        connection.commit();

        // clear cache and test again
        persistence.clearCache();
        KiWiNode testLiteral4 = connection.loadNodeById(literal.getId());

        // needs to be equal, but now it should not be the same object!
        Assert.assertEquals(literal, testLiteral4);
        Assert.assertEquals(uri, ((KiWiLiteral) testLiteral4).getType());
        //Assert.assertTrue(literal != testLiteral4);

        KiWiNode testLiteral5 = connection.loadLiteral(literal.stringValue(), null, uri);

        // needs to be equal, but now it should not be the same object!
        Assert.assertEquals(literal, testLiteral5);
        Assert.assertEquals(uri, ((KiWiLiteral) testLiteral5).getType());
        //Assert.assertTrue(literal != testLiteral5);

        // load by integer value
        KiWiNode testLiteral7 = connection.loadLiteral(value);

        // needs to be equal, and should also be the identical object!
        Assert.assertEquals(literal, testLiteral7);
        Assert.assertEquals(uri, ((KiWiLiteral) testLiteral7).getType());
        //Assert.assertTrue(literal != testLiteral7);

        connection.commit();

        // finally do a test on the nodes table, it should contain exactly one entry
        PreparedStatement checkNodeStmt = connection.getJDBCConnection()
                .prepareStatement("SELECT * FROM nodes WHERE ntype='int'");
        ResultSet result = checkNodeStmt.executeQuery();

        Assert.assertTrue(result.next());
        Assert.assertEquals((long) literal.getId(), result.getLong("id"));
        Assert.assertEquals(literal.stringValue(), result.getString("svalue"));
        Assert.assertEquals(value, result.getLong("ivalue"));
        Assert.assertEquals("int", result.getString("ntype"));
        Assert.assertNull(result.getString("lang"));
        Assert.assertEquals((long) uri.getId(), result.getLong("ltype"));

        result.close();
        connection.commit();
    } finally {
        connection.close();
    }

}

From source file:io.druid.hll.HyperLogLogCollectorTest.java

@Ignore
@Test // This test can help when finding potential combinations that are weird, but it's non-deterministic
public void testFoldingwithDifferentOffsets() throws Exception {
    // final Random random = new Random(37); // this seed will cause this test to fail because of slightly larger errors
    final Random random = new Random(0);
    for (int j = 0; j < 10; j++) {
        HyperLogLogCollector smallVals = HyperLogLogCollector.makeLatestCollector();
        HyperLogLogCollector bigVals = HyperLogLogCollector.makeLatestCollector();
        HyperLogLogCollector all = HyperLogLogCollector.makeLatestCollector();

        int numThings = 500000;
        for (int i = 0; i < numThings; i++) {
            byte[] hashedVal = fn.hashLong(random.nextLong()).asBytes();

            if (i < 1000) {
                smallVals.add(hashedVal);
            } else {
                bigVals.add(hashedVal);/* ww w . j  a v a  2 s  .c  om*/
            }
            all.add(hashedVal);
        }

        HyperLogLogCollector folded = HyperLogLogCollector.makeLatestCollector();
        folded.fold(smallVals);
        folded.fold(bigVals);
        final double expected = all.estimateCardinality();
        Assert.assertEquals(expected, folded.estimateCardinality(), expected * 0.025);
        Assert.assertEquals(numThings, folded.estimateCardinality(), numThings * 0.05);
    }
}

From source file:org.apache.druid.hll.HyperLogLogCollectorTest.java

@Ignore
@Test // This test can help when finding potential combinations that are weird, but it's non-deterministic
public void testFoldingwithDifferentOffsets() {
    // final Random random = new Random(37); // this seed will cause this test to fail because of slightly larger errors
    final Random random = new Random(0);
    for (int j = 0; j < 10; j++) {
        HyperLogLogCollector smallVals = HyperLogLogCollector.makeLatestCollector();
        HyperLogLogCollector bigVals = HyperLogLogCollector.makeLatestCollector();
        HyperLogLogCollector all = HyperLogLogCollector.makeLatestCollector();

        int numThings = 500000;
        for (int i = 0; i < numThings; i++) {
            byte[] hashedVal = fn.hashLong(random.nextLong()).asBytes();

            if (i < 1000) {
                smallVals.add(hashedVal);
            } else {
                bigVals.add(hashedVal);/*from w w w .  j a  v  a  2s  .co m*/
            }
            all.add(hashedVal);
        }

        HyperLogLogCollector folded = HyperLogLogCollector.makeLatestCollector();
        folded.fold(smallVals);
        folded.fold(bigVals);
        final double expected = all.estimateCardinality();
        Assert.assertEquals(expected, folded.estimateCardinality(), expected * 0.025);
        Assert.assertEquals(numThings, folded.estimateCardinality(), numThings * 0.05);
    }
}

From source file:io.druid.hll.HyperLogLogCollectorTest.java

@Test
public void testFolding() throws Exception {
    final Random random = new Random(0);
    final int[] numValsToCheck = { 10, 20, 50, 100, 1000, 2000 };
    for (int numThings : numValsToCheck) {
        HyperLogLogCollector allCombined = HyperLogLogCollector.makeLatestCollector();
        HyperLogLogCollector oneHalf = HyperLogLogCollector.makeLatestCollector();
        HyperLogLogCollector otherHalf = HyperLogLogCollector.makeLatestCollector();

        for (int i = 0; i < numThings; ++i) {
            byte[] hashedVal = fn.hashLong(random.nextLong()).asBytes();

            allCombined.add(hashedVal);//  w w w  .ja  va2s .  c o  m
            if (i % 2 == 0) {
                oneHalf.add(hashedVal);
            } else {
                otherHalf.add(hashedVal);
            }
        }

        HyperLogLogCollector folded = HyperLogLogCollector.makeLatestCollector();

        folded.fold(oneHalf);
        Assert.assertEquals(oneHalf, folded);
        Assert.assertEquals(oneHalf.estimateCardinality(), folded.estimateCardinality(), 0.0d);

        folded.fold(otherHalf);
        Assert.assertEquals(allCombined, folded);
        Assert.assertEquals(allCombined.estimateCardinality(), folded.estimateCardinality(), 0.0d);
    }
}

From source file:io.druid.hll.HyperLogLogCollectorTest.java

@Test
public void testFoldingByteBuffers() throws Exception {
    final Random random = new Random(0);
    final int[] numValsToCheck = { 10, 20, 50, 100, 1000, 2000 };
    for (int numThings : numValsToCheck) {
        HyperLogLogCollector allCombined = HyperLogLogCollector.makeLatestCollector();
        HyperLogLogCollector oneHalf = HyperLogLogCollector.makeLatestCollector();
        HyperLogLogCollector otherHalf = HyperLogLogCollector.makeLatestCollector();

        for (int i = 0; i < numThings; ++i) {
            byte[] hashedVal = fn.hashLong(random.nextLong()).asBytes();

            allCombined.add(hashedVal);//  w  w  w . j a  v a2  s.  c  o m
            if (i % 2 == 0) {
                oneHalf.add(hashedVal);
            } else {
                otherHalf.add(hashedVal);
            }
        }

        HyperLogLogCollector folded = HyperLogLogCollector.makeLatestCollector();

        folded.fold(oneHalf.toByteBuffer());
        Assert.assertEquals(oneHalf, folded);
        Assert.assertEquals(oneHalf.estimateCardinality(), folded.estimateCardinality(), 0.0d);

        folded.fold(otherHalf.toByteBuffer());
        Assert.assertEquals(allCombined, folded);
        Assert.assertEquals(allCombined.estimateCardinality(), folded.estimateCardinality(), 0.0d);
    }
}