How to get list of email address based on a specified group (CN) from memberOf Attribute in Active Directory in java - ldap

I had written a program to fetch all attributes from active directory based on username. now i want to get list of email address based on the group name CN= App_abc_Admin inside memerOf attribute.
Main .java
public void ldapQueryService()throws Exception{
try {
System.out.println("Querying Active Directory Using Java");
System.out.println("------------------------------------");
String domain = "abc.com";
String url = "ldap.abc.com:389";
String username = "username";
String password = "password";
String choice = "samaccountname";
String searchTerm = "xyz";
//Creating instance of ActiveDirectory
ActiveDirectory activeDirectory = new ActiveDirectory(username, password, domain, url);
//Searching
NamingEnumeration<SearchResult> result = activeDirectory.searchUser(searchTerm, choice, null);
while (result.hasMore()) {
SearchResult rs = (SearchResult) result.next();
Attributes attrs = rs.getAttributes();
String temp = attrs.get("samaccountname").toString();
System.out.println("Username : " + temp.substring(temp.indexOf(":") + 1));
String memberOf = attrs.get("memberOf").toString();
String stringToSearch = "CN=App_abc_Admin";
boolean test = memberOf.toLowerCase().contains(stringToSearch.toLowerCase());
if(test){
String mail = attrs.get("mail").toString();
System.out.println("Email ID : " + mail.substring(mail.indexOf(":") + 1));
}
}
activeDirectory.closeLdapConnection();
}catch(Exception e){
}
}
ActiveDirectory.java
public class ActiveDirectory {
//required private variables
private Properties properties;
private DirContext dirContext;
private SearchControls searchCtls;
private String[] returnAttributes = { "*"};
private String domainBase;
private String baseFilter = "(&((&(objectCategory=Person)(objectClass=User)))";
public ActiveDirectory(String username, String password, String domainController,String url) {
properties = new Properties();
properties.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
properties.put(Context.PROVIDER_URL, "LDAP://" + url);
properties.put(Context.SECURITY_PRINCIPAL, username + "#" + domainController);
properties.put(Context.SECURITY_CREDENTIALS, password);
//initializing active directory LDAP connection
try {
dirContext = new InitialDirContext(properties);
} catch (NamingException e) {
//LOG.severe(e.getMessage());
//e.printStackTrace();
}
//default domain base for search
domainBase = getDomainBase(domainController);
//initializing search controls
searchCtls = new SearchControls();
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
searchCtls.setReturningAttributes(returnAttributes);
}
public NamingEnumeration<SearchResult> searchUser(String searchValue, String searchBy, String searchBase) throws NamingException {
String filter = getFilter(searchValue, searchBy);
String base = (null == searchBase) ? domainBase : getDomainBase(searchBase);
return this.dirContext.search(base, filter, this.searchCtls);
}
public void closeLdapConnection(){
try {
if(dirContext != null)
dirContext.close();
}
catch (NamingException e) {
//e.printStackTrace();
}
}
private String getFilter(String searchValue, String searchBy) {
String filter = this.baseFilter;
if(searchBy.equals("email")) {
filter += "(mail=" + searchValue + "))";
} else if(searchBy.equals("username")) {
filter += "(samaccountname=" + searchValue + "))";
}else if(searchBy.equals("title")) {
filter += "(title=" + searchValue + "))";
}else if(searchBy.equals("department")) {
filter += "(department=" + searchValue + "))";
}else if(searchBy.equals("givenname")) {
filter += "(givenname=" + searchValue + "))";
}
else if(searchBy.equals("samaccountname")) {
filter += "(samaccountname=" + searchValue + "))";
}
return filter;
}
private static String getDomainBase(String base) {
char[] namePair = base.toUpperCase().toCharArray();
String dn = "DC=";
for (int i = 0; i < namePair.length; i++) {
if (namePair[i] == '.') {
dn += ",DC=" + namePair[++i];
} else {
dn += namePair[i];
}
}
return dn;
}
}
In the above example i'm passing the search by and search term. But how to get list of users based on the CN in the memberOf attribute?
I tried to update the filter as below but no output
private String baseFilter = "(&(objectClass=Person)(memberOf=cn=App_abc_Admin,ou=Application Groups,dc=abc,dc=com))";

