File: SchemaViewer.java

package info (click to toggle)
libspring-ldap-java 1.3.1.RELEASE-4
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 2,876 kB
  • sloc: java: 12,509; xml: 4,104; jsp: 36; makefile: 31; sh: 13
file content (233 lines) | stat: -rw-r--r-- 9,143 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
package org.springframework.ldap.odm.tools;

import java.io.PrintStream;
import java.util.Hashtable;

import javax.naming.AuthenticationException;
import javax.naming.CommunicationException;
import javax.naming.Context;
import javax.naming.NameClassPair;
import javax.naming.NameNotFoundException;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;

/**
 * A simple utility to list LDAP directory schema.
 * <p>
 * <code>SchemaViewer</code> takes the following flags:
 * <ul>
 * <li><code>-h,--help&lt;</code>                Print this help message</li>
 * <li><code>-l,--url &lt;arg></code>           Ldap url of directory to bind to (defaults to ldap://127.0.0.1:389)</li>
 * <li><code>-u,--username &lt;arg></code>      DN to bind with (defaults to "")</li>
 * <li><code>-p,--password &lt;arg></code>      Password to bind with (defaults to "")</li>
 * <li><code>-o,--objectclass &lt;arg></code>   Object class name or ? for all. Print object class schema</li>
 * <li><code>-a,--attribute &lt;arg></code>     Attribute name or ? for all. Print attribute schema</li>
 * <li><code>-s,--syntax &lt;arg></code>        Syntax or ? for all. Print syntax</li>
 * </ul>
 * 
 * Only one of <code>-a</code>, <code>-o</code> and <code>-s</code> should be specified.
 * 
 * @author Paul Harvey &lt;paul.at.pauls-place.me.uk>
 *
 */
public final class SchemaViewer {
    private static final String DEFAULT_URL="ldap://127.0.0.1:389";
    
    private enum Flag {
        URL("l", "url"),
        USERNAME("u", "username"),
        PASSWORD("p", "password"),
        OBJECTCLASS("o", "objectclass"),
        ATTRIBUTE("a", "attribute"),
        SYNTAX("s", "syntax"),
        HELP("h", "help"),
        ERROR("e", "error");

        private String shortName;

        private String longName;

        private Flag(String shortName, String longName) {
            this.shortName = shortName;
            this.longName = longName;
        }

        public String getShort() {
            return shortName;
        }

        public String getLong() {
            return longName;
        }

        @Override
        public String toString() {
            return String.format("short=%1$s, long=%2$s", shortName, longName);
        }
    }

    private enum SchemaContext {
        OBJECTCLASS("ClassDefinition"), ATTRIBUTE("AttributeDefinition"), SYNTAX("SyntaxDefinition");

        private String value;

        private SchemaContext(String value) {
            this.value = value;
        }

        public String getValue() {
            return value;
        }

        @Override
        public String toString() {
            return String.format("value=%1$s", value);
        }
    }

    private static final Options options = new Options();
    static {
        options.addOption(Flag.URL.getShort(), Flag.URL.getLong(), true, "Ldap url (defaults to "+DEFAULT_URL+")");
        options.addOption(Flag.USERNAME.getShort(), Flag.USERNAME.getLong(), true, "DN to bind with (defaults to \"\")");
        options.addOption(Flag.PASSWORD.getShort(), Flag.PASSWORD.getLong(), true, "Password to bind with defaults to \"\")");
        options.addOption(Flag.OBJECTCLASS.getShort(), Flag.OBJECTCLASS.getLong(), true,
                "Object class name or ? for all. Print object class schema");
        options.addOption(Flag.ATTRIBUTE.getShort(), Flag.ATTRIBUTE.getLong(), true,
                "Attribute name or ? for all. Print attribute schema");
        options.addOption(Flag.SYNTAX.getShort(), Flag.SYNTAX.getLong(), true,
                "Syntax OID or ? for all. Print attribute syntax");
        options.addOption(Flag.HELP.getShort(), Flag.HELP.getLong(), false, "Print this help message");
        options.addOption(Flag.ERROR.getShort(), Flag.ERROR.getLong(), false, "Send output to standard error");
    }

