How to get "supportedControl" from LDAP with com.novell.ldap - java

I want to get value from control oid from LDAP: For example when I use Linux ldapsearch:
ldapsearch -H ldap://host:port -x -wsecret -D "cn=manager,managedElementId=HSS1"
-b "dn" "objectClass=ConfigOAM" -E"1.3.6.1.4.1.637.81.2.10.10"
I get results:
...
**control: 1.3.6.1.4.1.637.81.2.10.10 false AgEB**
objectClass: top
objectClass: ConfigOAM
confOAMId: 1
...
My java code looks:
LDAPConnection connection = new LDAPConnection();
connection.connect(hostName, port);
connection.bind(LDAPConnection.LDAP_V3, userDN, password);
String returnedAttributes[] = {"+", "*"};
boolean attributeOnly = false;
String oid;
LDAPSearchResults results = connection.search("", LDAPConnection.SCOPE_BASE, "(objectClass=*)", returnedAttributes, attributeOnly);
LDAPEntry entry = results.next();
System.out.println("\n" + entry.getDN());
System.out.println(" Attributes: ");
LDAPAttributeSet attributeSet = entry.getAttributeSet();
Iterator allAttributes = attributeSet.iterator();
while(allAttributes.hasNext()) {
LDAPAttribute attribute = (LDAPAttribute)allAttributes.next();
String attrName = attribute.getName();
System.out.println(" " + attrName);
Enumeration allValues = attribute.getStringValues();
while(allValues.hasMoreElements()) {
oid = (String) allValues.nextElement();
if ( (attrName.equalsIgnoreCase("supportedExtension")) || (attrName.equalsIgnoreCase("supportedControl"))) {
System.out.println(" " + oid);
}
}
}
and the result is:
...
supportedControl
2.16.840.1.113730.3.4.2
1.2.840.113556.1.4.319
1.2.826.0.1.3344810.2.3
1.3.6.1.1.12
1.3.6.1.4.1.637.81.2.10.11
**1.3.6.1.4.1.637.81.2.10.10**
1.3.6.1.4.1.637.81.2.10.9
1.3.6.1.4.1.637.81.2.10.6
...
Please suggest me or advice how can I get the additional value "false AgEB" in java as I get it in ldapsearch?

You would need to add the control to the search request and be able to interpret the response.
There are soem examples available:
http://www.novell.com/documentation/developer/samplecode/jldap_sample/
-jim

Thank you for your answer :)
I made something like this from samples available on this site and from others soruces:
lc.connect( ldapHost, ldapPort );
lc.bind( ldapVersion, loginDN, password.getBytes("UTF8"));
LDAPControl ldapCtrl = new LDAPControl("1.3.6.1.4.1.637.81.2.10.10", false, null);
LDAPSearchConstraints cons = lc.getSearchConstraints();
cons.setControls( ldapCtrl );
lc.setConstraints(cons);
LDAPSearchResults searchResults = lc.search("",LDAPConnection.SCOPE_BASE, "(objectclass=*)", returnedAttributes,attributeOnly , cons);
LDAPControl[] controls = searchResults.getResponseControls();
but my "controls" varaible is always null, even if supportedControls are listed
LDAPEntry entry1 = searchResults.next();
System.out.println("\n" + entry1.getDN());
System.out.println(" Attributes: ");
LDAPAttributeSet attributeSet1 = entry1.getAttributeSet();
Iterator allAttributes1 = attributeSet1.iterator();
while(allAttributes1.hasNext()) {
LDAPAttribute attribute = (LDAPAttribute)allAttributes1.next();
String attrName = attribute.getName();
System.out.println(" " + attrName);
Enumeration allValues1 = attribute.getStringValues();
while(allValues1.hasMoreElements()) {
oid = (String) allValues1.nextElement();
if ( (attrName.equalsIgnoreCase("supportedExtension")) || (attrName.equalsIgnoreCase("supportedControl"))) {
System.out.println(" " + oid);
}
}
}
Maybe the searchResults options are wrong?

