Accessing ACTIVE DIRECTORY FROM JAVA CODE
I am trying to access the Active DIrectory user through a java code.
Kindly let me know the steps apart from creating the user in ADS to be followed so that the following java code may work.
presently it is giving the following error.
problem serching the directory
//package com.axa;
import java.util.Hashtable;
import javax.naming.ldap.*;
import javax.naming.directory.*;
import javax.naming.*;
public class AdHelper
public static void main(String args[])
System.out.println("1");
Hashtable env = new Hashtable();
String adminName = "CN=user,CN=Users,DC=BDC4AXA.CO.IN";
String adminPassword = "user";
String ldapURL = "ldap://10.1.242.51:636";
System.out.println("2");
env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.SECURITY_AUTHENTICATION,"simple");
env.put(Context.SECURITY_PRINCIPAL,adminName);
env.put(Context.SECURITY_CREDENTIALS,adminPassword);
env.put(Context.PROVIDER_URL,ldapURL);
System.out.println("3");
try {
// Create the initial directory context
DirContext ctx = new InitialLdapContext(env,null);
System.out.println("4");
SearchControls searchCtls = new SearchControls();
System.out.println("5");
//Specify the attributes to return
String returnedAtts[]={"sn","givenName","mail"};
searchCtls.setReturningAttributes(returnedAtts);
//Specify the search scope
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
//specify the LDAP search filter
String searchFilter = "(&(objectClass=user)(mail=*))";
System.out.println("6");
//Specify the Base for the search
String searchBase = "DC=ANTIPODES,DC=COM";
System.out.println("7");
//initialize counter to total the results
int totalResults = 0;
// Search for objects using the filter
NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls);
System.out.println("8"); //Loop through the search results
while (answer.hasMoreElements()) {
SearchResult sr = (SearchResult)answer.next();
totalResults++;
System.out.println("9");
System.out.println(">>>" + sr.getName());
Attributes attrs = sr.getAttributes();
if (attrs != null) {
try {
System.out.println(" surname: " + attrs.get("sn").get());
System.out.println(" firstname: " + attrs.get("givenName").get());
System.out.println(" mail: " + attrs.get("mail").get());
catch (NullPointerException e) {
System.out.println("Errors listing attributes: " + e);
System.out.println("Total results: " + totalResults);
ctx.close();
catch (NamingException e) {
System.err.println("Problem searching directory: " + e);
catch(Exception e)
System.out.println("Unhandled Exception: " + e);
}
This is what I have for my LDAP connection.
public Hashtable<String, String> env = null;
public LdapContext ldapContext = null;
public Control[] connCtls = null;
Context ctx;
DirContext dirContext;
public LDAPAuth(String ldapurl) {
ldapurl = "ldap://" + serverIP + ":389";
try {
env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.PROVIDER_URL, ldapurl);
env.put(Context.SECURITY_PRINCIPAL, "cn=username,cn=users" + baseName);
env.put(Context.SECURITY_CREDENTIALS, "password" + baseName);
env.put(Context.SECURITY_PROTOCOL, "ssl");
ctx = new InitialContext(env);
} catch (Exception e) {
System.out.println(" bind error: " + e);
e.printStackTrace();
try {
ldapContext = new InitialLdapContext(env, connCtls);
} catch (AuthenticationException e) {
System.out.println("Authentication exception " + e);
} catch (NamingException e) {
System.out.println("Naming exception " + e);
public Attributes fetch(String username) throws NamingException {
DirContext ctx = new InitialDirContext(env);
Attributes attributes = ctx.getAttributes(username);
try {
System.out.println("fetching: " + username);
Object obj = ctx.lookup("cn=" + username
+ baseName);
System.out.println("cn=" + username + baseName + "is bound to: " + obj);
//attributes = obj.getAttributes("");
for (NamingEnumeration<?> ae = attributes.getAll(); ae
.hasMoreElements();) {
Attribute attr = (Attribute) ae.next();
String attrId = attr.getID();
for (NamingEnumeration<?> vals = attr.getAll(); vals.hasMore();) {
String value = vals.next().toString();
System.out.println(attrId + ": " + value);
} catch (NamingException e) {
System.out.println(" Problem looking up " + username + baseName + ". " + e);
return attributes;
Now, I'm sure it has something to do with how I'm passing in the username and the groups. But I want to have ANY user log in, not just this test. I may be a little confused on how this works, but if anyone could explain to me why what I am trying to do doesn't work, I would greatly appreciate it.
Thanks in advance,
Tetsuya.
Edited by: tetsuyamasamune on Sep 8, 2008 3:55 PM
Similar Messages
-
Proplem: Access HTMLB controls from java code
Hi,
I am new to iView development for EP6. So my problem should be easy to solve (for you ).
I created in the NW Dev Studio a JSP DynPage.
The following files were created or edited:
1. JSP file (created)
2. java file (created)
3. portalapp.xml (edited)
In order to make the page running (proccessing) I changed the following things:
1. JSP file Add taglib reference to HTMLB-class
2. portalapp.xml Remove the native property so the JSP file will not be accessed directly.
Now I want to do the following:
On the JSP page I placed severeal HTMLB controls (textViews).
From the java code I try to access these controls in the doProcessBeforeOutput method and change/set values.
But I get all the time a null-Exception.
Code (JSP)
<%-- mcmsprovider.jsp --%>
<%@ taglib uri= "tagLib" prefix="hbj" %>
<hbj:content id="cntMcmsProvider" >
<hbj:page title="MCMS Provider Dynpage">
<hbj:form id="frmMcmsProvider" >
<hbj:textView id="tvwScript" encode="false"></hbj:textView>
<hbj:textView id="tvwStyle" encode="false"></hbj:textView>
</hbj:form>
</hbj:page>
</hbj:content>
Code (JAVA):
public void doProcessBeforeOutput() throws PageException {
this.setJspName("mcmsprovider.jsp");
TextView tvw = (TextView) this.getComponentByName("tvwStyle");
tvw.setText("Here the dynamic text");
I also tried to add raw text to the form but also null excpetion:
public void doProcessBeforeOutput() throws PageException {
this.setJspName("mcmsprovider.jsp");
Form frmCurrent = (Form) this.getForm();
frmCurrent.addRawText("<h3>This comes from here</h3>");
My goal is to dynamically add controls to the form, but until now I think it will be a dream:
public void doProcessBeforeOutput() throws PageException {
this.setJspName("mcmsprovider.jsp");
Form form = (Form)this.getForm();
TextView tvw = new TextView("tvwDynamic");
tvw.setText("Here the dynamic control");
form.addComponent(tvw);
The normal page processing runs:
public void doProcessBeforeOutput() throws PageException {
this.setJspName("mcmsprovider.jsp");
Any help is greatly appreciated.Eike
Here is the example straight from the PDK documentation. This should help you a little
UsingAbstractPortalComponentWithHTMLB.java
import com.sapportals.htmlb.*;
import com.sapportals.htmlb.enum.DataType;
import com.sapportals.htmlb.enum.GroupDesign;
import com.sapportals.htmlb.event.Event;
import com.sapportals.htmlb.rendering.IPageContext;
import com.sapportals.htmlb.rendering.PageContextFactory;
import com.sapportals.portal.prt.component.AbstractPortalComponent;
import com.sapportals.portal.prt.component.IPortalComponentRequest;
import com.sapportals.portal.prt.component.IPortalComponentResponse;
public class UsingAbstractPortalComponentWithHTMLB extends AbstractPortalComponent {
//Fill in your output for "normal" content creation mode here
protected void doContent(IPortalComponentRequest request, IPortalComponentResponse response) {
IPageContext myContext = PageContextFactory.createPageContext(request, response);
if (myContext == null) {
System.out.println("htmlb service did not start up as expected.");
Form myForm = myContext.createFormDocument("First Experiment");
Event lastEvent = myContext.getCurrentEvent();
Group myGroup = new Group();
myGroup.setWidth("350");
myGroup.setTitle("First Experiment");
myGroup.setDesign(GroupDesign.SAPCOLOR);
myForm.addComponent(myGroup);
GridLayout gl = new GridLayout();
myGroup.addComponent(gl);
if ((lastEvent != null) && (lastEvent.getComponentName().equals("submit"))) {
String name = myContext.getDataForComponentId("USER_NAME").toString();
TextView label = new TextView("Hi, " + name);
gl.addComponent(1, 1, label);
Button myButton = new Button("goback", "Go back");
myButton.setOnClick("goBack"); // ignored anyway
gl.addComponent(2, 1, myButton);
} else {
TextView label = new TextView("What's your name?");
gl.addComponent(1, 1, label);
InputField inf = new InputField("USER_NAME");
inf.setType(DataType.STRING);
gl.addComponent(1, 2, inf);
Button myButton = new Button("submit", "Tell");
myButton.setOnClick("submit");
gl.addComponent(2, 2, myButton);
myContext.render(); -
Accessing .properties file from java code
Hi,
I want my java code in a Tomcat Web Application to access values in a custom .properties file.How can i do it.
Any sample code / suggestions welcome.
Thanks
Vignesh.ResourceBundle vResourceBundle = ResourceBundle.getBundle("database", Locale.ENGLISH);
sDriverName = vResourceBundle.getString("database.DriverName");
sDbURL = vResourceBundle.getString("database.DriverUrl");
sDbUser = vResourceBundle.getString("database.UserName");
sDbPasswd = vResourceBundle.getString("database.PassWord");Where "database" is the name of the property file. ie., database.properties.
the content of the database.properties file
# Properties to access dabase
database.UserName = scott
database.PassWord = tiger
database.DriverName = oracle.jdbc.driver.OracleDriver
database.DriverUrl = jdbc:oracle:thin:@nn.nn.nn.nn:port:orartgnull -
Hi All,
I could see following error event in all client computers , Could you please some one help me on this ?
Log Name: Application
Source:
Microsoft-Windows-CertificateServicesClient-CredentialRoaming
Event ID: 1005
Level: Error
Description: Certificate Services Client: Credential Roaming failed to write to the Active Directory. Error code 5 (Access is denied.)
Regards, Srinivasu.MuchcherlaIf you are not using certificates and Credential Roaming for clients then simply ignore the error message.
If you are using certificates then you are getting access denied message when Credential Roaming is trying to write to your AD. More details about Credential Roaming here: http://blogs.technet.com/b/askds/archive/2009/01/06/certs-on-wheels-understanding-credential-roaming.aspx
http://blogs.technet.com/b/instan/archive/2009/05/26/considerations-for-implementing-credential-roaming.aspx
This is probably related to the fact that your schema version not 44 or higher: https://social.technet.microsoft.com/Forums/windowsserver/en-US/5b3a6e61-68c4-47d3-ae79-8296cb3be315/certificateservicesclientcredentialroaming-errors?forum=winserverGP
Active Directory
ObjectVersion
Windows 2000
13
Windows 2003
30
Windows 2003 R2
31
Windows 2008
44
Windows 2008 R2
47
This posting is provided AS IS with no warranties or guarantees , and confers no rights.
Ahmed MALEK
My Website Link
My Linkedin Profile
My MVP Profile -
Accessing XI Tables (ABAP Stack) from Java code
Hi,
IS it possible to access tables like SXMSPMAST, SXMSPEMAS directly from Java code without the use of any RFC or BAPI in between?
Cheers,
EarlenceI think it is technically possible, as you can get access to the JDBC Connector service using J2EE's JNDI feature ... Then you can use the internal DB datasource to read data from tables (read ONLY, cuz I'm not sure it is a good idea to update data "outside" the box, and reading can also have potiential perf or stability issue) ... Some (better) methods can also exist !
Chris
Edited by: Christophe PFERTZEL on Jan 15, 2010 3:07 PM -
Can u access Oracle9i Reports objects from Java Code?
Hi,
How can you access Oracle9i Reports (Rel 2) objects like Body, DataSource, Groups etc from Java Code?
What are the available APIs?
I went thru the APIs at http://otn.oracle.com/products/reports/htdocs/getstart/docs/Javadocs/oracle/reports/plugin/definition/package-summary.html
However various constructors stated in these APIs are using classes from "oracle.reports.definition" package which are difficult for me to locate.
For eg. Report constructor is using oracle.reports.definition.RWReport and there is no API documentation available for RWReport class.
Please suggest me the site for the above APIs or the method to get a reference to "Report" instance.
Thanks
Rakesh.Thanks Tugdual for your quick reply.
Thats exactly what I am trying to do. I want to develop a utility which can have a subset of Report Developer's functionality.
Currently using Reports Developer & Report Wizard, I can create a report by providing SQL statement and few parameters (like Report Style, Calculated Fields, Template file etc). I want to put all these parameters in a XML file and run my java utility (based on the APIs which I am looking for) which will use these XML parameter file and generate a '.rdf' file.
Also, could you please suggest me the site for oracle.reports.definition package API or the way to get a reference to oracle.reports.plugin.definition.Report instance.
Thanks,
Rakesh -
Accessing excel from java code
Hello
our system uses reportNet to generate reports. When reports are generated in CSV format we have a problem:
Report consists of people (can be more than one) so under name column we have same name in more than one row. BUT if more than one name is suppose to be in the CSV report then the header (column names row) is again printed.
so for example if i requested rpeort for two names A and B (reportNet uses same template which is executed twice) then report will look like this
Name (header - column name)
A
A
A
A
A
Name (header - column name)
B
B
B
B
I want to be able to remove the second header that comes before B starts.
so i was thinking i would be able to access this excel sheet from java. and keep record of every row. If the row changes from A to B...i delete the previous row (which would end up being the second header).
Can this be done thru java. I havnt before accessed excel sheets from java so any pointers would be greatly appreciated.Hi, well CSV is not currently an Excel file, it is a Comma Separated Values
file which can be read through Excel.
Now, if you wish to remove the header, I would purpose that you develop an
application that reads the CSV file, as it is mere text, and that it also reads
another file (lets call it confirguration.txt) in which you determine the pattern
you want to remove, then you just read your report and if a string line
matches the pattern you defined in the configuration.txt file, then you simply
erase it.
And if you keep interested in reading real Excel files (xls), I would
recommend you use POI-HSSF API from Apache.org
http://jakarta.apache.org/poi/hssf/index.html
Hope this helps, cya around. -
Clear the Filter Criteria from java code programmatically
Hi All,
I am using jdev version 11.1.1.6.0.
I do have ADF table for which I have added filter to each column .
I created table using java class data control.
Filter is working Fine .
My use case is-
When I click on search button data is populated in table.
When anybody enters filter value in column suppose product and hit enter ,it filters data.
if he clears and do not hit enter key and search again then it does not show all data it only show filtered data.
So how can I programmatically clear all filters so on click of search it will show all the values not filtered values.
I have not used default Filter Behavior.
Please check below code for reference
<af:table value="#{bindings.AfMyAccOrderStatusHistorySearchVO.rangeSet}"
var="row"
rows="#{bindings.AfMyAccOrderStatusHistorySearchVO.rangeSize}"
emptyText="#{bindings.AfMyAccOrderStatusHistorySearchVO.viewable ? 'No data to display.' : 'Access Denied.'}"
fetchSize="#{bindings.AfMyAccOrderStatusHistorySearchVO.rangeSize}"
rowBandingInterval="0" id="tblStatusHistoryList"
autoHeightRows="#{bindings.AfMyAccOrderStatusHistorySearchVO.rangeSize}"
rowSelection="single"
width="100%"
partialTriggers="::cb5 ::cb8 ::cb1 ::cb2"
filterModel="#{bindings.AfMyAccOrderStatusHistorySearchVO1Query.queryDescriptor}"
queryListener="#{bindings.AfMyAccOrderStatusHistorySearchVO1Query.processQuery}"
filterVisible="true" varStatus="vs"
binding="#{AfMyAccOrderStatusHistoryAction.orderStatusHistorySearchList}">
<af:column headerText="#{alfaprojectBundle['ordstatushistory.column.invoiceDate']}"
width="70"
sortProperty="invoiceDate"
sortable="true" filterable="true"
id="c7" filterFeatures="caseInsensitive">
<af:outputText value="#{row.invoiceDate}" id="ot16"/>
</af:column>
<af:column headerText="#{alfaprojectBundle['ordstatushistory.column.soldto']}"
width="100"
sortProperty="soldTo"
sortable="true" filterable="true"
id="c14" filterFeatures="caseInsensitive">
<af:outputText value="#{row.soldTo}"
visible="#{row.visibilityIsOrdrFirstItem}"
id="ot23"/>
</af:column>
So how to clear all filter values from java code.I can't get the example "Programmatically Manipulating a Table's QBE Filter Fields"
Where is it ?
https://smuenchadf.samplecode.oracle.com/samples/ClearTableColumnFilterFields.zip
Thks -
Programatically calling control flows from java code
Hi all,
I have a bounded taskFlow that uses pageFragments. This flow is a region in a page(.jspx).
In my page fragment, I have a inputComboboxListOfValues with a ValueChangeListener code in a java bean.
I want when a value is changed, to programatically call "controll flow" (this one has: "From Activity Id" -the page fragment with that inputComboboxListOfValues, and "To Activity Id" - the default Activity on this task Flow).
So when the value change, practically I want to restart the flow programatically and pass the selected value as input parameter.
Since the inputComboboxListOfValues is not like a button where in the "Action" property you can set the Control Flow and navigate somewhere, the only option I have is to programatically cause navigation from java code (example: the value change listener code).
Can this be achieved?
Any advice is helpfull.Hi,
Absolutely, you can do it using the NavigationHandler. Try the following in you value change listener:
FacesContext context = FacesContext.getcurrentInstance();
NavigationHandler handler = context.getApplication().getNavigationHandler();
handler.handleNavigation(context, null, outcome);
// Render the response after that phase, the button actions should not be called
context.renderResponse();
// Add the following line if you want to prevent further value change listeners to be called
// throw new AbortProcessingException();Regards,
~ Simon -
Ask from Java code if service runs
Hi,
i have a service, com.business.company.navigation.connector
running as ear on sap portal server.
Is there a way to ask from Java code if this service is running or not!?
I found following code which shows how access the portal runtime to get
default portal services:
NavigationEventsHelperService helperService = (NavigationEventsHelperService) PortalRuntime.getRuntimeResources().getService(NavigationEventsHelperService.KEY);
Thanks for any hint.Hi,
i have a service, com.business.company.navigation.connector
running as ear on sap portal server.
Is there a way to ask from Java code if this service is running or not!?
I found following code which shows how access the portal runtime to get
default portal services:
NavigationEventsHelperService helperService = (NavigationEventsHelperService) PortalRuntime.getRuntimeResources().getService(NavigationEventsHelperService.KEY);
Thanks for any hint. -
ADF mobile: access app preferences from java
Hi,
Jdev 11.1.2.3.0 + mobile extension.
Where I can find example code or documentation to access preferences (configured in adfmf-application.xml) from java code?
regards
PeterThanks!
It's following part of the document:
"At the Java layer, an EL value expression is resolved using the following
approach:
String val =
AdfmfJavaUtilities.evaluateELExpression("#{preferenceScope.feature.f0.vendor}")
regards
Peter -
Generation of xml file from java code
hi,
I want to manipulate data in a xml file with java code.I have read data from xml file and also changed it. But i am unable to covert it again in xml file from java code. Can you please tell me how i can do this?Let me know which parser are you using currently for reading xml files so that i assist you. For now, you can refer to STAX Parser API under this link
http://java.sun.com/webservices/docs/1.6/tutorial/doc/SJSXP3.html -
How to call a .bat file from java code?
How to call a .bat file from java code? and how can i pass parameters to that .bat file?
Thanks in advancethanks for ur reply
but still i am getting the same error.
I am trying to run a .bat file of together tool, my code looks like below
import java.lang.Runtime;
import java.lang.Process;
import java.io.File;
class SysCall{
public static void main(String args[]){
String cmd="D://Borland//Together6.2//bin//Together.bat -script:com.togethersoft.modules.qa.QA -metrics out:D://MySamples//Metrics// -fmt:html D://Borland//Together6.2//samples//java//CashSales//CashSales.tpr";
//String path="D://Borland//Together6.2//bin//Together.bat ";
Runtime r= Runtime.getRuntime(); //Declare the system call
try{
System.out.println("Before batch is called");
Process p=r.exec(cmd);
System.out.println(" Exit value =" + p.exitValue());
System.out.println("After batch is called");
/*can produce errors which must be caught*/
catch(Exception e) {
e.printStackTrace();
System.out.println (e.toString());
I am getting the below exception
Before batch is called
java.lang.IllegalThreadStateException: process has not exited
at java.lang.Win32Process.exitValue(Native Method)
at SysCall.main(SysCall.java:17)
java.lang.IllegalThreadStateException: process has not exited -
I know this question has been asked before, but never for R2, that I can tell, and the posted fixes aren't working. I have just installed SCVMM 2008 R2 on a Windows Server 2008 R2 server, using a remote SQL 2008 SP1 database. When I attempt to connect to SCVMM, I get the following error:
"The SQL Server service account does not have permission to access Active Directory Domain Services (AD DS).
Ensure that the SQL Server service is running under a domain account or a computer account that has permission to access AD DS. For more information, see "Some applications and APIs require access to authorization information on account objects" in the Microsoft Knowledge Base at http://go.microsoft.com/fwlink/?LinkId=121054.
ID: 2607"
What I've seen online is that this is usually becuase the domain account SCVMM is running as does not have the proper permissions on the SQL database. Here's what I've confirmed:
1) My SCVMM service account is a local admin on the SCVMM server
2) My SCVMM service account is a dbowner on the SCVMM database in SQL
3) My SQL service account is a dbowner on the SCVMM database in SQL
4) My SQL service account is a domain user (even made it a domain admin, just in case, and it still "doesn't have access to AD DS," which is obviously untrue)
5) Neither service account is locked out
Has anyone run in to this? It says in Technet that remote SQL 2008 is supported, as long as the SQL management studio is installed to the SCVMM server, and I installed and patched before I began the SCVMM installation. I just don't know what else to try - I have no errors in event logs, no issues during the installation itself...
Andrew ToppThat answer was very unhelpful fr33m4n. The individual mentions that they've received the error that points to the KB article. I currently receive the same error -- there seems to be no resolution. I've run the Microsoft VBS script to add TAUG to the WAAG
as suggested by 331951, and that made absolutely no difference.
1) My SCVMM service account is a local admin on the SCVMM server
2) My SCVMM service account is a dbowner on the SCVMM database in SQL
3) My SQL service account is a dbowner on the SCVMM database in SQL
4) My SQL service account is a domain user (even made it a domain admin, just in case, and it still
"doesn't have access to AD DS," which is obviously untrue)
The user is also a member of WAAG, the machines have delegated authority to each other. Is there any other solution? -
Starting exetutable java file from java code
Hi I was wondering how I can start a executable java file from java code?
thanksHi Mkaveli,
Yes, it's possible. If you have a JAR executable, you've just to call the main method of its starter class. For a simple executable class, just call its main method.
This way :
SomeStarter.main(null); // if there's no argumentSmall precision : the executable JAR or class must be specified in the classpath of your application.
Maybe you are looking for
-
Get Javascript values and use them in a servlet?
Hey I have a HTML which has Javascript scripts which I have to get values from (a array to be exact) and pass them to a servlet so I can process the information in a certain way. I cant seem to find a way to do this properly as the servlet is server
-
Error while running the tcode....EASISI
hello Experts, I am trying to execute the tcode EASISI with a varient..... All the proper values are given to....... Simulation From,Simulate To,Document Date,Posting Date,Installation,Invoicing simulation,Simulate invoic. for ind. doc., and Billing
-
Merging of multiple aperture libraries into one master library
Over the years, due to limited disk space on my Mac, I ended up having now 3 aperture libraries in 3 separate external hard drive, totaling between he 3 libraries over 2TB of photo storage. I just purchased an additional 4TB external drive (my 4th ex
-
PHP web form not working properly
I am having a problem with writing some PHP script in an attempt to draw info, entered by users, on a form on my site and email it to myself. The form is on the website page www.highwaytoheavenchurch.com/prayerRequest.php In lesson 13 of the textboo
-
Sahring library across multiple macs
I just bought a second mac and was wondering if there is a way to display photos in the iPhoto library on Mac #2, as if they were resident on the machine. Mac #1 has an extensive, many-gig photo and iTunes library and I don't want to have to copy all