updated the filter as below.It works now
private String baseFilter = "(&((&(objectCategory=Person)(objectClass=User)(mail=*abc.com)(memberOf=CN=App_abc_Admin,OU=Application Groups,OU=Security Groups,OU=Users_OU,DC=abc,DC=com))))";

Related

Pdf file renaming and deleting not working in Android 10 using MediaStore

I create an app that fetch all pdf documents from Phone storage... But in Android 10 devices , all pdfs not retrieved ... and even when I shall be tried to rename the pdf file , the pdf file is gone...
this is my code :
#NonNull
public ArrayList getAllPdfs(#NonNull Context context1) {
String str = null;
Uri collection;
ArrayList<PdfModel> arrayList = new ArrayList<>();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
collection = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL);
} else {
collection = MediaStore.Files.getContentUri("external");
}
// collection = MediaStore.Files.getContentUri("external");
try {
final String[] projection = new String[]{
MediaStore.Files.FileColumns._ID,
MediaStore.Files.FileColumns.DISPLAY_NAME,
MediaStore.Files.FileColumns.DATE_ADDED,
MediaStore.Files.FileColumns.DATA,
MediaStore.Files.FileColumns.MIME_TYPE,
};
Context context = getActivity();
SharedPreferences save_preferences = homeContext.getSharedPreferences(MY_SORT_PREF,
MODE_PRIVATE);
SharedPreferences preferencesOrder = homeContext.getSharedPreferences("Order", MODE_PRIVATE);
String order_by_descending = preferencesOrder.getString("order", "descending");
String order = null;
switch (order_by_descending) {
case "descending":
String sort = save_preferences.getString("sorting", "SortByDate");
switch (sort) {
case "SortByName":
order = MediaStore.Files.FileColumns.DISPLAY_NAME + " DESC";
break;
case "SortByDate":
order = MediaStore.Files.FileColumns.DATE_ADDED + " DESC";
break;
case "SortBySize":
order = MediaStore.Files.FileColumns.SIZE + " DESC";
break;
}
break;
case "ascending":
String sort_date = save_preferences.getString("sorting", "SortByDate");
switch (sort_date) {
case "SortByName":
order = MediaStore.Files.FileColumns.DISPLAY_NAME + " ASC";
break;
case "SortByDate":
order = MediaStore.Files.FileColumns.DATE_ADDED + " ASC";
break;
case "SortBySize":
order = MediaStore.Files.FileColumns.SIZE + " ASC";
break;
}
break;
}
final String selection = MediaStore.Files.FileColumns.MIME_TYPE + " = ?";
final String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("pdf");
final String[] selectionArgs = new String[]{mimeType};
CursorLoader cursorLoader = new CursorLoader(context1, collection, projection, selection,
selectionArgs, order);
Cursor cursor = cursorLoader.loadInBackground();
if (cursor != null && cursor.moveToFirst()) {
do {
int columnName = cursor.getColumnIndex(MediaStore.Files.FileColumns.DISPLAY_NAME);
int columnData = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);
String path = cursor.getString(columnData);
if (new File(path).exists()) {
#SuppressLint("Range")
File file = new
File(cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA)));
if (file.exists()) {
Log.d(TAG, "getAllPdfs: a " + file.length());
PdfModel pdfModel = new PdfModel();
//------------------------------Remove (.pdf) extension------------------------
String fileName = file.getName();
if (fileName.indexOf(".") > 0)
fileName = fileName.substring(0, fileName.lastIndexOf("."));
Uri imageUri = Uri.fromFile(file.getAbsoluteFile());
Log.d(TAG, "getAllPdfs: bb " + file.getName());
pdfModel.setId(file.getName());
pdfModel.setName(removeExtension(file.getName()));
pdfModel.setAbsolutePath(file.getAbsolutePath());
pdfModel.setParentFilePath(Objects.requireNonNull(file.getParentFile()).getName());
pdfModel.setPdfUri(file.toString());
pdfModel.setLength(file.length());
pdfModel.setLastModified(file.lastModified());
//pdfModel.setThumbNailUri(file.);
arrayList.add(pdfModel);
} else {
Log.d(TAG, "getAllPdfs: ");
}
}
} while (cursor.moveToNext());
cursor.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return arrayList;
}
Please solve this problem ....

