-6

I have a little problem with Attributes. I am currently working on a project that parses emails from an LDAP server into the Java application that will be doing some interesting stuff with emails in the future.

I am currently having this code that takes emails from users on LDAP and it needs to put emails in the User class as seen in my code:

     [some code here, TRY CATCH is also included]


        LdapContext ctx = new InitialLdapContext(env, null);
                ctx.setRequestControls(null);
       NamingEnumeration<?> namingEnum2 = ctx.search("[path to the server]", "(objectClass=user)", getSimpleSearchControls());


    System.out.println("Test: print emails from whole DIRECOTRY: \n");


    while (namingEnum2.hasMore()) {

        SearchResult result = (SearchResult) namingEnum2.next();
        Attributes attrs = result.getAttributes();

         System.out.println(attrs.get("mail"));
         /** This line above works fine, but every time there is no email
             in User info, it prints "null" in some cases when there is
             no email, which is not perfect. But this is just here to see
             if everything works and indeed it does.**/

         /**User Class accepts a String parameter, checks if it's empty
            and all that, does some checking and etc... BUT! attrs.get("mail")
            is an Attribute, NOT a String. And I need to somehow "cast" this
            attribute to a String, so I can work with it.**/
        User user = new User(attrs.get("mail")); //error yet,because the parameter is not a String.

        User user = new User(attrs.get("mail").toString());//gives an expeption.

        /** And I know that there is a toString() method in Attribute Class,
            but it doesn't work, it gives an "java.lang.NullPointerException"
            exception when I use it as attrs.get("mail").toString() **/
    }

Here is User class's constructor:

public User(String mail){
        eMail = "NO EMAIL!";
        if (mail != null && !mail.isEmpty()){


            eMail = mail;
        }
        else
        {


           eMail = "NO EMAIL!";
        }


    }
halfer
  • 19,824
  • 17
  • 99
  • 186
  • 4
    Could you format your code readably so that it has consistent indentation and doesn't have loads of arbitrary blank lines? It currently looks like it was dropped on the floor. – khelwood Jul 20 '16 at 12:36
  • .toString() is giving exception because attrs.get("mail") is returning null itself – Loki Jul 20 '16 at 12:39
  • Why my question's rating is so down btw? It's not like it a super dumb question like "how to print out "Hello World" in console in JavaScript or Java, same thing lul". The formating of my code is not perfect, yet still readable. there were a lot of comments by other fellow programmers in Russian that I had to delete, so you guys don't mind them. Did I do something wrong in asking my qestion? – Doom Dooms Jul 20 '16 at 13:00
  • 1
    Some suggestions for avoiding negative reactions to your questions: 1) put in the effort to format your code properly (not just bearably); 2) post a [minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) instead of fragments of code; 3) Post the stack trace of any exceptions; 4) Describe your problems clearly in your question, not hidden in comments inside the code. Not doing those things is offloading effort from yourself onto the people you are asking for help. – khelwood Jul 20 '16 at 13:12
  • @khelwood Ok, it makes sense. – Doom Dooms Jul 20 '16 at 13:54
  • Also, all of this is unnecessary: `Please help me solve this problem, I have a deadline, I am still a Junior developer, and I am really trying to get it done`. Engineers like succinctness, so if they see those four clauses, they see four chatty attempts to hurry or beg volunteers. See [this discussion](http://meta.stackoverflow.com/q/326569/472495) about adding this sort of material into posts. – halfer Jul 20 '16 at 20:10

2 Answers2

1

try this

User user = new User(attrs.get("mail")!=null?attrs.get("mail").toString():null);
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
Loki
  • 801
  • 5
  • 13
  • 2
    [`Objects.toString(attrs.get("mail"))`](https://docs.oracle.com/javase/7/docs/api/java/util/Objects.html#toString(java.lang.Object)) does roughly the same as your ternary statement (it doesn't call `attrs.get` twice). – Andy Turner Jul 20 '16 at 12:43
  • Indeed it worked! Could you explain why it worked? It's the first time I have to work with Attributes in general, so I probably look dumb – Doom Dooms Jul 20 '16 at 12:48
  • It was not working because attrs.get("mail") was returning null and you cannot invoke toString() method on null.So for null value , null is passed to User object. – Loki Jul 20 '16 at 12:49
0

First you need to check that given attribute exists by using != null (e.g. using Objects.toString which does that inside, or manual if) check, and then use either toString on the Attribute, just like println does inside:

User user = new User(Objects.toString(attrs.get("mail")));

Or you can also use (to retrieve a single value in the attribute, if you have many you need to use getAll):

Object mail = null;
if (attrs.get("mail") != null) {
    mail = attrs.get("mail").get();
}
User user = new User(mail.toString());
Krzysztof Krasoń
  • 26,515
  • 16
  • 89
  • 115
  • It gives me this stuff: java.lang.NullPointerException at LdapConnection.main(LdapConnection.java:77) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147) – Doom Dooms Jul 20 '16 at 12:37
  • Relying on the implementation of toString is not a good idea. What if it changes? – Mark Chorley Jul 20 '16 at 12:38
  • @MarkChorley What other option you have if `get()` returns an Object? – Krzysztof Krasoń Jul 20 '16 at 12:45
  • @DoomDooms You need to check for null also, added that to answer – Krzysztof Krasoń Jul 20 '16 at 12:49