Example usage for org.apache.zookeeper.server.auth DigestAuthenticationProvider generateDigest

List of usage examples for org.apache.zookeeper.server.auth DigestAuthenticationProvider generateDigest

Introduction

In this page you can find the example usage for org.apache.zookeeper.server.auth DigestAuthenticationProvider generateDigest.

Prototype

public static String generateDigest(String idPassword) throws NoSuchAlgorithmException 

Source Link

Usage

From source file:com.anteam.demo.zookeeper.ZooKeeperOperationDemo.java

License:Apache License

/**
 * @param args/*w w w  .j  a  v a 2  s  . c o m*/
 * @return void()
 * @throws IOException
 * @throws InterruptedException
 * @throws KeeperException
 * @Title: main
 * @Description: ?
 */
public static void main(String[] args) throws Exception {
    String password = DigestAuthenticationProvider.generateDigest("admin:admin.pwd");
    System.out.println(password);
    //        ZooKeeperOperationDemo dm = new ZooKeeperOperationDemo();
    //        dm.createZKInstance();
    //        dm.ZKOperations();
    //        dm.ZKClose();
}

From source file:com.bfd.harpc.registry.ZkServerRegistry.java

License:Apache License

/**
 * //w  w w  . j av  a  2  s .com
 * <p>
 * 
 * @throws RpcException
 */
private void createParentsNode() throws RpcException {
    String parentPath = zkPath + Constants.ZK_SEPARATOR_DEFAULT + Constants.ZK_NAMESPACE_SERVERS;
    try {
        if (zookeeper.checkExists().forPath(parentPath) == null) {
            Id id = new Id("digest", DigestAuthenticationProvider.generateDigest(auth));
            List<ACL> acls = new ArrayList<ACL>(2);
            ACL acl = new ACL(Perms.CREATE, id);// ???server
            Id id2 = new Id("world", "anyone");
            ACL acl2 = new ACL(Perms.READ, id2);// read???
            acls.add(acl);
            acls.add(acl2);
            zookeeper.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).withACL(acls)
                    .forPath(parentPath);
        }
    } catch (Exception e) {
        String message = MessageFormat.format("Zookeeper error in the path : {0}", parentPath);
        LOGGER.error(message, e);
        throw new RpcException(message, e);
    }
}

From source file:com.bfd.harpc.test.registry.ZkTest.java

License:Apache License