How to insert current date and time when user insert data in database

I am trying to insert data into database. i am basically trying to get current date , I am also hiding that particular field("Update Date) because I do want the user to see. Now all I am wanting is whenever i insert some data to database created date should automatically inserted.
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(StoreImageCreateVM StoreImageVM)
{
if (ModelState.IsValid)
{
try
{
StoreImageLogic.Insert(StoreImageVM);
}
catch (Exception e)
{
TempData["Failure"] = "Creation Failed. Image too large.";
return View(StoreImageVM);
}
TempData["Success"] = "Creation Successful";
return RedirectToAction("Index", new { id = StoreImageVM.StoreID });
}
return View(StoreImageVM);
}
savechangesmethod
public bool Insert(StoreImageCreateVM imageVM)
{
StoreImage image = new StoreImage();
image.StoreID = imageVM.StoreID;
image.ImageDescription = imageVM.Description;
image.UploadDate = imageVM.uploadDate;
//Upload the file
string path = AppDomain.CurrentDomain.BaseDirectory + #"Content\Uploads";
string filename = imageVM.File.FileName;
string fullPath = Path.Combine(path, filename);
imageVM.File.SaveAs(fullPath);
//Set imageURL
string serverFilePath = #"\Content\Uploads\";
image.FullFilePath = serverFilePath + filename;
image.Active = true;
return base.Insert(image).StoreImageID != 0;
}
}
i just add to change the savechangesmethod by using the DateTime.Now method. see below.
public bool Insert(StoreImageCreateVM imageVM)
{
StoreImage image = new StoreImage();
image.StoreID = imageVM.StoreID;
image.ImageDescription = imageVM.Description;
image.UploadDate = DateTime.Now;
//Upload the file
string path = AppDomain.CurrentDomain.BaseDirectory + #"Content\Uploads";
string filename = imageVM.File.FileName;
string fullPath = Path.Combine(path, filename);
imageVM.File.SaveAs(fullPath);
//Set imageURL
string serverFilePath = #"\Content\Uploads\";
image.FullFilePath = serverFilePath + filename;
image.Active = true;
return base.Insert(image).StoreImageID != 0;
}
}
}

Coded UI c# - how to click a table htmlcell

