Java Code Examples for org.apache.zookeeper.ZooKeeper#addAuthInfo()

The following examples show how to use org.apache.zookeeper.ZooKeeper#addAuthInfo() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CuratorFrameworkImpl.java    From curator with Apache License 2.0 6 votes vote down vote up
private ZookeeperFactory makeZookeeperFactory(final ZookeeperFactory actualZookeeperFactory)
{
    return new ZookeeperFactory()
    {
        @Override
        public ZooKeeper newZooKeeper(String connectString, int sessionTimeout, Watcher watcher, boolean canBeReadOnly) throws Exception
        {
            ZooKeeper zooKeeper = actualZookeeperFactory.newZooKeeper(connectString, sessionTimeout, watcher, canBeReadOnly);
            for ( AuthInfo auth : authInfos )
            {
                zooKeeper.addAuthInfo(auth.getScheme(), auth.getAuth());
            }

            return zooKeeper;
        }
    };
}
 
Example 2
Source File: CuratorFrameworkImpl.java    From xian with Apache License 2.0 6 votes vote down vote up
private ZookeeperFactory makeZookeeperFactory(final ZookeeperFactory actualZookeeperFactory)
{
    return new ZookeeperFactory()
    {
        @Override
        public ZooKeeper newZooKeeper(String connectString, int sessionTimeout, Watcher watcher, boolean canBeReadOnly) throws Exception
        {
            ZooKeeper zooKeeper = actualZookeeperFactory.newZooKeeper(connectString, sessionTimeout, watcher, canBeReadOnly);
            for ( AuthInfo auth : authInfos )
            {
                zooKeeper.addAuthInfo(auth.getScheme(), auth.getAuth());
            }

            return zooKeeper;
        }
    };
}
 
Example 3
Source File: ZKManager.java    From tbschedule with Apache License 2.0 6 votes vote down vote up
private void createZookeeper(final CountDownLatch connectionLatch) throws Exception {
    zk = new ZooKeeper(this.properties.getProperty(keys.zkConnectString.toString()),
        Integer.parseInt(this.properties.getProperty(keys.zkSessionTimeout.toString())),
        new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                sessionEvent(connectionLatch, event);
            }
        });
    String authString = this.properties.getProperty(keys.userName.toString()) + ":" + this.properties
        .getProperty(keys.password.toString());
    this.isCheckParentPath = Boolean
        .parseBoolean(this.properties.getProperty(keys.isCheckParentPath.toString(), "true"));
    zk.addAuthInfo("digest", authString.getBytes());
    acl.clear();
    acl.add(new ACL(ZooDefs.Perms.ALL, new Id("digest", DigestAuthenticationProvider.generateDigest(authString))));
    acl.add(new ACL(ZooDefs.Perms.READ, Ids.ANYONE_ID_UNSAFE));
}
 
Example 4
Source File: ZKManager.java    From uncode-schedule with Apache License 2.0 6 votes vote down vote up
private void createZookeeper(final CountDownLatch connectionLatch) throws Exception {
  zk = new ZooKeeper(this.properties.getProperty(keys.zkConnectString
      .toString()), Integer.parseInt(this.properties
      .getProperty(keys.zkSessionTimeout.toString())),
      new Watcher() {
        public void process(WatchedEvent event) {
          sessionEvent(connectionLatch, event);
        }
      });
  String authString = this.properties.getProperty(keys.userName.toString())
      + ":" + this.properties.getProperty(keys.password.toString());
  zk.addAuthInfo("digest", authString.getBytes());
  acl.clear();
  acl.add(new ACL(ZooDefs.Perms.ALL, new Id("digest",
      DigestAuthenticationProvider.generateDigest(authString))));
  acl.add(new ACL(ZooDefs.Perms.READ, Ids.ANYONE_ID_UNSAFE));
}
 
Example 5
Source File: ActiveStandbyElector.java    From big-c with Apache License 2.0 6 votes vote down vote up
/**
 * Get a new zookeeper client instance. protected so that test class can
 * inherit and pass in a mock object for zookeeper
 * 
 * @return new zookeeper client instance
 * @throws IOException
 * @throws KeeperException zookeeper connectionloss exception
 */
