当前位置: 技术问答>java相关
谁能给些JAVA操纵LDAP的例子?
来源: 互联网 发布时间:2015-05-02
本文导语: 谢了。 | import javax.naming.*; import java.io.*; import java.util.*; /** * Interactive directory structure browser. */ public class Browser { /** * Main() is just a wrapper that starts the directory browsing. */ ...
谢了。
|
import javax.naming.*;
import java.io.*;
import java.util.*;
/**
* Interactive directory structure browser.
*/
public class Browser {
/**
* Main() is just a wrapper that starts the directory browsing.
*/
public static void main (String[] args) {
try {
new Browser().browse();
}catch (Exception e) {
System.err.println(e);
e.printStackTrace();
}
}
// Initial Context
protected Context ctx;
// This JNDI Name object is used to track the current
// context (folder) we're in as we traverse the directory tree
protected Name currName;
// We use a NameParser to generate Name objects for us.
// A NameParser knows how to construct a Name using
// a proprietary service provider syntax, such as
// "c:winnt" for the File System service provider, or
// "cn=Ed Roman, ou=People, o=Airius.com" for the LDAP
// service provider.
protected NameParser parser;
/*
* Constructor called from main(). Initializes things.
*/
public Browser() throws Exception {
/*
* 1) Create the initial context. Parameters are
* supplied in the System properties.
*/
ctx = new InitialContext(System.getProperties());
/*
* 2) Get the NameParser from the service provider.
*/
parser = ctx.getNameParser("");
/*
* 3) Use the NameParser to create the initial location
* of where we are in the directory structure. Since
* the NameParser is service provider specific, the
* resulting Name object will be formatted to a
* specific directory syntax.
*/
currName = parser.parse("");
}
/**
* Call to begin browsing the file system directory structure.
* This method isn't important, it just interacts with the user.
*/
public void browse() {
/*
* Start reading input from standard input
*/
String line = null, command = null, args = null;
StringTokenizer tokens = null;
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
while (true) {
/*
* Print prompt, read next input line,
* and get command
*/
try {
System.out.println();
System.out.print(currName + "> ");
line = reader.readLine();
System.out.println();
tokens =
new StringTokenizer(line, " ", false);
// Get command. e.g. "cd" in "cd .."
command = tokens.nextToken();
// Get arguments. e.g. ".." in "cd .."
if (tokens.hasMoreElements()) {
args = line.substring(
command.length()+1,
line.length());
}
}
catch (Exception e) {
continue;
}
/*
* Do case analysis based upon command. Call
* the corresponding JNDI function.
*/
try {
if (command.equals("ls")) {
ls();
}
else if (command.equals("mv")) {
/*
* Figure out the name of the
* context the user is trying
* to rename (mv)
*/
String oldStr = null,
newStr = null;
try {
StringTokenizer argtokens = new StringTokenizer(args, " ", false);
oldStr = argtokens.nextToken();
newStr = argtokens.nextToken();
}
catch (Exception e) {
throw new Exception("Syntax: mv ");
}
mv(oldStr, newStr);
}
else if (command.equals("cd")) {
cd(args);
}
else if (command.equals("mkdir")) {
mkdir(args);
}
else if (command.equals("rmdir")) {
rmdir(args);
}
else if (command.equals("cat")) {
cat(args);
}
else if (command.equals("quit")) {
System.exit(0);
}
else {
System.out.println("Syntax: [ls|mv|cd|mkdir|rmdir|cat|quit] [args...]");
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Lists the contents of the current context (folder)
*/
private void ls() throws Exception {
// Get an enumeration of Names bound to this context
NamingEnumeration e = ctx.list(currName);
// Each enumeration element is a NameClassPair.
// Print the Name part.
while (e.hasMore()) {
NameClassPair p = (NameClassPair) e.next();
System.out.println(p.getName());
}
}
/**
* Navigate the directory structure
*/
private void cd(String newLoc) throws Exception {
if (newLoc == null) {
throw new Exception("You must specify a folder");
}
// Save the old Name, in case the user tries to cd
// into a bad folder.
Name oldName = (Name) currName.clone();
try {
/*
* If the user typed "cd ..", pop up one
* directory by removing the last element from
* the Name.
*/
if (newLoc.equals("..")) {
if (currName.size() > 0) {
currName.remove(currName.size()-1);
}
else {
System.out.println(
"Already at top level.");
}
}
/*
* Otherwise, the user typed "cd ". Go
* deeper into the directory structure.
*
* Note that we use "addAll()" which will add every
* atomic folder name into the total name. This means
* when we type "cd .." later, we will only traverse
* down one folder.
*/
else {
currName.addAll(parser.parse(newLoc));
}
/*
* Confirm our traversal by trying to do a lookup()
* operation after we've popped out a directory. If
* lookup() fails, we need to restore the directory
* Name to what it was, and throw an exception.
*/
ctx.lookup(currName);
}
catch (Exception e) {
currName = oldName;
throw new Exception("Cannot traverse to desired directory: " + e.toString());
}
}
/**
* Renames (moves) one context to a new name.
*
* @param oldStr the old context
* @param newStr the new context
*/
private void mv(String oldStr, String newStr) throws Exception {
/*
* Navigate to the current context (folder)
*/
Context currCtx = (Context) ctx.lookup(currName);
/*
* Rename the subcontext
*/
currCtx.rename(oldStr, newStr);
}
/**
* Makes a subfolder (subcontext)
*/
private void mkdir(String str) throws Exception {
Context currCtx = (Context) ctx.lookup(currName);
currCtx.createSubcontext(str);
}
/**
* Removes a subfolder (subcontext)
*/
private void rmdir(String str) throws Exception {
Context currCtx = (Context) ctx.lookup(currName);
currCtx.destroySubcontext(str);
}
/**
* displays a file (specific to File System service provider)
*/
private void cat(String fileStr) throws Exception {
/*
* Append the filename to the folder string
*/
Name fileName = (Name) currName.clone();
fileName.addAll(parser.parse(fileStr));
/*
* Use JNDI to get a File Object reference
*/
File f = (File) ctx.lookup(fileName);
/*
* Print out file contents
*/
FileReader fin = new FileReader(f);
Writer out = new PrintWriter(System.out);
char[] buf = new char[512];
int howmany;
while ((howmany = fin.read(buf)) >= 0) {
out.write(buf, 0, howmany);
}
out.flush();
fin.close();
}
}
import java.io.*;
import java.util.*;
/**
* Interactive directory structure browser.
*/
public class Browser {
/**
* Main() is just a wrapper that starts the directory browsing.
*/
public static void main (String[] args) {
try {
new Browser().browse();
}catch (Exception e) {
System.err.println(e);
e.printStackTrace();
}
}
// Initial Context
protected Context ctx;
// This JNDI Name object is used to track the current
// context (folder) we're in as we traverse the directory tree
protected Name currName;
// We use a NameParser to generate Name objects for us.
// A NameParser knows how to construct a Name using
// a proprietary service provider syntax, such as
// "c:winnt" for the File System service provider, or
// "cn=Ed Roman, ou=People, o=Airius.com" for the LDAP
// service provider.
protected NameParser parser;
/*
* Constructor called from main(). Initializes things.
*/
public Browser() throws Exception {
/*
* 1) Create the initial context. Parameters are
* supplied in the System properties.
*/
ctx = new InitialContext(System.getProperties());
/*
* 2) Get the NameParser from the service provider.
*/
parser = ctx.getNameParser("");
/*
* 3) Use the NameParser to create the initial location
* of where we are in the directory structure. Since
* the NameParser is service provider specific, the
* resulting Name object will be formatted to a
* specific directory syntax.
*/
currName = parser.parse("");
}
/**
* Call to begin browsing the file system directory structure.
* This method isn't important, it just interacts with the user.
*/
public void browse() {
/*
* Start reading input from standard input
*/
String line = null, command = null, args = null;
StringTokenizer tokens = null;
BufferedReader reader =
new BufferedReader(new InputStreamReader(System.in));
while (true) {
/*
* Print prompt, read next input line,
* and get command
*/
try {
System.out.println();
System.out.print(currName + "> ");
line = reader.readLine();
System.out.println();
tokens =
new StringTokenizer(line, " ", false);
// Get command. e.g. "cd" in "cd .."
command = tokens.nextToken();
// Get arguments. e.g. ".." in "cd .."
if (tokens.hasMoreElements()) {
args = line.substring(
command.length()+1,
line.length());
}
}
catch (Exception e) {
continue;
}
/*
* Do case analysis based upon command. Call
* the corresponding JNDI function.
*/
try {
if (command.equals("ls")) {
ls();
}
else if (command.equals("mv")) {
/*
* Figure out the name of the
* context the user is trying
* to rename (mv)
*/
String oldStr = null,
newStr = null;
try {
StringTokenizer argtokens = new StringTokenizer(args, " ", false);
oldStr = argtokens.nextToken();
newStr = argtokens.nextToken();
}
catch (Exception e) {
throw new Exception("Syntax: mv ");
}
mv(oldStr, newStr);
}
else if (command.equals("cd")) {
cd(args);
}
else if (command.equals("mkdir")) {
mkdir(args);
}
else if (command.equals("rmdir")) {
rmdir(args);
}
else if (command.equals("cat")) {
cat(args);
}
else if (command.equals("quit")) {
System.exit(0);
}
else {
System.out.println("Syntax: [ls|mv|cd|mkdir|rmdir|cat|quit] [args...]");
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Lists the contents of the current context (folder)
*/
private void ls() throws Exception {
// Get an enumeration of Names bound to this context
NamingEnumeration e = ctx.list(currName);
// Each enumeration element is a NameClassPair.
// Print the Name part.
while (e.hasMore()) {
NameClassPair p = (NameClassPair) e.next();
System.out.println(p.getName());
}
}
/**
* Navigate the directory structure
*/
private void cd(String newLoc) throws Exception {
if (newLoc == null) {
throw new Exception("You must specify a folder");
}
// Save the old Name, in case the user tries to cd
// into a bad folder.
Name oldName = (Name) currName.clone();
try {
/*
* If the user typed "cd ..", pop up one
* directory by removing the last element from
* the Name.
*/
if (newLoc.equals("..")) {
if (currName.size() > 0) {
currName.remove(currName.size()-1);
}
else {
System.out.println(
"Already at top level.");
}
}
/*
* Otherwise, the user typed "cd ". Go
* deeper into the directory structure.
*
* Note that we use "addAll()" which will add every
* atomic folder name into the total name. This means
* when we type "cd .." later, we will only traverse
* down one folder.
*/
else {
currName.addAll(parser.parse(newLoc));
}
/*
* Confirm our traversal by trying to do a lookup()
* operation after we've popped out a directory. If
* lookup() fails, we need to restore the directory
* Name to what it was, and throw an exception.
*/
ctx.lookup(currName);
}
catch (Exception e) {
currName = oldName;
throw new Exception("Cannot traverse to desired directory: " + e.toString());
}
}
/**
* Renames (moves) one context to a new name.
*
* @param oldStr the old context
* @param newStr the new context
*/
private void mv(String oldStr, String newStr) throws Exception {
/*
* Navigate to the current context (folder)
*/
Context currCtx = (Context) ctx.lookup(currName);
/*
* Rename the subcontext
*/
currCtx.rename(oldStr, newStr);
}
/**
* Makes a subfolder (subcontext)
*/
private void mkdir(String str) throws Exception {
Context currCtx = (Context) ctx.lookup(currName);
currCtx.createSubcontext(str);
}
/**
* Removes a subfolder (subcontext)
*/
private void rmdir(String str) throws Exception {
Context currCtx = (Context) ctx.lookup(currName);
currCtx.destroySubcontext(str);
}
/**
* displays a file (specific to File System service provider)
*/
private void cat(String fileStr) throws Exception {
/*
* Append the filename to the folder string
*/
Name fileName = (Name) currName.clone();
fileName.addAll(parser.parse(fileStr));
/*
* Use JNDI to get a File Object reference
*/
File f = (File) ctx.lookup(fileName);
/*
* Print out file contents
*/
FileReader fin = new FileReader(f);
Writer out = new PrintWriter(System.out);
char[] buf = new char[512];
int howmany;
while ((howmany = fin.read(buf)) >= 0) {
out.write(buf, 0, howmany);
}
out.flush();
fin.close();
}
}