I have tried numerous things to access a cell in a table. I have actually found the row that I need based on an innertext search, but then when I change the columnindex to the column for the found row, I cannot get mouse.click(cell); to do anything. Please see my code below. It has been modified many times! I have also used record to capture information about the cell.
The Method:
` public string SelectExistingCustomer(UITestControl parent, TestContext TestContext, string sLastName)
{
Controls control = new Controls(this.parent);
EditControl econtrol = new EditControl(this.parent);
HtmlTable tCustomerSearch = new HtmlTable(this.parent);
//HtmlTable tCustomerSearch1 = tCustomerSearch;
HtmlCell cell = new HtmlCell(tCustomerSearch);
//HtmlCell cell = GetCell;
string sFullName = "";
string sRowIndex = "";
if (sLastName != "")
{
try
{
// CodedUI scrolls items into view before it can click them
bool notfound = true;
int NumberOfpages = 0;
while (notfound)
{
tCustomerSearch.SearchProperties.Add(HtmlTable.PropertyNames.TagName, "TABLE");
Trace.WriteLine("####tCustomerSearch??? : " + tCustomerSearch + " : TABLE.");
tCustomerSearch.SearchConfigurations.Add(SearchConfiguration.AlwaysSearch);
int rowcount = tCustomerSearch.RowCount;
Trace.WriteLine("Row###: " + rowcount + ".");
HtmlRow lastRow = (HtmlRow)tCustomerSearch.Rows[rowcount - 1];
//lastRow.EnsureClickable();
NumberOfpages++;
cell.SearchProperties.Add(HtmlCell.PropertyNames.InnerText, sLastName, PropertyExpressionOperator.Contains);
cell.SearchConfigurations.Add(SearchConfiguration.AlwaysSearch);
if (cell.TryFind())
{
notfound = false;
sFullName = cell.GetProperty(HtmlCell.PropertyNames.InnerText).ToString();
sRowIndex = cell.GetProperty(HtmlCell.PropertyNames.RowIndex).ToString();
Trace.WriteLine(string.Format("found name at page {0}", NumberOfpages));
Trace.WriteLine(string.Format("Table row nr: {0}", cell.RowIndex));
Trace.WriteLine("cell####: " + cell + ".");
}
else Trace.WriteLine("NOT FOUND: CELL###:" + cell + ". And sFullName: " + sFullName + ".");
}
Trace.WriteLine("CELL###:" + cell + ". And sFullName: " + sFullName + ". And sRowIndex: " + sRowIndex + ".");
cell.SearchProperties.Add(HtmlCell.PropertyNames.RowIndex, sRowIndex);
cell.SearchProperties.Add(HtmlCell.PropertyNames.ColumnIndex, "0");
cell.SearchProperties[HtmlCell.PropertyNames.InnerText] = "Get";
cell.SetFocus();
//HtmlInputButton stry = new HtmlInputButton(cell);
Mouse.Click(cell);
//Mouse.Click(stry);
Assert.IsTrue(!notfound);
}
catch (Exception ex)
{
Trace.WriteLine("Failed to Search and find. Exception: " + ex + ".");
return "Failed";
}
}
//else - For the Future
return sFullName;
}
Table and cell - I modified this from the recording, not really sure what this does but I did something similar when I was having difficulty selecting from a combox:
public class tCustomerSearch : HtmlTable
{
public tCustomerSearch(UITestControl searchLimitContainer) :
base(searchLimitContainer)
{
#region Search Criteria
this.FilterProperties[HtmlTable.PropertyNames.ControlDefinition] = "class=\"table table-striped\"";
this.FilterProperties[HtmlTable.PropertyNames.Class] = "table table-striped";
this.FilterProperties[HtmlTable.PropertyNames.TagInstance] = "1";
#endregion
}
#region Properties
public HtmlCell GetCell
{
get
{
if ((this.mGetCell == null))
{
this.mGetCell = new HtmlCell(this);
#region Search Criteria
this.mGetCell.SearchProperties[HtmlCell.PropertyNames.InnerText] = "Get";
//this.GetCell.SearchProperties[HtmlCell.PropertyNames.MaxDepth] = "3";
Trace.WriteLine("###sLastName: " + sLastName + ". And mGetCell: " + mGetCell + ".");
#endregion
}
return this.mGetCell;
}
}
#endregion
// public string ctrlPropertyValue { get; private set; }
public string sLastName { get; }
#region Fields
private HtmlCell mGetCell;
#endregion
}
`
So, I found my own answer - even though this is not the best - it works!
` Keyboard.SendKeys("{TAB}");
Keyboard.SendKeys("{ENTER}");
'
I use this in place of mouse.click(cell);
The TAB highlights the button in the cell, and Enter triggers the event.

CloudStack: Unable to verify user credentials and/or request signature

I am working on CloudStack API now and I have the problem about making the API request. I always got "{ "listtemplatesresponse" : {"errorcode":401,"errortext":"unable to verify user credentials and/or request signature"} }" even though I change the parameter.
This error occurs in some commands that require the parameter and this is the command that I use:
command=listTemplates&templatefilter=featured
I don't know what I did wrong since it works with others. Here is the code I use to make the API request:
try {
String encodedApiKey = URLEncoder.encode(apiKey.toLowerCase(), "UTF-8");
ArrayList<String> sortedParams = new ArrayList<String>();
sortedParams.add("apikey="+encodedApiKey);
StringTokenizer st = new StringTokenizer(apiUrl, "&");
while (st.hasMoreTokens()) {
String paramValue = st.nextToken().toLowerCase();
String param = paramValue.substring(0, paramValue.indexOf("="));
String value = URLEncoder.encode(paramValue.substring(paramValue.indexOf("=")+1, paramValue.length()), "UTF-8");
sortedParams.add(param + "=" + value);
}
Collections.sort(sortedParams);
System.out.println("Sorted Parameters: " + sortedParams);
String sortedUrl = null;
boolean first = true;
for (String param : sortedParams) {
if (first) {
sortedUrl = param;
first = false;
} else {
sortedUrl = sortedUrl + "&" + param;
}
}
sortedUrl += "&response=json";
System.out.println("sorted URL : " + sortedUrl);
String encodedSignature = signRequest(sortedUrl, secretKey);
String finalUrl = host + "?" + apiUrl + "&response=json&apiKey=" + apiKey + "&signature=" + encodedSignature;
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(finalUrl);
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
System.out.println("str: "+str);
result = str.toString();
System.out.println("result: "+str);
}
else
System.out.println("Error response!!");
} catch (Throwable t) {
System.out.println(t);
}
And this is signRequest function:
public static String signRequest(String request, String key) {
try {
Mac mac = Mac.getInstance("HmacSHA1");
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1");
mac.init(keySpec);
mac.update(request.getBytes());
byte[] encryptedBytes = mac.doFinal();
return URLEncoder.encode(Base64.encodeBytes(encryptedBytes), "UTF-8");
} catch (Exception ex) {
System.out.println(ex);
}
return null;
}
Please feel free to ask me if you need more information. All comments and advice are welcome!
Have you tried sorting after you've added "&response=json" to the list of parameters?
E.g.
try {
String encodedApiKey = URLEncoder.encode(apiKey.toLowerCase(), "UTF-8");
ArrayList<String> sortedParams = new ArrayList<String>();
sortedParams.add("apikey="+encodedApiKey);
sortedParams.add("response=json");
StringTokenizer st = new StringTokenizer(apiUrl, "&");
while (st.hasMoreTokens()) {
String paramValue = st.nextToken().toLowerCase();
String param = paramValue.substring(0, paramValue.indexOf("="));
String value = URLEncoder.encode(paramValue.substring(paramValue.indexOf("=")+1, paramValue.length()), "UTF-8");
sortedParams.add(param + "=" + value);
}
Collections.sort(sortedParams);
System.out.println("Sorted Parameters: " + sortedParams);
String sortedUrl = null;
boolean first = true;
for (String param : sortedParams) {
if (first) {
sortedUrl = param;
first = false;
} else {
sortedUrl = sortedUrl + "&" + param;
}
}
System.out.println("sorted URL : " + sortedUrl);
String encodedSignature = signRequest(sortedUrl, secretKey);
String finalUrl = host + "?" + apiUrl + "&response=json&apiKey=" + apiKey + "&signature=" + encodedSignature;
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(finalUrl);
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
System.out.println("str: "+str);
result = str.toString();
System.out.println("result: "+str);
}
else
System.out.println("Error response!!");
} catch (Throwable t) {
System.out.println(t);
}
Your API Key and Response parameters need to be part of the sorted Url used when signing, which they appear to be.
try changing
return URLEncoder.encode(Base64.encodeBytes(encryptedBytes), "UTF-8");
to
return URLEncoder.encode(Base64.encodeAsString(encryptedBytes), "UTF-8");

the process cannot access the file 'xxx.xml' because it is being used by another process

I googled a lot, but i dint get any solution for problem.
Iam trying to add a node in to a xxx.xml file, but its throwing an error
"the process cannot access the file 'xxx.xml' because it is being used by another process", below is my class
public class Registration
{
List Users;
List NewUsers;
string Userpath = string.Empty;
string NewUserpath = string.Empty;
string strUsername = string.Empty;
public bool FINDUSERNAME(string firstname, string lastname, string emailaddress, string country, string purchasedate, string username, string password)
{
//Put code to get the offers from database to Offers variable
if (ReadXML(firstname, lastname, emailaddress, country, purchasedate, username, password))
return true;
else
return false;
}
//bool ReadXML(XmlDocument xmlfile2)
bool ReadXML(string firstname, string lastname, string emailaddress, string country, string purchasedate, string username, string password)
{
try
{
XmlDocument receivedxml = new XmlDocument();
Userpath = HttpContext.Current.Server.MapPath("/SampleData/Registration.xml");
NewUserpath = HttpContext.Current.Server.MapPath("/SampleData/NewRegistration.xml");
XmlReaderSettings xrs = new XmlReaderSettings();
xrs.DtdProcessing = DtdProcessing.Ignore;
XmlReader xr = XmlReader.Create(Userpath, xrs);
if (xr != null)
{
//Setting the Root element
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "Registration";
xRoot.IsNullable = true;
XmlSerializer deserializer = new XmlSerializer(typeof(Registration), xRoot);
Registration UserDetails = (Registration)deserializer.Deserialize(xr);
Users = UserDetails.Users;
foreach (var varuser in Users)
{
if (username == varuser.Username)
{
strUsername = varuser.Username;
return true;
}
}
if (strUsername == "")
{
//here iam trying to add a node to the xml
using (StreamWriter sw = new StreamWriter(File.Create(Userpath)))
{
sw.Write("<User><Firstname>"
+ firstname + "</Firstname><Lastname>"
+ lastname + "</Lastname><Country>"
+ country + "</Country><Purchasedate>"
+ purchasedate + "</Purchasedate><Emailaddress>"
+ emailaddress + "</Emailaddress><Username>"
+ username + "</Username><Password>"
+ password + "</Password></User>");
}
return false;
}
}
return false;
}
catch (Exception)
{
return false;
}
}
}
Thanks in Advance...
It looks like you are never closing your reader, you need to call xr.Close() at some point. Or as Johan suggested, wrap it in a using statement:
using (XmlReader xr = XmlReader.Create(Userpath, xrs))
{
//Setting the Root element
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "Registration";
xRoot.IsNullable = true;
XmlSerializer deserializer = new XmlSerializer(typeof(Registration), xRoot);
Registration UserDetails = (Registration)deserializer.Deserialize(xr);
Users = UserDetails.Users;
foreach (var varuser in Users)
{
if (username == varuser.Username)
{
strUsername = varuser.Username;
return true;
}
}
if (strUsername == "")
{
//here iam trying to add a node to the xml
using (StreamWriter sw = new StreamWriter(File.Create(Userpath)))
{
sw.Write("<User><Firstname>"
+ firstname + "</Firstname><Lastname>"
+ lastname + "</Lastname><Country>"
+ country + "</Country><Purchasedate>"
+ purchasedate + "</Purchasedate><Emailaddress>"
+ emailaddress + "</Emailaddress><Username>"
+ username + "</Username><Password>"
+ password + "</Password></User>");
}
return false;
}
}
Also another note: I notice your method is named ReadXML, yet you are also writing XML in this method. This can be confusing, are you reading or writing? Part of your issue may also be that you are opening the file for reading, and then creating the file for writing?? I have not dealt with the C# Xml libs before but something doesn't seem right here. You might consider breaking this down more.