Related

Pass field/attributes values from java to RTC using JAZZ API's

I am trying to create work item in RTC through java application using the jazz api's.
My connection to the repository is successful. Now i need to set all the required fields through java code in order to save/run the workitem. Really dont know how to set those values in below codes.
String repositoryURI= args[0];
String userId= args[1];
String password= args[2];
String projectAreaName= args[3];
String typeIdentifier= args[4];
String summary= args[5];
String categoryName= args[6];
ITeamRepository teamRepository= TeamPlatform.getTeamRepositoryService().getTeamRepository(repositoryURI);
teamRepository.registerLoginHandler(new LoginHandler(userId, password));
teamRepository.login(null);
IProcessClientService processClient= (IProcessClientService) teamRepository.getClientLibrary(IProcessClientService.class);
IAuditableClient auditableClient= (IAuditableClient) teamRepository.getClientLibrary(IAuditableClient.class);
IWorkItemClient workItemClient= (IWorkItemClient) teamRepository.getClientLibrary(IWorkItemClient.class);
URI uri= URI.create(projectAreaName.replaceAll(" ", "%20"));
IProjectAreaHandle projectArea= (IProjectAreaHandle) processClient.findProcessArea(uri, null, null);
//IProjectAreaHandle projectArea = teamArea.getProjectArea();
if (projectArea == null) {
System.out.println("Project area not found.");
return false;
}
//IWorkItemType workItemType = service.findWorkItemType(projectArea, "defect", monitor);
IWorkItemType workItemType= workItemClient.findWorkItemType((IProjectAreaHandle) projectArea, typeIdentifier, null);
// findWorkItemType(projectArea, typeIdentifier, null);
if (workItemType == null) {
System.out.println("Work item type not found.");
return false;
}
System.out.println("Category not found.: " + categoryName );
List path= Arrays.asList(categoryName.split("/"));
System.out.println("Category not found.: " + path );
ICategoryHandle category= workItemClient.findCategoryByNamePath((IProjectAreaHandle) projectArea, path, null);
//ICategoryHandle category=
if (category == null) {
System.out.println("Category not found.: " + category );
return false;
}
WorkItemInitialization operation= new WorkItemInitialization(summary, category);
IWorkItemHandle handle= operation.run(workItemType, null);
IWorkItem workItem= auditableClient.resolveAuditable(handle, IWorkItem.FULL_PROFILE, null);
System.out.println("Created work item " + workItem.getId() + ".");
teamRepository.logout();
While running the codes i am receiving the below errors. Because of mandatory fields are not assigned. Can any one help me to pass the attribute values (Contact Phone) from java to jazz.
ERROR received:
Severity: ERROR
Summary: Attribute 'Contact Phone #' not set
Description: The 'Contact Phone #' attribute needs to be set (work item <09:13:03>).

How to check if a user is in an LDAP group