public static void main(String[] args) {
    try {/*from www  .  j av  a  2  s  . c om*/
        RegistryConfig registryConfig = new RegistryConfig();
        registryConfig.setConnectstr("172.18.1.22:2182");
        CuratorFramework zookeeper = registryConfig.obtainZkClient();

        Id id = new Id("digest", DigestAuthenticationProvider.generateDigest("admin:admin123"));
        List<ACL> acls = new ArrayList<ACL>(2);
        ACL acl = new ACL(Perms.CREATE, id);
        Id id2 = new Id("world", "anyone");
        ACL acl2 = new ACL(Perms.READ, id2);
        acls.add(acl);
        acls.add(acl2);

        // zookeeper.setACL().withACL(acls);
        // zookeeper.create().creatingParentsIfNeeded().withACL(acls).forPath("/test");
        // zookeeper.create().withACL(acls).forPath("/test/123",
        // "123".getBytes());
        // zookeeper.delete().forPath("/test/123");

        String address = NetUtils.getLocalHost() + ":0:i_";
        StringBuilder pathBuilder = new StringBuilder("test123");
        // address = "192.168.73.1:0:i_0000000001";
        pathBuilder.append(Constants.ZK_SEPARATOR_DEFAULT).append(Constants.ZK_NAMESPACE_CLIENTS)
                .append(Constants.ZK_SEPARATOR_DEFAULT).append(address);

        // int length = "192.168.1.108:0:i_".length();
        // zookeeper.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(pathBuilder.toString());
        // 
        for (int i = 0; i < 10; i++) {
            zookeeper.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT_SEQUENTIAL)
                    .forPath(pathBuilder.toString());

            // List<String> list =
            // zookeeper.getChildren().forPath("test123/clients");
            // while (list.size() > 10) {
            // Integer min = new Integer(list.get(0).substring(length));
            // for (String s : list) {
            // Integer tempValue = new Integer(s.substring(length));
            // if (tempValue < min)
            // min = tempValue;
            // }
            //
            // zookeeper.delete().forPath("test123/clients" +
            // "/192.168.1.108:0:i_" + String.format("%010d", min));
            // list.remove("192.168.1.108:0:i_" + String.format("%010d",
            // min));
            // }
        }
        Thread.sleep(100000);

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.cloudera.llama.am.LlamaHAFencer.java

License:Apache License

private List<ACL> createAclsForExclusiveReadAccess() throws LlamaException {
    List<ACL> acls = new ArrayList<ACL>();
    for (ACL acl : conf.getZkAcls()) {
        acls.add(new ACL(ZKUtil.removeSpecificPerms(acl.getPerms(), ZooDefs.Perms.READ), acl.getId()));
    }/*w ww. j a va 2s  .c o m*/
    Id llamaId;
    try {
        llamaId = new Id(authScheme,
                DigestAuthenticationProvider.generateDigest(fencingUsername + ":" + fencingPassword));
    } catch (NoSuchAlgorithmException e) {
        throw new LlamaException(ErrorCode.INTERNAL_ERROR, "Unable to create username:password digest for ZK");
    }
    acls.add(new ACL(ZooDefs.Perms.READ, llamaId));
    return acls;
}

From source file:com.renren.Wario.zookeeper.test.ZooKeeperClientTest.java

License:Apache License

@Test
public void generalTest() throws InterruptedException, IOException, KeeperException {
    final ZooKeeperClient zooKeeperClient = new ZooKeeperClient("localhost:2181", 5000);
    Assert.assertFalse(zooKeeperClient.isAvailable());
    new Thread() {
        @Override/*  w  ww. j a v a  2  s  . c o  m*/
        public void run() {
            zooKeeperClient.createConnection();
        }
    }.start();

    Assert.assertFalse(zooKeeperClient.isAvailable());

    if (zkBackgroundServer == null) {
        zkBackgroundServer = new ZooKeeperBackgroundServer("2181");
        zkBackgroundServer.setDaemon(true);
        zkBackgroundServer.start();
        try {
            Thread.sleep(6000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    Assert.assertTrue(zooKeeperClient.isAvailable());
    Assert.assertEquals("localhost:2181", zooKeeperClient.getConnectionString());
    Assert.assertEquals(5000, zooKeeperClient.getSessionTimeout());
    Assert.assertTrue(zooKeeperClient.isAvailable());
    zooKeeperClient.releaseConnection();
    Assert.assertFalse(zooKeeperClient.isAvailable());
    zooKeeperClient.createConnection();
    Assert.assertTrue(zooKeeperClient.isAvailable());

    CountDownLatch countDownLatch = new CountDownLatch(1);
    ZooKeeper zk = new ZooKeeper("localhost:2181", 2000, new MyWatcher(countDownLatch));
    countDownLatch.await();

    try {
        ArrayList<ACL> acls = new ArrayList<ACL>();
        Id id = new Id("digest", DigestAuthenticationProvider.generateDigest("admin:admin"));
        ACL acl = new ACL(ZooDefs.Perms.ALL, id);
        acls.add(acl);
        zk.create("/testACL", "testACL".getBytes(), acls, CreateMode.PERSISTENT);

        ZooKeeperClient zooKeeperClient2 = new ZooKeeperClient("localhost:2181", 2000, "", "admin:admin");
        zooKeeperClient2.createConnection();
        Assert.assertEquals("testACL", new String(zooKeeperClient2.getData("/testACL", new Stat())));

    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (KeeperException e) {
        e.printStackTrace();
    } finally {
        zk.delete("/testACL", -1);
    }
}

From source file:me.smoe.adar.zookeeper.zookeeper.Zookeeper.java

License:Apache License

public static void auth(ZooKeeper zooKeeper)
        throws NoSuchAlgorithmException, KeeperException, InterruptedException {
    ACL acl = new ACL(Perms.READ, new Id("digest", DigestAuthenticationProvider.generateDigest("admin:admin")));

    zooKeeper.create("/auth", "auth".getBytes(), Collections.singletonList(acl), CreateMode.EPHEMERAL);
}

From source file:me.smoe.adar.zookeeper.zookeeper.Zookeeper.java

License:Apache License

public static void authForRoot(ZooKeeper zooKeeper)
        throws NoSuchAlgorithmException, KeeperException, InterruptedException {
    ACL acl = new ACL(Perms.ALL, new Id("digest", DigestAuthenticationProvider.generateDigest("admin:admin")));

    zooKeeper.setACL("/", Collections.singletonList(acl), -1);
}

From source file:me.smoe.adar.zookeeper.zookeeper.Zookeeper.java

License:Apache License

public static void createNodeWithAuth(ZooKeeper zooKeeper, String path, String username, String password)
        throws KeeperException, InterruptedException, NoSuchAlgorithmException {
    ACL acl = new ACL(Perms.READ | Perms.WRITE | Perms.CREATE | Perms.DELETE,
            new Id("digest", DigestAuthenticationProvider.generateDigest(username + ":" + password)));

    zooKeeper.create(path, path.getBytes(), Collections.singletonList(acl), CreateMode.PERSISTENT);
}

From source file:org.apache.curator.framework.recipes.leader.TestLeaderAcls.java

License:Apache License

@Test(description = "Validation test for CURATOR-365")
public void testAclErrorWithLeader() throws Exception {
    ACLProvider provider = new ACLProvider() {
        @Override//from  www  . j a v  a 2 s .  co  m
        public List<ACL> getDefaultAcl() {
            return ZooDefs.Ids.OPEN_ACL_UNSAFE;
        }

        @Override
        public List<ACL> getAclForPath(String path) {
            if (path.equals("/base")) {
                try {
                    String testDigest = DigestAuthenticationProvider.generateDigest("test:test");
                    return Collections.singletonList(new ACL(ZooDefs.Perms.ALL, new Id("digest", testDigest)));
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }
            }
            return getDefaultAcl();
        }
    };

    RetryPolicy retryPolicy = new ExponentialBackoffRetry(timing.milliseconds(), 3);
    CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder()
            .connectString(server.getConnectString()).retryPolicy(retryPolicy).aclProvider(provider)
            .authorization("digest", "test:test".getBytes());
    CuratorFramework client = builder.build();
    LeaderLatch latch = null;
    try {
        client.start();

        latch = new LeaderLatch(client, "/base");
        latch.start();
        Assert.assertTrue(latch.await(timing.forWaiting().seconds(), TimeUnit.SECONDS));
        latch.close();
        latch = null;

        CuratorFramework noAuthClient = CuratorFrameworkFactory.newClient(server.getConnectString(),
                retryPolicy);
        try {
            noAuthClient.start();

            final CountDownLatch noAuthLatch = new CountDownLatch(1);
            UnhandledErrorListener listener = new UnhandledErrorListener() {
                @Override
                public void unhandledError(String message, Throwable e) {
                    if (e instanceof KeeperException.NoAuthException) {
                        noAuthLatch.countDown();
                    }
                }
            };
            noAuthClient.getUnhandledErrorListenable().addListener(listener);

            // use a path below "base" as noAuthClient is not authorized to create nodes in "/base"
            // but also making sure that the code goes through the backgroundCreateParentsThenNode() codepath
            latch = new LeaderLatch(noAuthClient, "/base/second");
            latch.start();
            Assert.assertTrue(timing.awaitLatch(noAuthLatch));
        } finally {
            CloseableUtils.closeQuietly(noAuthClient);
        }
    } finally {
        CloseableUtils.closeQuietly(latch);
        CloseableUtils.closeQuietly(client);
    }
}

From source file:org.apache.curator.x.async.modeled.TestModeledFramework.java

License:Apache License

@Test
public void testAcl() throws NoSuchAlgorithmException {
    List<ACL> aclList = Collections.singletonList(new ACL(ZooDefs.Perms.WRITE,
            new Id("digest", DigestAuthenticationProvider.generateDigest("test:test"))));
    ModelSpec<TestModel> aclModelSpec = ModelSpec.builder(modelSpec.path(), modelSpec.serializer())
            .withAclList(aclList).build();
    ModeledFramework<TestModel> client = ModeledFramework.wrap(async, aclModelSpec);
    complete(client.set(new TestModel("John", "Galt", "Galt's Gulch", 21, BigInteger.valueOf(1010101))));
    complete(client.update(new TestModel("John", "Galt", "Galt's Gulch", 54, BigInteger.valueOf(88))),
            (__, e) -> Assert.assertNotNull(e, "Should've gotten an auth failure"));

    try (CuratorFramework authCurator = CuratorFrameworkFactory.builder()
            .connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1))
            .authorization("digest", "test:test".getBytes()).build()) {
        authCurator.start();/*from  w ww .ja  va  2  s  . c o  m*/
        ModeledFramework<TestModel> authClient = ModeledFramework.wrap(AsyncCuratorFramework.wrap(authCurator),
                aclModelSpec);
        complete(authClient.update(new TestModel("John", "Galt", "Galt's Gulch", 42, BigInteger.valueOf(66))),
                (__, e) -> Assert.assertNull(e, "Should've succeeded"));
    }
}