Я нашел это полезным:
получает членство в группе для Active Directory
И у меня есть этот рабочий код:
import java.util.Hashtable;
import javax.naming.CompositeName;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NameParser;
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 javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
public class TestAD1 {
private static String userBase = "DC=SomeName,DC=SomeName,DC=SomeName,DC=SomeName,DC=COM,DC=US";
public static void main(String[] args) {
TestAD1 tad = new TestAD1();
try {
// Create a LDAP Context
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "ldap.serviceaccount@domain.com");
env.put(Context.SECURITY_CREDENTIALS, "drowssap");
env.put(Context.PROVIDER_URL, "ldap://fully.qualified.server.name:389");
LdapContext ctx = new InitialLdapContext(env, null);
InitialDirContext inidircontext = new InitialDirContext(env);
DirContext dirctx = new InitialLdapContext(env, null);
System.out.println("Connection Successful.");
// Print all attributes of the name in namespace
SearchControls sctls = new SearchControls();
String retatts[] = {"sn", "mail", "displayName", "sAMAccountName"};
sctls.setReturningAttributes(retatts);
sctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String srchfilter = "(&(objectClass=user)(mail=*))";
String srchbase = userBase;
int totalresults = 0;
NamingEnumeration answer = dirctx.search(srchbase, srchfilter, sctls);
while (answer.hasMoreElements()) {
SearchResult sr = (SearchResult) answer.next();
totalresults++;
System.out.println(">>> " + sr.getName());
Attributes attrs = sr.getAttributes();
if (answer == null || !answer.hasMore()) {
System.out.println("No result found");
return;
}
if (attrs != null) {
try {
System.out.println(" surname: " + attrs.get("sn").get());
System.out.println(" Email - ID: " + attrs.get("mail").get());
System.out.println(" User - ID: " + attrs.get("displayName").get());
System.out.println(" Account Name: " + attrs.get("sAMAccountName").get());
tad.GetGroups(inidircontext, attrs.get("sAMAccountName").get().toString());
} catch (NullPointerException e) {
System.out.println("Error listing attributes..." + e);
}
}
System.out.println("Total Results : " + totalresults);
// close dir context
dirctx.close();
}
ctx.close();
} catch (NamingException e) {
System.out.println("Problem Search Active Directory..." + e);
//e.printStackTrace();
}
}
// Get all the groups.
public void GetGroups(InitialDirContext context, String username) throws NamingException {
String[] attrIdsToSearch = new String[]{"memberOf"};
String SEARCH_BY_SAM_ACCOUNT_NAME = "(sAMAccountName=%s)";
String filter = String.format(SEARCH_BY_SAM_ACCOUNT_NAME, username);
SearchControls constraints = new SearchControls();
constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
constraints.setReturningAttributes(attrIdsToSearch);
NamingEnumeration results = context.search(userBase, filter, constraints);
// Fail if no entries found
if (results == null || !results.hasMore()) {
System.out.println("No result found");
return;
}
SearchResult result = (SearchResult) results.next();
Attributes attrs = result.getAttributes();
Attribute attr = attrs.get(attrIdsToSearch[0]);
NamingEnumeration e = attr.getAll();
System.out.println(username + " is Member of the following groups : \n");
while (e.hasMore()) {
String value = (String) e.next();
System.out.println(value);
}
}
}
Если вы хотите сделать это целиком из кода:
import UIKit
struct MatchInfo {
var teamA: String
var teamB: String
}
class ViewController: UIViewController, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var matches = [MatchInfo]()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.dataSource = self
// Add some data
matches.append(MatchInfo(teamA: "Panthers", teamB: "Broncos"))
matches.append(MatchInfo(teamA: "Bucaneers", teamB: "Falcons"))
matches.append(MatchInfo(teamA: "Vikings", teamB: "Titans"))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: -
// MARK: Table View Data Source Delegate
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return matches.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("myCell") ?? makeCell()
let textFieldA = cell.viewWithTag(1) as! UITextField
let textFieldB = cell.viewWithTag(2) as! UITextField
let row = indexPath.row
textFieldA.text = matches[row].teamA
textFieldB.text = matches[row].teamB
return cell
}
func makeCell() -> UITableViewCell {
let textFieldA = UITextField(frame: CGRectZero)
let textfieldB = UITextField(frame: CGRectZero)
textFieldA.tag = 1
textfieldB.tag = 2
[textFieldA, textfieldB].forEach {
$0.translatesAutoresizingMaskIntoConstraints = false
$0.borderStyle = .RoundedRect
}
let vsLabel = UILabel(frame: CGRectZero)
vsLabel.text = "vs."
vsLabel.translatesAutoresizingMaskIntoConstraints = false
let cell = UITableViewCell(style: .Default, reuseIdentifier: "myCell")
[textFieldA, textfieldB, vsLabel].forEach { cell.contentView.addSubview($0) }
// Layout the elements
let views = ["A": textFieldA, "B": textfieldB, "vs": vsLabel]
let c1 = NSLayoutConstraint.constraintsWithVisualFormat("H:[A]-8-[vs]-8-[B]", options: .AlignAllBaseline, metrics: nil, views: views)
let c2 = NSLayoutConstraint(item: textFieldA, attribute: .Left, relatedBy: .Equal, toItem: cell.layoutMarginsGuide, attribute: .Left, multiplier: 1, constant: 0)
let c3 = NSLayoutConstraint(item: textfieldB, attribute: .Right, relatedBy: .Equal, toItem: cell, attribute: .Right, multiplier: 1, constant: 0)
let c4 = NSLayoutConstraint(item: textFieldA, attribute: .CenterY, relatedBy: .Equal, toItem: cell.contentView, attribute: .CenterY, multiplier: 1, constant: 0)
let c5 = NSLayoutConstraint(item: textFieldA, attribute: .Width, relatedBy: .Equal, toItem: textfieldB, attribute: .Width, multiplier: 1, constant: 0)
NSLayoutConstraint.activateConstraints(c1 + [c2, c3, c4, c5])
return cell
}
}
Результат:
Выполните следующие действия:
tableView(_: numberOfRowsInSection:)
и tableview(_: cellForRowAtIndexPath:)
. Затем в последнем методе напишите: пусть myCell = tableView.dequeueReusableCellWithIdentifier («myCellID») как! MyTableViewCell возвращает myCell Несмотря на то, что мы не используем выходы для созданных вами текстовых полей, вам нужно будет в какой-то момент использовать их для предварительного заполнения контента, установки методов целевого действия, и др.
class TextFieldsCell: UITableViewCell {
@IBOutlet var textfield1: UITextField!
@IBOutlet var textfield2: UITextField!
}
TextFieldsCell
к соответствующие текстовые поля: func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: TextFieldsCell = tableView.dequeueReusableCellWithIdentifier("TextFieldsCell") as! TextFieldsCell
return cell
}