protected synchronized ZooKeeper getNewZooKeeper() throws IOException,
    KeeperException {
  
  // Unfortunately, the ZooKeeper constructor connects to ZooKeeper and
  // may trigger the Connected event immediately. So, if we register the
  // watcher after constructing ZooKeeper, we may miss that event. Instead,
  // we construct the watcher first, and have it block any events it receives
  // before we can set its ZooKeeper reference.
  watcher = new WatcherWithClientRef();
  ZooKeeper zk = new ZooKeeper(zkHostPort, zkSessionTimeout, watcher);
  watcher.setZooKeeperRef(zk);

  // Wait for the asynchronous success/failure. This may throw an exception
  // if we don't connect within the session timeout.
  watcher.waitForZKConnectionEvent(zkSessionTimeout);
  
  for (ZKAuthInfo auth : zkAuthInfo) {
    zk.addAuthInfo(auth.getScheme(), auth.getAuth());
  }
  return zk;
}
 
Example 6
Source File: ActiveStandbyElector.java    From hadoop with Apache License 2.0 6 votes vote down vote up
/**
 * Get a new zookeeper client instance. protected so that test class can
 * inherit and pass in a mock object for zookeeper
 * 
 * @return new zookeeper client instance
 * @throws IOException
 * @throws KeeperException zookeeper connectionloss exception
 */
protected synchronized ZooKeeper getNewZooKeeper() throws IOException,
    KeeperException {
  
  // Unfortunately, the ZooKeeper constructor connects to ZooKeeper and
  // may trigger the Connected event immediately. So, if we register the
  // watcher after constructing ZooKeeper, we may miss that event. Instead,
  // we construct the watcher first, and have it block any events it receives
  // before we can set its ZooKeeper reference.
  watcher = new WatcherWithClientRef();
  ZooKeeper zk = new ZooKeeper(zkHostPort, zkSessionTimeout, watcher);
  watcher.setZooKeeperRef(zk);

  // Wait for the asynchronous success/failure. This may throw an exception
  // if we don't connect within the session timeout.
  watcher.waitForZKConnectionEvent(zkSessionTimeout);
  
  for (ZKAuthInfo auth : zkAuthInfo) {
    zk.addAuthInfo(auth.getScheme(), auth.getAuth());
  }
  return zk;
}
 
Example 7
Source File: ZKManager.java    From uncode-schedule with GNU General Public License v2.0 6 votes vote down vote up
private void createZookeeper(final CountDownLatch connectionLatch) throws Exception {
    zk = new ZooKeeper(this.properties.getProperty(keys.zkConnectString
            .toString()), Integer.parseInt(this.properties
            .getProperty(keys.zkSessionTimeout.toString())),
            new Watcher() {
                public void process(WatchedEvent event) {
                    sessionEvent(connectionLatch, event);
                }
            });
    String authString = this.properties.getProperty(keys.userName.toString())
            + ":"+ this.properties.getProperty(keys.password.toString());
    zk.addAuthInfo("digest", authString.getBytes());
    acl.clear();
    acl.add(new ACL(ZooDefs.Perms.ALL, new Id("digest",
            DigestAuthenticationProvider.generateDigest(authString))));
    acl.add(new ACL(ZooDefs.Perms.READ, Ids.ANYONE_ID_UNSAFE));
}
 
Example 8
Source File: ZookeeperTest.java    From uncode-schedule with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testCreateTask() throws Exception {
	ZooKeeper zk = new ZooKeeper("localhost:2181", 3000, null);
	List<ACL> acls = new ArrayList<ACL>();
	zk.addAuthInfo("digest", "ScheduleAdmin:password".getBytes());
	acls.add(new ACL(ZooDefs.Perms.ALL, new Id("digest",
			DigestAuthenticationProvider.generateDigest("ScheduleAdmin:password"))));
	acls.add(new ACL(ZooDefs.Perms.READ, Ids.ANYONE_ID_UNSAFE));
	zk.create("/uncode/schedule/task/taskObj#print", new byte[0], acls, CreateMode.PERSISTENT);
	zk.getData("/uncode/schedule/task/taskObj#print", false, null);
}
 