Problem
I want to see if user "john" is in group "Calltaker". I can't seem to get the syntax right on my search filter to check for a specific user in a specific group. I can list all users in a group to verify the desired user is there.
Questions
What is the right syntax for a ldap search filter to determine if a specific user is in a specific group(in Tivoli Access Manager)?
What should I check on the returned LDAPEntry object given by that search string to see that the user is, or isn't, in the group?
Info
john is defined in "cn=users,dc=ldap,dc=net"
Calltaker is defined in "cn=groups,dc=ldap,dc=net"
I'm querying against TAM's ldap, from java
Using the searchfilter to be "cn=Calltaker" I can print out the search results such that calling nextEntry.toString contains the list of users. See Example 1 below
Here's a few searchfilters I've tried that don't work (aka searchResults.next() throws an error):
(&(objectclass=groupOfUniqueName)(uniquemember=uid="+ username + ",cn=groups,dc=ldap,dc=net))
(&(objectclass=groupOfUniqueName)(uniquemember=uid="+ username + ",cn=users,dc=ldap,dc=net))
(uniquemember=uid="+ username + ",cn=users,dc=ldap,dc=net)
Example 1) only search group, using searchFilter="cn=Calltaker", verify it contains users:
System.out.println(nextEntry.toString()); //added newlines for readability
nextEntry:
LDAPEntry:
cn=Calltaker,cn=groups,dc=ldap,dc=net;
LDAPAttributeSet:
LDAPAttribute: {type='objectclass', values='groupOfUniqueNames','top'}
LDAPAttribute: {type='uniquemember',
values=
'uid=placeholder,cn=users,dc=ldap,dc=net',
'secAuthority=default',
'uid=john,cn=users,dc=ldap,dc=net',
'uid=sally,cn=users,dc=ldap,dc=net', ....etc
Code:
public boolean isUserInGroup(username){
boolean userInGroup = false;
String loginDN = "uid=" + admin_username + "," + "cn=users,dc=ldap,dc=net";
String searchBase = "cn=groups,dc=ldap,dc=net";
int searchScope = LDAPConnection.SCOPE_SUB;
searchFilter = "(&(objectclass=ePerson)(uniquemember=uid="+ username + ",cn=users,dc=ldap,dc=net))";
//Connect
LDAPConnection lc = connect(hosts);
lc.bind(LDAPConnection.LDAP_V3, loginDN, admin_password.getBytes("UTF8"));
lc.getAuthenticationDN();
LDAPSearchResults searchResults = lc.search(searchBase,
searchScope,
searchFilter,
null, // return all attributes
false); // return attrs and values
while (searchResults.hasMore()) {
LDAPEntry nextEntry = null;
try {
nextEntry = searchResults.next();
} catch (LDAPException e) {
// Exception is thrown, go for next entry
if (e.getResultCode() == LDAPException.LDAP_TIMEOUT || e.getResultCode() == LDAPException.CONNECT_ERROR)
break;
else
continue;
}
//TODO some check to verify nextEntry shows the user in the group
userInGroup = true;
LDAPAttributeSet attributeSet = nextEntry.getAttributeSet();
Iterator<LDAPAttribute> allAttributes = attributeSet.iterator();
while (allAttributes.hasNext()) {
LDAPAttribute attribute = (LDAPAttribute) allAttributes.next();
String attributeName = attribute.getName();
System.out.println("found attribute '" + attributeName + "' with value '" + attribute.getStringValue() + "'");
}
}
lc.disconnect();
return userInGroup;
}
** EDIT **
Implemented answer from EJP, changed searchBase to include group
Code that works:
private static final String admin_username = "foo";
private static final String[] hosts = new String[]{"foohost.net"};
public boolean isUserInGroup(String username, String group){
boolean userInGroup = false;
String loginDN = "uid=" + admin_username + "," + "cn=users,dc=ldap,dc=net";
String searchBase = "cn=" + group + "," + "cn=groups,dc=ldap,dc=net";
int searchScope = LDAPConnection.SCOPE_SUB;
searchFilter = "(&(objectclass=groupOfUniqueNames)(uniquemember=uid="+ username + ",cn=users,dc=ldap,dc=net))";
//Connect
LDAPConnection lc = connect(hosts);
lc.bind(LDAPConnection.LDAP_V3, loginDN, admin_password.getBytes("UTF8"));
lc.getAuthenticationDN();
LDAPSearchResults searchResults = lc.search(searchBase,
searchScope,
searchFilter,
null, // return all attributes
false); // return attrs and values
while (searchResults.hasMore()) {
LDAPEntry nextEntry = null;
try {
nextEntry = searchResults.next();
} catch (LDAPException e) {
// Exception is thrown, go for next entry
if (e.getResultCode() == LDAPException.LDAP_TIMEOUT || e.getResultCode() == LDAPException.CONNECT_ERROR)
break;
else
continue;
}
//A result was found, therefore the user is in the group
userInGroup = true;
}
lc.disconnect();
return userInGroup;
}
What is the right syntax for a ldap search filter to determine if a specific user is in a specific group(in Tivoli Access Manager)?
Either of the filters you used, but the objectClass to search on is groupofUniqueNames (plural).
What should I check on the returned LDAPEntry object given by that search string to see that the user is, or isn't, in the group?
Nothing. He will be, otherwise the group won't be returned in the search. All you need to do is check that the search result is non-empty.
Here's a few searchfilters I've tried that don't work (aka searchResults.next() throws an error):
Throws what error?
(&(objectclass=groupOfUniqueName)(uniquemember=uid="+ username + ",cn=groups,dc=ldap,dc=net))
Nothing wrong with this except for groupOfUniqueName. You should use search filter arguments like {0} rather than building them into the search string.
(&(objectclass=groupOfUniqueName)(uniquemember=uid="+ username + ",cn=users,dc=ldap,dc=net))
This one will search the cn=users subtree for a group. It won't work unless you have groups under cn=users, which doesn't seem likely.
(uniquemember=uid="+ username + ",cn=users,dc=ldap,dc=net)
This will select non-groups. You don't want that: you need the objectClass part.

Deserializing Gson NullPointer?

I am trying to parse JSON to get some values.
{
"username":"shobhit#gmail.com",
"roles:
{
"ROLE_Student_Trial":true,
"ROLE_student":true,
"ROLE_Student_Unlimited":true
},
"type":"student",
"lastLogin":1441305986000,
"token":"123"
}
This is how I am deSerializing it
JsonObject obj = new JsonParser().parse(jsonString).getAsJsonObject();
String userName = obj.get("username").getAsString();
JsonObject roles = obj.get("roles").getAsJsonObject();
Boolean isTrial = roles.get("ROLE_Student_Trial").getAsBoolean();
Boolean isStudent = roles.get("ROLE_Student").getAsBoolean();
Boolean isUnlimited = roles.get("ROLE_Student_Unlimited").getAsBoolean(); // LoginTest.java:31
long lastLogin = obj.get("lastLogin").getAsLong();
int token = obj.get("token").getAsInt();
String type = obj.get("type").getAsString();
System.out.println(userName);
if(isTrial){
System.out.println("Student trial is on last login " + timeConverter(lastLogin));
}
if(isStudent){
System.out.println("Student access level");
}
if(isUnlimited){
System.out.println("Student is unlimited as " + type + " and its token = " + token);
}
I was trying to get values of inner JSON,
but I am getting NullPointerException.
Exception in thread "main" java.lang.NullPointerException
at loginActivityHttpURL.LoginTest.main(LoginTest.java:31)
I am answering to my own question.
JSON is case sensitive, so at ("ROLE_Student") gson wouldn't find any value. Instead I corrected it with ("ROLE_student") and it worked.
Thanks to #Tobia Tesan
Change this line
Boolean isStudent = roles.get("ROLE_Student").getAsBoolean();
to
Boolean isStudent = roles.get("ROLE_student").getAsBoolean();

How to find the list of user stories under a given iteration and a given project using rally rest api

I am able to get the iterations under the project object. Now how do I get the iteration I need under that project and then drill down to the stories in that iteration using the JAVA toolkit?
https://sandbox.rallydev.com/slm/webservice/v2.0/project/7191194697/iterations
Given a project:
String projectRef = "/project/1234";
You may scope your requests as follows:
iterationRequest.setProject(projectRef);
or
storyRequest.setProject(projectRef);
If you scoped a story request to a project, then you may query on stories by traversing Iteration.Name if you know the iteration already:
storyRequest.setQueryFilter(new QueryFilter("Iteration.Name", "=", "my Iteration 1"));
Here is a more complex example that returns stories assigned to iterations that fall within the timbox of a specific release. If, for example, you have 4 iterations per release, this code will return stories assigned to all four iterations.
If you code against the sandbox, replace the value in the host variable accordingly.
public class FindIterationsByReleaseDateAndStories {
public static void main(String[] args) throws URISyntaxException, IOException {
String host = "https://rally1.rallydev.com";
String username = "user#co.com";
String password = "secret";
String projectRef = "/project/12352608219";
String applicationName = "Find Iterations by Release Dates and Stories";
RallyRestApi restApi = null;
try {
restApi = new RallyRestApi(
new URI(host),
username,
password);
restApi.setApplicationName(applicationName);
System.out.println(restApi.getWsapiVersion());
QueryRequest releaseRequest = new QueryRequest("Release");
releaseRequest.setFetch(new Fetch("ReleaseStartDate", "ReleaseDate"));
releaseRequest.setScopedDown(false);
releaseRequest.setScopedUp(false);
releaseRequest.setProject(projectRef);
releaseRequest.setQueryFilter(new QueryFilter("Name", "=", "r1"));
QueryResponse releaseQueryResponse = restApi.query(releaseRequest);
int numberOfReleasesInProject = releaseQueryResponse.getTotalResultCount();
System.out.println(numberOfReleasesInProject);
JsonObject releaseJsonObject = releaseQueryResponse.getResults().get(0).getAsJsonObject();
System.out.println(releaseJsonObject.get("ReleaseStartDate"));
System.out.println(releaseJsonObject.get("ReleaseDate"));
String rsd = releaseJsonObject.get("ReleaseStartDate").getAsString();
String rd = releaseJsonObject.get("ReleaseDate").getAsString();
QueryRequest iterationRequest = new QueryRequest("Iteration");
iterationRequest.setFetch(new Fetch("Name","StartDate","EndDate"));
iterationRequest.setScopedDown(false);
iterationRequest.setScopedUp(false);
iterationRequest.setProject(projectRef);
iterationRequest.setQueryFilter(new QueryFilter("StartDate", ">=", rsd).and(new QueryFilter("EndDate", "<=", rd)));
QueryResponse iterationQueryResponse = restApi.query(iterationRequest);
int numberOfIteraitons = iterationQueryResponse.getTotalResultCount();
System.out.println("numberOfIteraitons " + numberOfIteraitons);
if(numberOfIteraitons >0){
for (int i=0;i<numberOfIteraitons;i++){
JsonObject iterationJsonObject = iterationQueryResponse.getResults().get(i).getAsJsonObject();
String iterationName = iterationJsonObject.get("Name").getAsString();
System.out.println("iteration: " + iterationName);
QueryRequest storyRequest = new QueryRequest("HierarchicalRequirement");
storyRequest.setProject(projectRef);
storyRequest.setFetch(new Fetch(new String[] {"Name", "FormattedID","ScheduleState"}));
storyRequest.setLimit(1000);
storyRequest.setScopedDown(false);
storyRequest.setScopedUp(false);
storyRequest.setQueryFilter(new QueryFilter("Iteration.Name", "=", iterationName));
QueryResponse storyQueryResponse = restApi.query(storyRequest);
System.out.println("Number of stories in " + iterationName + " :" + storyQueryResponse.getTotalResultCount());
for (int j=0; j<storyQueryResponse.getResults().size();j++){
JsonObject storyJsonObject = storyQueryResponse.getResults().get(j).getAsJsonObject();
System.out.println("Name: " + storyJsonObject.get("Name") + " FormattedID: " + storyJsonObject.get("FormattedID") + " ScheduleState: " + storyJsonObject.get("ScheduleState"));
}
}
}
}
finally{
if (restApi != null) {
restApi.close();
}
}
}
}
UPDATE: as far as your question in the comment, the code above is equivalent of
https://rally1.rallydev.com/slm/webservice/v2.0/hierarchicalrequirement?query=((Iteration.Name = i1) AND (Project = /project/12352608219))
There are other ways to achive the same result. Iteration name may not be unique, hence the second condition by project ref. In the code the request's project is set first, that's why the query itself uses one condition, but effectively there are two. If you know your iteration's ref, or ObjectID then the same result will be returned from (Iteration = /iteration/123456789), and there is no need to filter by project since a reference or ObjectID are unique.
WS API doc is interactive.Test your queries in WS API and copy the resulting query URLs from the address bar if you want to see how queries are formed:
-Query in the context of the intended object: click on the work item type in the Object Model, e.g. Defect or HierarchicalRequirement before typing your query in the query box.
-Enter a query in a box, e.g (Iteration.Name = i1)
-Click on Query button
-Results are displayed in the window from which you can copy query URL from address bar of your browser.

java.lang.NullPointerException when trying to parse XML

This problem really has me scratching my head.
I have a chat application that parses xml from the server. It is successful parsing the message text, msg id, but I am getting a nullpointerException for the UserID but I am pulling it from the same location. Please help
// Get messages
NodeList messageList = documentElement.getElementsByTagName("MESSAGE");
ret.messages = new ChatStruct[messageList.getLength()];
Log.v("response","Message Length " + messageList.getLength());
for (int i = 0; i < messageList.getLength(); i++) {
Element messageNode = (Element) messageList.item(i);
ret.messages[i] = new ChatStruct();
// Get messageId
try {
Element messageIdNode = (Element) messageNode.getElementsByTagName("ID").item(0);
String messageId = messageIdNode.getFirstChild().getNodeValue();
System.out.println("messageId = " + messageId);
ret.messages[i].id = Long.parseLong(messageId);
//Log.v("Util","Message ID " + Long.parseLong(messageId));
} catch (Exception e) {
ret.messages[i].id = 0l;
// e.printStackTrace();
}
// Get text
try {
Element textNode = (Element) messageNode.getElementsByTagName("TEXT").item(0);
String text = textNode.getFirstChild().getNodeValue();
System.out.println("text = " + text);
ret.messages[i].textMessage = text.trim();
//Log.v("Util","Message text " + text.trim());
} catch (Exception e) {
ret.messages[i].textMessage = "";
// e.printStackTrace();
}
// Get userId
try {
//ret.messages[i].userId = 1;
//Log.v("Util # userID node","userID should be 1");
Element userIdNode = (Element) messageNode.getElementsByTagName("USERID").item(0);
Log.i("Util # userID node","userIdNode set");
String userId = userIdNode.getFirstChild().getNodeValue();
//String userId = "1";
Log.i("Util # userID node","userId String set");
System.out.println("userId = " + userId);
ret.messages[i].userId = Long.parseLong(userId);
//ret.messages[i].userId = 1;
} catch (Exception e) {
Log.v("Util # userID node", "there was an error " + e);
ret.messages[i].userId = 0l;
// e.printStackTrace();
}
I can hard code the string and it works but other than that the error occurs at
String userId = userIdNode.getFirstChild().getNodeValue();
It makes it up to commented line of code confirming the userIDNode is set
I can't figure out why userID is not coming in from the server here is the XML:
<MESSAGE>
<ID><?php echo $row_shouts['msgid']; ?></ID>
<USERID><?php echo $row_shouts['userid']; ?></USERID>
<GENDER><?php echo $row_shouts['gender']; ?></GENDER>
<ONLINE><?php echo $row_shouts['account_status'];?></ONLINE>
<TDATE><?php echo datee("h:i:s M, d Y", strtotime($row_shouts['date'])); ?></TDATE>
<ICONID><?php echo $iconid; ?></ICONID>
<PIC><?php echo $PIC; ?></PIC>
<MSGPIC><?php echo $row_shouts['media']; ?></MSGPIC>
<PICDATE><?php echo strtotime($row_shouts['picdate']); ?></PICDATE>
<ALIAS><![CDATA[<?php echo $row_shouts['nickname'];?>]]></ALIAS>
<TEXT><![CDATA[<?php echo $mesg;?>]]></TEXT>
</MESSAGE>
Did you check with the DTD file for the supplied Xml, May be USERID is not clearly defined there.
[please share the error logs]
What's the execption say if you print the stack trace? It might be because the user id isn't a long and you're trying to parse it. I don't see any errors in the retrieval of the user id.

Categories

Resources