    private static void printAttrs(Attributes attrs) throws NamingException {
        NamingEnumeration<? extends Attribute> attrsEnum = attrs.getAll();
        while (attrsEnum.hasMore()) {
            Attribute currentAttr = attrsEnum.next();
            outstream.print(String.format("%1$s:", currentAttr.getID()));
            NamingEnumeration<?> valuesEnum = currentAttr.getAll();
            while (valuesEnum.hasMoreElements()) {
                outstream.print(String.format("%1$s ", valuesEnum.nextElement().toString()));
            }
            outstream.println();
        }
    }

    private static void printObject(String contextName, String schemaName, DirContext schemaContext)
            throws NameNotFoundException, NamingException {

        DirContext oContext = (DirContext)schemaContext.lookup(contextName + "/" + schemaName);

        outstream.println("NAME:" + schemaName);
        printAttrs(oContext.getAttributes(""));
    }
    
    private static void printSchema(String contextName, DirContext schemaContext) throws NameNotFoundException,
            NamingException {

        outstream.println();

        NamingEnumeration<NameClassPair> schemaList = schemaContext.list(contextName);

        while (schemaList.hasMore()) {
            NameClassPair ncp = schemaList.nextElement();

            printObject(contextName, ncp.getName(), schemaContext);
            outstream.println();
        }

        outstream.println();
    }

    private static void print(String optionValue, String contextName, DirContext schemaContext)
            throws NameNotFoundException, NamingException {

        if (optionValue.equals(WILDCARD)) {
            printSchema(contextName, schemaContext);
        } else {
            printObject(contextName, optionValue, schemaContext);
        }
    }

    private static PrintStream outstream=System.out;
    private static String WILDCARD = "?";

    public static void main(String[] argv) {
        CommandLineParser parser = new PosixParser();
        CommandLine cmd = null;

        try {
            cmd = parser.parse(options, argv);
        } catch (ParseException e) {
            System.out.println(e.getMessage());
            System.exit(1);
        }

        if (cmd.hasOption(Flag.HELP.getShort())) {
            HelpFormatter formatter = new HelpFormatter();

            formatter.printHelp(120, SchemaViewer.class.getSimpleName(), null, options, null, true);
            System.exit(0);
        }

        if (cmd.hasOption(Flag.ERROR.getShort())) {
            outstream=System.err;
        }
        
        String url = cmd.getOptionValue(Flag.URL.getShort(), DEFAULT_URL);
        String user = cmd.getOptionValue(Flag.USERNAME.getShort(), "");
        String pass = cmd.getOptionValue(Flag.PASSWORD.getShort(), "");

        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.PROVIDER_URL, url);
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        if (user != null) {
            env.put(Context.SECURITY_PRINCIPAL, user);
        }
        if (pass != null) {
            env.put(Context.SECURITY_CREDENTIALS, pass);
            if (user == null) {
                System.err.println("You must specify a user if you specify a password");
                System.exit(1);
            }
        }

        try {
            DirContext context = new InitialDirContext(env);
            DirContext schemaContext = context.getSchema("");

            if (cmd.hasOption(Flag.OBJECTCLASS.getShort())) {
                print(cmd.getOptionValue(Flag.OBJECTCLASS.getShort()), SchemaContext.OBJECTCLASS.getValue(),
                        schemaContext);
            }

            if (cmd.hasOption(Flag.ATTRIBUTE.getShort())) {
                print(cmd.getOptionValue(Flag.ATTRIBUTE.getShort()), SchemaContext.ATTRIBUTE.getValue(), schemaContext);
            }

            if (cmd.hasOption(Flag.SYNTAX.getShort())) {
                print(cmd.getOptionValue(Flag.SYNTAX.getShort()), SchemaContext.SYNTAX.getValue(), schemaContext);
            }

        } catch (AuthenticationException e) {
            System.err.println(String.format("Failed to bind to ldap server at %1$s", url));
        } catch (CommunicationException e) {
            System.err.println(String.format("Failed to contact ldap server at %1$s", url));
        } catch (NameNotFoundException e) {
            System.err.println(String.format("Can't find object %1$s", e.getMessage()));
        } catch (NamingException e) {
            System.err.println(e.toString());
        }
    }
}