Example 9
Source File: ZookeeperTest.java    From uncode-schedule with Apache License 2.0 5 votes vote down vote up
@Test
public void deletePath() throws Exception {
  ZooKeeper zk = new ZooKeeper("localhost:2181", 3000, watcher);
  zk.addAuthInfo("digest", "ScheduleAdmin:123456".getBytes());

  ZKTools.deleteTree(zk, "/schedule/dev");

  Thread.sleep(10 * 1000);
  zk.close();
}
 
Example 10
Source File: DefaultZKClientService.java    From twill with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new ZooKeeper connection.
 */
private ZooKeeper createZooKeeper() throws IOException {
  ZooKeeper zk = new ZooKeeper(zkStr, sessionTimeout, wrapWatcher(this));
  for (Map.Entry<String, byte[]> authInfo : authInfos.entries()) {
    zk.addAuthInfo(authInfo.getKey(), authInfo.getValue());
  }
  return zk;
}
 
Example 11
Source File: TephraZKClientService.java    From phoenix-tephra with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new ZooKeeper connection.
 */
private ZooKeeper createZooKeeper() throws IOException {
  ZooKeeper zk = new ZooKeeper(zkStr, sessionTimeout, wrapWatcher(this));
  for (Map.Entry<String, byte[]> authInfo : authInfos.entries()) {
    zk.addAuthInfo(authInfo.getKey(), authInfo.getValue());
  }
  return zk;
}
 
Example 12
Source File: ZookeeperTest.java    From uncode-schedule with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void deletePath() throws Exception {
	ZooKeeper zk = new ZooKeeper("127.0.0.1:2181", 3000, null);
	zk.addAuthInfo("digest", "ScheduleAdmin:password".getBytes());
	ZKTools.deleteTree(zk, "/uncode/schedule/task/taskObj#print");
	//ZKTools.deleteTree(zk, "/uncode/schedule");
	StringWriter writer = new StringWriter();
	ZKTools.printTree(zk, "/", writer, "\n");
	System.out.println(writer.getBuffer().toString());
}
 
Example 13
Source File: ZookeeperTest.java    From tbschedule with Apache License 2.0 5 votes vote down vote up
@Test
public void testACL() throws Exception {
    ZooKeeper zk = new ZooKeeper("localhost:2181", 3000, new ScheduleWatcher(null));
    List<ACL> acls = new ArrayList<ACL>();
    zk.addAuthInfo("digest", "TestUser:password".getBytes());
    acls.add(new ACL(ZooDefs.Perms.ALL,
            new Id("digest", DigestAuthenticationProvider.generateDigest("TestUser:password"))));
    acls.add(new ACL(ZooDefs.Perms.READ, Ids.ANYONE_ID_UNSAFE));
    zk.create("/abc", new byte[0], acls, CreateMode.PERSISTENT);
    zk.getData("/abc", false, null);
}
 
Example 14
Source File: ZookeeperTest.java    From tbschedule with Apache License 2.0 5 votes vote down vote up
@Test
public void deletePath() throws Exception {
    ZooKeeper zk = new ZooKeeper("localhost:2181", 3000, new ScheduleWatcher(null));
    zk.addAuthInfo("digest", "ScheduleAdmin:password".getBytes());

    ZKTools.deleteTree(zk, "/taobao-pamirs-schedule");
    StringWriter writer = new StringWriter();
    ZKTools.printTree(zk, "/", writer, "\n");
    System.out.println(writer.getBuffer().toString());
}
 
Example 15
Source File: ZooKeeperMigrator.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
private ZooKeeper getZooKeeper(String zooKeeperConnectString, AuthMode authMode, byte[] authData) throws IOException {
    CountDownLatch connectionLatch = new CountDownLatch(1);
    ZooKeeper zooKeeper = new ZooKeeper(zooKeeperConnectString, 3000, watchedEvent -> {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("ZooKeeper server state changed to {} in {}", watchedEvent.getState(), zooKeeperConnectString);
        }
        if (watchedEvent.getType().equals(Watcher.Event.EventType.None) && watchedEvent.getState().equals(Watcher.Event.KeeperState.SyncConnected)) {
            connectionLatch.countDown();
        }
    });

    final boolean connected;
    try {
        connected = connectionLatch.await(5, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        closeZooKeeper(zooKeeper);
        Thread.currentThread().interrupt();
        throw new IOException(String.format("interrupted while waiting for ZooKeeper connection to %s", zooKeeperConnectString), e);
    }

    if (!connected) {
        closeZooKeeper(zooKeeper);
        throw new IOException(String.format("unable to connect to %s", zooKeeperConnectString));
    }

    if (authMode.equals(AuthMode.DIGEST)) {
        zooKeeper.addAuthInfo(SCHEME_DIGEST, authData);
    }
    return zooKeeper;
}
 
Example 16
Source File: ZooKeeperMigrator.java    From nifi with Apache License 2.0 5 votes vote down vote up
private ZooKeeper getZooKeeper(String zooKeeperConnectString, AuthMode authMode, byte[] authData) throws IOException {
    CountDownLatch connectionLatch = new CountDownLatch(1);
    ZooKeeper zooKeeper = new ZooKeeper(zooKeeperConnectString, 3000, watchedEvent -> {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("ZooKeeper server state changed to {} in {}", watchedEvent.getState(), zooKeeperConnectString);
        }
        if (watchedEvent.getType().equals(Watcher.Event.EventType.None) && watchedEvent.getState().equals(Watcher.Event.KeeperState.SyncConnected)) {
            connectionLatch.countDown();
        }
    });

    final boolean connected;
    try {
        connected = connectionLatch.await(5, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        closeZooKeeper(zooKeeper);
        Thread.currentThread().interrupt();
        throw new IOException(String.format("interrupted while waiting for ZooKeeper connection to %s", zooKeeperConnectString), e);
    }

    if (!connected) {
        closeZooKeeper(zooKeeper);
        throw new IOException(String.format("unable to connect to %s", zooKeeperConnectString));
    }

    if (authMode.equals(AuthMode.DIGEST)) {
        zooKeeper.addAuthInfo(SCHEME_DIGEST, authData);
    }
    return zooKeeper;
}
 
Example 17
Source File: Holder.java    From opensharding-spi-impl with Apache License 2.0 4 votes vote down vote up
protected void initZookeeper() throws IOException {
    zooKeeper = new ZooKeeper(context.getServers(), context.getSessionTimeOut(), startWatcher());
    if (!Strings.isNullOrEmpty(context.getScheme())) {
        zooKeeper.addAuthInfo(context.getScheme(), context.getAuth());
    }
}
 
Example 18
Source File: ZooKeeperClient.java    From distributedlog with Apache License 2.0 4 votes vote down vote up
@Override
public void authenticate(ZooKeeper zooKeeper) {
    zooKeeper.addAuthInfo("digest", String.format("%s:%s", username, password).getBytes(UTF_8));
}
 
Example 19
Source File: ZooKeeperClient.java    From distributedlog with Apache License 2.0 4 votes vote down vote up
@Override
public void authenticate(ZooKeeper zooKeeper) {
    zooKeeper.addAuthInfo("digest", String.format("%s:%s", username, password).getBytes(UTF_8));
}
 
Example 20
Source File: AuthDigestExample.java    From yuzhouwan with Apache License 2.0 4 votes vote down vote up
@Before
public void init() throws Exception {
    zoo = new ZooKeeper(HOST.concat(":" + CLIENT_PORT), TIME_OUT_MILLISECOND, null);
    zoo.addAuthInfo("digest", "yuzhouwan:com".getBytes());
    zooNoAuth = new ZooKeeper(HOST.concat(":" + CLIENT_PORT), TIME_OUT_MILLISECOND, null);
}