Check username and password in Ldap server through java - java

I have to check if username and password gave from user are right matching with the Ldap server. I use two connection, in the first I retrieve dn from uid and in the second I connect to Ldap with dn and password.
I have a problem with retrieved dn, it doesn't have the right fields.
It returns
cn=Lu Ca+sn=Ca+uid=luca+userPassword={SSHA}OiMBVTTZBPqnohYch9\+ISeVv\+5ucgxMR: null:null:No attributes
and not
cn=Lu Ca+sn=Ca+uid=luca+userPassword={SSHA}OiMBVTTZBPqnohYch9\+ISeVv\+5ucgxMR,ou=people,dc=example,dc=com
As you can see, ou and dc are not returned so my second query fails.
This is my code
#Override
public void isAuthenticated(String username, String password) throws LdapException{
String dn;
Hashtable<String, Object> ldapEnv = new Hashtable<String, Object>();
ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
ldapEnv.put(Context.PROVIDER_URL, env.getRequiredProperty(PROPERTY_NAME_LDAP_URL));
ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
ldapEnv.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
ldapEnv.put(Context.SECURITY_CREDENTIALS, "secret");
String[] returnAttribute = {"dn"};
DirContext ctx = null;
NamingEnumeration<SearchResult> results = null;
try {
ctx = new InitialDirContext(ldapEnv);
SearchControls controls = new SearchControls();
controls.setReturningAttributes(returnAttribute);
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
String filter = "uid=" + username ;
results = ctx.search(env.getRequiredProperty(PROPERTY_NAME_LDAP_USERSEARCHBASE), filter, controls);
if (results.hasMore())
dn = results.nextElement().toString();
else throw new LdapException("Wrong username. Please retry!");
} catch (Exception e) {
throw new LdapException(e);
} finally {
try{
if (results != null)
results.close();
if (ctx != null)
ctx.close();
}catch(Exception e){
throw new LdapException(e);
}
}
Hashtable<String, Object> authEnv = new Hashtable<String, Object>();
authEnv.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
authEnv.put(Context.PROVIDER_URL, env.getRequiredProperty(PROPERTY_NAME_LDAP_URL));
authEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
authEnv.put(Context.SECURITY_PRINCIPAL, dn);
authEnv.put(Context.SECURITY_CREDENTIALS, password);
try {
new InitialDirContext(authEnv);
} catch (AuthenticationException authEx) {
throw new LdapException("Authentication error. Password was wrong");
} catch(Exception e){
throw new LdapException(e);
}
}
with this parameters
ldap.url=ldap://127.0.0.1:10389/dc=example,dc=com
ldap.userSearchBase=ou=people
I'm uing this value also for spring authentication but I have one method (send big file) that fails only if I use authentication so I would like to try to authenticate with java and not through Spring
Do you know why I have this problem? thanks
UPDATE: with
dn = results.nextElement().getNameInNamespace();
it works, is my codes robust?

This is jboss LDAP login module implementation you can compare you code:
full code link
protected void rolesSearch(LdapContext ctx, SearchControls constraints, String user, String userDN,
int recursionMax, int nesting) throws NamingException
{
LdapContext ldapCtx = ctx;
Object[] filterArgs = {user, sanitizeDN(userDN)};
boolean referralsExist = true;
while (referralsExist) {
NamingEnumeration results = ldapCtx.search(rolesCtxDN, roleFilter, filterArgs, constraints);
try
{
while (results.hasMore())
{
SearchResult sr = (SearchResult) results.next();
String dn;
if (sr.isRelative()) {
dn = canonicalize(sr.getName());
}
else {
dn = sr.getNameInNamespace();
}
if (nesting == 0 && roleAttributeIsDN && roleNameAttributeID != null)
{
if(parseRoleNameFromDN)
{
parseRole(dn);
}
else
{
// Check the top context for role names
String[] attrNames = {roleNameAttributeID};
Attributes result2 = null;
if (sr.isRelative()) {
result2 = ldapCtx.getAttributes(quoteDN(dn), attrNames);
}
else {
result2 = getAttributesFromReferralEntity(sr, user, userDN);
}
Attribute roles2 = (result2 != null ? result2.get(roleNameAttributeID) : null);
if( roles2 != null )
{
for(int m = 0; m < roles2.size(); m ++)
{
String roleName = (String) roles2.get(m);
addRole(roleName);
}
}
}
}
// Query the context for the roleDN values
String[] attrNames = {roleAttributeID};
Attributes result = null;
if (sr.isRelative()) {
result = ldapCtx.getAttributes(quoteDN(dn), attrNames);
}
else {
result = getAttributesFromReferralEntity(sr, user, userDN);
}
if (result != null && result.size() > 0)
{
Attribute roles = result.get(roleAttributeID);
for (int n = 0; n < roles.size(); n++)
{
String roleName = (String) roles.get(n);
if(roleAttributeIsDN && parseRoleNameFromDN)
{
parseRole(roleName);
}
else if (roleAttributeIsDN)
{
// Query the roleDN location for the value of roleNameAttributeID
String roleDN = quoteDN(roleName);
String[] returnAttribute = {roleNameAttributeID};
try
{
Attributes result2 = null;
if (sr.isRelative()) {
result2 = ldapCtx.getAttributes(roleDN, returnAttribute);
}
else {
result2 = getAttributesFromReferralEntity(sr, user, userDN);
}
Attribute roles2 = (result2 != null ? result2.get(roleNameAttributeID) : null);
if (roles2 != null)
{
for (int m = 0; m < roles2.size(); m++)
{
roleName = (String) roles2.get(m);
addRole(roleName);
}
}
}
catch (NamingException e)
{
PicketBoxLogger.LOGGER.debugFailureToQueryLDAPAttribute(roleNameAttributeID, roleDN, e);
}
}
else
{
// The role attribute value is the role name
addRole(roleName);
}
}
}
if (nesting < recursionMax)
{
rolesSearch(ldapCtx, constraints, user, dn, recursionMax, nesting + 1);
}
}
referralsExist = false;
}
catch (ReferralException e) {
ldapCtx = (LdapContext) e.getReferralContext();
}
finally
{
if (results != null)
results.close();
}
} // while (referralsExist)
}

Related

Spring LDAP getting LDAP: error code 32 - 0000208D NO_OBJECT

I finally able to write a standalone java which I am able to connect to LDAP and get user name and also able to authenticate (with password). But When I try same url and other details in Spring LDAP, I am getting error. Not getting what I am missing in Spring LDAP. Any help please???
LDAPService.java (Standalone)
public class LDAPService {
private final static int ACCOUNT_DISABLED = 2;
private static String[] ldapUrls = null;
private static String adminId = null;
private static String adminPassword = null;
private static SearchControls searchCtls = null;
private static String defaultGroup = null;
private static LDAPService ldapService;
private static String searchBase = null;
private int domainIndex;
private int domainCount;
public static LDAPService getInstance() {
if(ldapService == null ) ldapService = new LDAPService();
return ldapService;
}
public LDAPService() {
super();
String ldapUrl = "ldap://mycompany-ldap-tdu.lb.xyz.dm.company.com:389/OU=Engine,OU=PQR%20Global,DC=am,DC=mds,DC=pqr,DC=com";
ldapUrls = StringUtils.split(ldapUrl, ";");
adminId = "CN=APP-XYZ-GRP,OU=Non-Person,OU=Users,OU=QWE,OU=Engine,OU=PQR Global,DC=am,DC=mds,DC=pqr,DC=com";
adminPassword = "admpasswd";
defaultGroup = "85";
searchBase = "";
searchCtls = new SearchControls();
String attrTemp = "distinguishedName,userPassword,memberOf,pwdLastSet,accountExpires,userAccountControl,givenName,sn";
String returnedAtts[]= null;
if(null != attrTemp){
StringTokenizer st = new StringTokenizer(attrTemp,",");
int size = st.countTokens();
returnedAtts = new String[size];
int counter = 0;
while(st.hasMoreElements()){
returnedAtts[counter++] = st.nextToken();
}
}
int scope = 2;
searchCtls.setReturningAttributes(returnedAtts);
searchCtls.setSearchScope(scope);
//Start with a random domain controller to balance load.
Random randomGenerator = new Random();
domainIndex = randomGenerator.nextInt(ldapUrls.length);
domainCount = 0;
}
private Hashtable<String,String> getEnvironment(String userId, String password) {
Hashtable<String,String> envDC = new Hashtable<String,String>();
envDC.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
envDC.put(Context.SECURITY_AUTHENTICATION,"simple");
envDC.put(Context.PROVIDER_URL, ldapUrls[domainIndex]);
envDC.put(Context.SECURITY_PRINCIPAL,userId);
envDC.put(Context.SECURITY_CREDENTIALS,password);
return envDC;
}
public List<UserSecurityGroupId> authenticate(String userId,String password)throws Exception{
List<UserSecurityGroupId> groups = null;
String distinguishedName = null;
String memberOf = null;
Long pwdLastSet = null;
Long accountExpires = null;
Hashtable<String,String> envGC = getEnvironment(adminId, adminPassword);
String searchFilter = "(&(cn="+ userId + ")(objectClass=user))";
try{
LdapContext ctxGC = new InitialLdapContext(envGC,null);
//search LDAP Server using search Filter.
NamingEnumeration answer = ctxGC.search(searchBase, searchFilter, searchCtls);
if (answer.hasMoreElements()) {
SearchResult result = (SearchResult)answer.next();
Attributes attrs = result.getAttributes();
// get all attributes if the user exists
if (attrs != null) {
//Check if the User Account has been disabled
//This is identified by the returned values binary place holder for the decimal value 2 being a 1
if(null != attrs.get("useraccountcontrol")){
int userAccountControl = NumberUtils.toInt(attrs.get("useraccountcontrol")
.toString().replaceAll("userAccountControl: ", ""), ACCOUNT_DISABLED);
if((userAccountControl & ACCOUNT_DISABLED) == ACCOUNT_DISABLED){
return null;
}
}
//memberOf attribute retrieves the groups to which user belongs.
//only retrieve group memberships if password is provided
if(null != attrs.get("memberOf") && (null != password) && (password.trim().length() > 0)){
memberOf = attrs.get("memberOf").toString();
}
groups = getListOfGroups(memberOf, userId);
//pwdLastSet retrieves the time when password was last set.
if(null != attrs.get("pwdLastSet")){
pwdLastSet = new Long(attrs.get("pwdLastSet").get().toString());
}
//accountExpires retrieves the time when account will expire.
if(null != attrs.get("accountExpires")){
accountExpires = new Long(attrs.get("accountExpires").get().toString());
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(1601, 0, 1, 0, 0);
accountExpires = accountExpires / 10000 + calendar.getTime().getTime();
}
//distinguished name retrieves the distinguished name for the user.
if(null != attrs.get("distinguishedName")){
distinguishedName = attrs.get("distinguishedName").get().toString();
}
}
}else{
// if no attributes retrieved then user does not exist.
throw new LoginException(LoginStatus.USER_NOT_EXIST.toString());
}
ctxGC.close();
// verify if account is already expired.
if ( (null != accountExpires) && (accountExpires.longValue() > 0)) {
long today = System.currentTimeMillis();
long expireDay = accountExpires.longValue();
if ( expireDay < today ) {
throw new LoginException(LoginStatus.PASSWORD_EXPIRED.toString());
}
}
} catch (NamingException e) {
System.out.println("Naming Exception occurred");
if(checkNextDomainController())
authenticate(userId, password);
else
throw new LoginException(LoginStatus.AUTHENTICATION_ERROR.toString());
}
if(null != distinguishedName){
// verify the username and password if password is provided
if((null != password) && (password.trim().length() > 0)){
try {
Hashtable envDC = getEnvironment(distinguishedName,password);
DirContext ctx = new InitialDirContext(envDC);
ctx.close();
return groups;
}catch (CommunicationException comEx){
System.out.println("Communication Exception occurred");
if(checkNextDomainController())
return authenticate(userId, password);
else
throw new LoginException(LoginStatus.AUTHENTICATION_ERROR.toString());
}catch (AuthenticationException authEx){
authEx.printStackTrace();
System.out.println("Authentication Exception occurred");
throw new LoginException(LoginStatus.PASSWORD_INCORRECT.toString());
}catch (NamingException nameEx){
System.out.println("Naming Exception occurred");
if(checkNextDomainController())
return authenticate(userId, password);
else
throw new LoginException(LoginStatus.AUTHENTICATION_ERROR.toString());
}
}else{
return groups;
}
}else{
throw new LoginException(LoginStatus.USER_NOT_EXIST.toString());
}
}
private List<UserSecurityGroupId> getListOfGroups(String memberOf, String userId) {
List<UserSecurityGroupId> userScrityGrpList = new ArrayList<UserSecurityGroupId>();
String[] userSecurityGroupFilter = {"APP-XYZ"};
if(null != memberOf){
while(memberOf.indexOf("CN=") > 0){
memberOf = memberOf.substring(memberOf.indexOf("CN=")+3);
String tmp = memberOf.substring(0,memberOf.indexOf(','));
if(StringUtils.startsWithAny(tmp, userSecurityGroupFilter )) {
UserSecurityGroupId groupId = new UserSecurityGroupId(userId, tmp);
userScrityGrpList.add(groupId);
}
}
}
UserSecurityGroupId group = new UserSecurityGroupId(userId, defaultGroup);
if(!userScrityGrpList.contains(group)){
userScrityGrpList.add(group);
}
return userScrityGrpList;
}
/**
* This utility will return Associate Name from Active Directory corresponding to given user id.
* #param userId
* #return Associate Name
*/
public String getAssociateName(String userId) {
Hashtable<String,String> envGC = getEnvironment(adminId, adminPassword);
String searchFilter = "(&(cn="+ userId + ")(objectClass=user))";
String associateName = "";
try{
LdapContext ctxGC = new InitialLdapContext(envGC,null);
//search LDAP Server using search Filter.
NamingEnumeration answer = ctxGC.search(searchBase, searchFilter, searchCtls);
if (answer.hasMoreElements()) {
SearchResult result = (SearchResult)answer.next();
Attributes attrs = result.getAttributes();
// get all attributes if the user exists
if (attrs != null) {
//givenName attribute retrieves Given Name.
if(null != attrs.get("givenName") ){
associateName = associateName + attrs.get("givenName").get().toString() + " ";
}
//sn retrieves the Surname.
if(null != attrs.get("sn")){
associateName += attrs.get("sn").get().toString();
}
System.out.println(attrs.get("userPassword"));
}
}
ctxGC.close();
} catch (NamingException e) {
System.out.println("Naming Exception occurred while retrieving associate name");
}
return associateName;
}
public static void main(String[] a) {
LDAPService s = new LDAPService();
try {
System.out.println(s.getAssociateName("12345"));
//System.out.println(s.authenticate("12345", "password123"));
}catch(Exception e) {
e.printStackTrace();
}
}
}
WebSecurityConfiguration.java (Spring class)
#Configurable
#EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
try {
auth.ldapAuthentication()
.contextSource().url("ldap://mycompany-ldap-tdu.lb.xyz.dm.company.com:389/OU=Engine,OU=PQR%20Global,DC=am,DC=mds,DC=pqr,DC=com")
.managerDn("CN=APP-XYZ-GRP,OU=Non-Person,OU=Users,OU=QWE,OU=Engine,OU=PQR Global,DC=am,DC=mds,DC=pqr,DC=com")
.managerPassword("admpasswd")
.and()
.userSearchBase("")
.groupSearchBase("")
.userSearchFilter("(&(cn={0})(objectClass=user))")
.groupSearchFilter("(member=userGroup)");
}catch(Exception e) {
e.printStackTrace();
}
}
Error:
o.s.security.web.FilterChainProxy : /account/login at position 7 of 14 in additional filter chain; firing Filter: 'DefaultLoginPageGeneratingFilter'
o.s.security.web.FilterChainProxy : /account/login at position 8 of 14 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
o.s.s.w.a.www.BasicAuthenticationFilter : Basic Authentication Authorization header found for user 'user'
o.s.s.authentication.ProviderManager : Authentication attempt using org.springframework.security.ldap.authentication.LdapAuthenticationProvider
o.s.s.l.a.LdapAuthenticationProvider : Processing authentication request for user: user
o.s.s.l.s.FilterBasedLdapUserSearch : Searching for user 'user', with user search [ searchFilter: '(&(cn={0})(objectClass=user))', searchBase: '', scope: subtree, searchTimeLimit: 0, derefLinkFlag: false ]
.s.a.DefaultAuthenticationEventPublisher : No event was found for the exception org.springframework.security.authentication.InternalAuthenticationServiceException
o.s.s.w.a.www.BasicAuthenticationFilter : Authentication request for failed: org.springframework.security.authentication.InternalAuthenticationServiceException: [LDAP: error code 32 - 0000208D: NameErr: DSID-0310020A, problem 2001 (NO_OBJECT), data 0, best match of:
'DC=am,DC=mds,DC=pqr,DC=com'
]; nested exception is javax.naming.NameNotFoundException: [LDAP: error code 32 - 0000208D: NameErr: DSID-0310020A, problem 2001 (NO_OBJECT), data 0, best match of:
'DC=am,DC=mds,DC=pqr,DC=com'
]; remaining name '/'
Trying to match using RequestHeaderRequestMatcher [expectedHeaderName=X-Requested-With, expectedHeaderValue=XMLHttpRequest]
s.w.a.DelegatingAuthenticationEntryPoint : No match found. Using default entry point org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint#1dd945b2
w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed

Unable to upload a file through multipart form data from java as well as postman

I have been trying to upload a file from java as well as postman. But I am unable to upload. The server is giving back the response as 200 Ok. But, the file is not being uploaded.
API Details:
I have an API for uploading file as "FileExplorerController". This API has a method "upload()" to upload the files. Url to access this method is"/fileupload". The API is working fine if I upload a file through HTML UI.
But I am trying to upload using Java. I have tried using Postman as well.
I have passed the multipart form data in several ways. But unable to resolve the issue. The code is as follows.
API - Upload - Function
public Result upload() {
String fileName="";
String folderPath="";
String fileDescription="";
String userName = "";
StopWatch stopWatch = null;
List<FileUploadStatusVo> fileStatus = new ArrayList<>();
try {
stopWatch = LoggerUtil.startTime("FileExplorerController -->
upload() : File Upload");
StringBuilder exceptionBuilder = new StringBuilder();
Http.MultipartFormData body =
play.mvc.Controller.request().body().asMultipartFormData();
Http.Context ctx = Http.Context.current();
userName = ctx.session().get(SessionUtil.USER_NAME);
String password = "";
if(StringUtils.isBlank(userName)) {
Map<String, String[]> formValues = play.mvc.Controller.
request().body().asMultipartFormData().asFormUrlEncoded();
if(formValues != null) {
if(formValues.get("userName") != null &&
formValues.get("userName").length > 0) {
userName = formValues.get("userName")[0];
}
if(formValues.get("password") != null &&
formValues.get("password").length > 0) {
password = formValues.get("password")[0];
}
}
if(StringUtils.isBlank(userName) ||
StringUtils.isBlank(password)) {
return Envelope.ok();
}
UserVo userVo = userService.findUserByEmail(userName);
boolean success = BCrypt.checkpw(password, userVo.password);
if(!success) {
return badRequest("Password doesn't match for the given user
name: "+userName);
}
if(userVo == null) {
return Envelope.ok();
}
}
boolean override = false;
String fileTags="";
boolean isPublicView = false;
boolean isPublicDownload = false;
boolean isPublicDelete = false;
boolean isEmailNotification = false;
boolean isEmailWithS3Link = false;
List<String> viewerGroupNames = new ArrayList<>();
List<String> downloaderGroupNames = new ArrayList<>();
List<String> deleterGroupNames = new ArrayList<>();
List<String> viewerUserNames = new ArrayList<>();
List<String> downloaderUserNames = new ArrayList<>();
List<String> deleterUserNames = new ArrayList<>();
List<String> emailIds = new ArrayList<>();
Map<String, String[]> formValues =
play.mvc.Controller.request().body().
asMultipartFormData().asFormUrlEncoded();
JSONObject obj = new JSONObject(formValues.get("model")[0]);
Set<String> groupNames = new HashSet<>();
Set<String> userNames = new HashSet<>();
if(obj != null) {
if(obj.get("override") != null) {
override = Boolean.valueOf(obj.get("override").toString());
}
if(obj.get("description") != null) {
fileDescription = obj.get("description").toString();
}
if(obj.get("tags") != null) {
fileTags = obj.get("tags").toString();
}
if(obj.get("folderPath") != null){
folderPath = obj.get("folderPath").toString();
} else {
folderPath =
ctx.session().get(SessionUtil.LOCAL_STORAGE_PATH);
}
if(obj.get("isPublicView") != null) {
isPublicView =
Boolean.parseBoolean(obj.get("isPublicView").toString());
}
if(obj.get("isPublicDownload") != null) {
isPublicDownload =
Boolean.parseBoolean(obj.get("isPublicDownload").toString());
}
if(obj.get("isPublicDelete") != null) {
isPublicDelete = Boolean.parseBoolean(
obj.get("isPublicDelete").toString());
}
if(obj.get("emailNotification") != null) {
isEmailNotification =
Boolean.parseBoolean(obj.get("emailNotification").toString());
}
if(obj.get("emailWithFileAttachement") != null) {
isEmailWithS3Link =
Boolean.parseBoolean(obj.get(
"emailWithFileAttachement").toString());
}
if(obj.get("viewerGroupNames") != null) {
//TODO
if(!isPublicView) {
String[] namesArr =
(obj.get("viewerGroupNames").toString()).split(",");
for(String name:namesArr) {
if(StringUtils.isNotEmpty(name)) {
viewerGroupNames.add(name);
groupNames.add(name);
}
}
}
}
if(obj.get("downloaderGroupNames") != null) {
//TODO
if(!isPublicDownload) {
String[] namesArr =
(obj.get("downloaderGroupNames").toString().split(","));
for(String name:namesArr){
if(StringUtils.isNotEmpty(name)) {
downloaderGroupNames.add(name);
groupNames.add(name);
}
}
}
}
if(obj.get("deleteGroupNames") != null) {
//TODO
if(!isPublicDelete){
String[] namesArr =
(obj.get("deleteGroupNames").toString().split(","));
for(String name:namesArr){
if(StringUtils.isNotEmpty(name)) {
deleterGroupNames.add(name);
groupNames.add(name);
}
}
}
}
if(obj.get("viewerUserNames") != null) {
//TODO
if(!isPublicView) {
String[] namesArr =
(obj.get("viewerUserNames").toString()).split(",");
for(String name:namesArr) {
if(StringUtils.isNotEmpty(name)) {
viewerUserNames.add(name);
userNames.add(name);
}
}
}
}
if(obj.get("downloaderUserNames") != null) {
//TODO
if(!isPublicDownload) {
String[] namesArr =
(obj.get("downloaderUserNames").toString().split(","));
for(String name:namesArr){
if(StringUtils.isNotEmpty(name)) {
downloaderUserNames.add(name);
userNames.add(name);
}
}
}
}
if(obj.get("deleteUserNames") != null) {
//TODO
if(!isPublicDelete){
String[] namesArr =
(obj.get("deleteUserNames").toString().split(","));
for(String name:namesArr){
if(StringUtils.isNotEmpty(name)) {
deleterUserNames.add(name);
userNames.add(name);
}
}
}
}
if(obj.get("emailIds") != null) {
if(isEmailWithS3Link) {
String[] emailIdsArr =
(obj.get("emailIds").toString()).split(",");
for(String emailId:emailIdsArr){
if(StringUtils.isNotEmpty(emailId)){
emailIds.add(emailId);
}
}
}
}
}
if(groupNames.size() == 0 && userNames.size() == 0){
isEmailNotification = false;
}
List<Http.MultipartFormData.FilePart> files = body.getFiles();
boolean multiUpload = false;
if(files != null && files.size() > 1) {
multiUpload = true;
}
Logger.info("Total Number of files is to be uploaded:"+ files.size()
+" by user: " + userName);
int uploadCount = 0;
List<String> fileNames = new ArrayList<>();
List<String> fileMasters = new ArrayList<>();
FileMasterVo fileMasterVo = null;
UserVo userVo = userService.findUserByEmail(userName);
for(Http.MultipartFormData.FilePart uploadedFile: files) {
if (uploadedFile == null) {
return badRequest("File upload error for file " +
uploadedFile + " for file path: " + fileName);
}
uploadCount++;
String contentType = uploadedFile.getContentType();
String name = uploadedFile.getFile().getName();
Logger.info("Content Type: " + contentType);
Logger.info("File Name: " + fileName);
Logger.info("Name: " + name);
Logger.info("Files Processed : "+uploadCount+"/"+files.size()+"
for user: "+userName);
try {
String extension =
FileUtil.getExtension(uploadedFile.getFilename()).toLowerCase();
File renamedUploadFile =
FileUtil.moveTemporaryFile(System.getProperty("java.io.tmpdir"),
System.currentTimeMillis() + "_" +
uploadedFile.getFilename(), uploadedFile.getFile());
FileInputStream fis = new
FileInputStream(renamedUploadFile);
String errorMsg = "";
fileName = folderPath + uploadedFile.getFilename();
fileNames.add(uploadedFile.getFilename());
if(multiUpload) {
Logger.info("Attempting to upload file " + folderPath +
"/" + uploadedFile.getFilename());
fileMasterVo = fileService.upload(folderPath,fileName,
fileDescription, new Date(), fis, fis.available(),
extension, override,
fileTags, isPublicView, isPublicDownload,
isPublicDelete, viewerGroupNames, downloaderGroupNames,
deleterGroupNames, viewerUserNames,
downloaderUserNames,
deleterUserNames,userName,isEmailNotification);
} else if(fileName != null) {
Logger.info("Attempting to upload file " + fileName);
int index = fileName.lastIndexOf("/");
if (index > 1) {
fileMasterVo =
fileService.upload(folderPath,fileName, fileDescription,
new Date(), fis, fis.available(), extension, override,
fileTags, isPublicView, isPublicDownload,
isPublicDelete, viewerGroupNames, downloaderGroupNames,
deleterGroupNames, viewerUserNames,
downloaderUserNames,
deleterUserNames,userName,isEmailNotification);
} else {
errorMsg = "Root Folder MUST exist to upload any
file";
return badRequest(errorMsg);
}
} else {
errorMsg = "File Name is incorrect";
return badRequest(errorMsg);
}
createFileActivityLog(
fileMasterVo,userVo,ViewConstants.UPLOADED);
if (fileMasterVo != null && fileMasterVo.getId() != null) {
fileMasters.add(fileMasterVo.getId().toString());
}
} catch (Exception inEx) {
createErrorLog(userName,fileName,inEx);
exceptionBuilder.append("Exception occured in uploading
file: ");
exceptionBuilder.append(name);
exceptionBuilder.append(" are as follows ");
exceptionBuilder.append(ExceptionUtils.getStackTrace(inEx));
}
fileStatus.add(new
FileUploadStatusVo(uploadedFile.getFilename(),
fileMasterVo.getStatus()));
}
if(isEmailNotification){
fileService.sendNotificationForFile(folderPath,fileNames,
userName, groupNames,
userNames, ViewConstants.UPLOADED);
}
if (isEmailWithS3Link) {
//fileService.sendFileS3Link(folderPath, emailIds, fileMasters);
// Replacing sending S3 link with sending cdi specific link
fileService.sendFilesLink(emailIds, fileMasters);
}
String exceptions = exceptionBuilder.toString();
LoggerUtil.endTime(stopWatch);
if(!StringUtils.isBlank(exceptions)) {
Logger.error("Exception occured while uploading file: " +
fileName + " are as follows " + exceptions);
}
return Envelope.ok(fileStatus);
} catch (Exception inEx) {
createErrorLog(userName,fileName,inEx);
return badRequest("There is a system error please contact
support/administrator" );
} }
Client
**Client - Program**
multipart.addFormField("fileName",file.getAbsolutePath());
multipart.addFormField("folderPath","D/");
multipart.addFormField("fileDescription","Desc");
multipart.addFormField("userName","superadmin");
multipart.addFormField("password","admin");
multipart.addFormField("override","false");
multipart.addFormField("fileTags","tag");
multipart.addFormField("isPublicView","true");
multipart.addFormField("isPublicDownload","true");
multipart.addFormField("isPublicDelete","false");
multipart.addFormField("isEmailNotification","false");
multipart.addFormField("isEmailWithS3Link","true");*/
multipart.addFormField("file", input);
System.out.print("SERVER REPLIED: ");
for (String line : response)
{
System.out.print(line);
}
// synchronize(clientFolder, uploadFolder, true);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
I am able to upload using the following code snippet.
Here "model" is a json object which contain all parameters.
DefaultHttpClient client = new DefaultHttpClient();
HttpEntity entity = MultipartEntityBuilder
.create()
.addTextBody("userName", userName)
.addTextBody("password", passWord)
.addBinaryBody("upload_file", new File(sourceFolder + "/" + fileName), ContentType.create("application/octet-stream"), fileName)
.addTextBody("model", object.toString())
.build();
HttpPost post = new HttpPost(uploadURL);
post.setEntity(entity);
HttpResponse response = null;
try {
response = client.execute(post);
if (response.getStatusLine().getStatusCode() == 200) {
logger.info("File " + file.getName() + " Successfully Uploaded At: " + destination);
} else {
logger.info("File Upload Unsuccessful");
}
logger.info("Response from server:" + response.getStatusLine());
} catch (ClientProtocolException e) {
logger.error("Client Protocol Exception");
logger.error(e.getMessage());

Authentification failed while connecting to ActiveDirectory from a remote host

I wrote the code on Ubuntu 16 and tried to connect to ActiveDirectory on a Windows Server 2012 virtual machine.
The user name is : siwar
The user password is : siwarmp
The domain name is: squeezer.celtron.com
The VM host address (Windows server 2012) : 192.168.1.115
The following code did not work and generated an Authentification:
package ldap;
import java.util.Hashtable;
import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NameNotFoundException;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.SizeLimitExceededException;
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;
public class LdapMain {
static DirContext ctx = null;
static String userLog = "cn=siwar,ou=users,dc=squeezer,dc=celtron,dc=com";
// static String userLog =
// "cn=siwar,cn=users,dc=squeezer,dc=celtron,dc=com";
static String userMP = "siwarmp";
public static void main(String args[]) throws Exception {
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://192.168.1.115:389/");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=admin,dc=squeezer,dc=celtron,dc=com");
env.put(Context.SECURITY_CREDENTIALS, "ldap");
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
getGroup(env, 500);
getRole(env, "readonly");
validateLogin(env, userLog, userMP);
}
private static SearchControls getSimpleSearchControls() {
SearchControls searchControls = new SearchControls();
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
searchControls.setTimeLimit(30000);
// String[] attrIDs = {"objectGUID"};
// searchControls.setReturningAttributes(attrIDs);
return searchControls;
}
public static Boolean validateLogin(Hashtable<String, String> env, String userName, String userPassword) {
NamingEnumeration<SearchResult> results = null;
try {
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
controls.setCountLimit(1);
controls.setTimeLimit(5000);
env.put(Context.SECURITY_PRINCIPAL, userName);
env.put(Context.SECURITY_CREDENTIALS, userPassword);
ctx = new InitialDirContext(env);
results = ctx.search("ou=users,dc=celtron,dc=com", "(objectclass=inetOrgPerson)",
getSimpleSearchControls());
// results = ctx.search("dc=celtron,dc=com",
// "(objectclass=inetOrgPerson)", getSimpleSearchControls());
results = ctx.search(userName, "(objectclass=*)", getSimpleSearchControls());
System.out.println(results);
while (results.hasMore()) {
SearchResult result = (SearchResult) results.next();
Attributes attrs = result.getAttributes();
Attribute dnAttr = attrs.get("cn");
String dn = (String) dnAttr.get();
System.out.println(dn);
Attribute gidAttr = attrs.get("gidNumber");
String gid = (String) gidAttr.get();
System.out.println(gid);
// User Exists, Validate the Password
env.put(Context.SECURITY_PRINCIPAL, userName);
env.put(Context.SECURITY_CREDENTIALS, userPassword);
return true;
}
return false;
} catch (AuthenticationException e) { // Invalid Login
return false;
} catch (NameNotFoundException e) { // The base context was not found.
return false;
} catch (SizeLimitExceededException e) {
throw new RuntimeException("LDAP Query Limit Exceeded, adjust the query to bring back less records", e);
} catch (NamingException e) {
throw new RuntimeException(e);
} finally {
try {
if (results != null) {
results.close();
}
if (ctx != null) {
ctx.close();
}
} catch (Exception e) { /* Do Nothing */
}
}
}
public static Boolean getRole(Hashtable<String, String> env, String roleName) {
NamingEnumeration<SearchResult> results = null;
try {
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
controls.setCountLimit(1);
controls.setTimeLimit(5000);
ctx = new InitialDirContext(env);
results = ctx.search("cn=readonly,ou=roles,dc=celtron,dc=com", "(objectclass=organizationalRole)",
getSimpleSearchControls());
while (results.hasMore()) {
SearchResult result = (SearchResult) results.next();
Attributes attrs = result.getAttributes();
Attribute dnAttr = attrs.get("roleOccupant");
String dn = (String) dnAttr.get();
System.out.println(dn);
return true;
}
return false;
} catch (AuthenticationException e) { // Invalid Login
System.out.println("Auth failed");
return false;
} catch (NameNotFoundException e) { // The base context was not found.
return false;
} catch (SizeLimitExceededException e) {
throw new RuntimeException("LDAP Query Limit Exceeded, adjust the query to bring back less records", e);
} catch (NamingException e) {
throw new RuntimeException(e);
} finally {
try {
if (results != null) {
results.close();
}
if (ctx != null) {
ctx.close();
}
} catch (Exception e) {
}
}
}
public static String getGroup(Hashtable<String, String> env, int gid) {
NamingEnumeration<SearchResult> results = null;
try {
SearchControls controls = new SearchControls();
controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
controls.setCountLimit(1);
controls.setTimeLimit(5000);
ctx = new InitialDirContext(env);
results = ctx.search("ou=groups,dc=celtron,dc=com", "(gidNumber=500)", getSimpleSearchControls());
while (results.hasMore()) {
SearchResult result = (SearchResult) results.next();
Attributes attrs = result.getAttributes();
Attribute dnAttr = attrs.get("cn");
String dn = (String) dnAttr.get();
System.out.println(dn);
return dn;
}
return "";
} catch (AuthenticationException e) {
return "";
} catch (NameNotFoundException e) {
return "";
} catch (SizeLimitExceededException e) {
throw new RuntimeException("LDAP Query Limit Exceeded, adjust the query to bring back less records", e);
} catch (NamingException e) {
throw new RuntimeException(e);
} finally {
try {
if (results != null) {
results.close();
}
if (ctx != null) {
ctx.close();
}
} catch (Exception e) {
}
}
}
}

How to do fulltext search with collectionId on Oracle UCM?

How can we make a fulltext search with collectionId on Oracle UCM? Is it possible to do fulltext search supplying recursively start with collectionId parameter?
I did some trials (you can take a look below) but if i test with collectionId, there is no result return.
public List<UCMDocumentTemplate> fullTextSearchByFolderId(#WebParam(name = "searchCriteria")
String paramSearchCriteria, #WebParam(name = "ucmFolderId")
Long ucmFolderId) throws UCMDocumentSearchException
{
List<UCMDocumentTemplate> documentTemplateList = new ArrayList<UCMDocumentTemplate>();
String documentSearchCriteria = "";
try
{
if (ucmFolderId != null)
documentSearchCriteria = "xCollectionID <= <qsch>" + ucmFolderId + "</qsch> <AND>";
documentSearchCriteria += "dDocFullText <substring> <qsch>" + paramSearchCriteria + "</qsch>";
List<Properties> childDocumentList = UCM_API.fullTextSearch(documentSearchCriteria);
UCMDocumentTemplate ucmDocumentTemplate = null;
if (childDocumentList != null)
for (Properties properties : childDocumentList)
{
ucmDocumentTemplate = transformToUCMDocumentTemplate(new UCMDocumentTemplate(), properties);
documentTemplateList.add(ucmDocumentTemplate);
}
}
catch (Exception e)
{
UCMDocumentSearchException exc = new UCMDocumentSearchException(documentSearchCriteria, e);
System.err.println(exc.getCompleteCode());
e.printStackTrace();
throw exc;
}
return documentTemplateList;
}
public static List<Properties> fullTextSearch(String searchCriteria) throws Exception
{
List<Properties> resultList = null;
List<Field> fields = null;
Properties responseProperties = null;
Properties inputBinderProperties = new Properties();
inputBinderProperties.put("IdcService", "GET_SEARCH_RESULTS");
inputBinderProperties.put("QueryText", searchCriteria);
inputBinderProperties.put("SearchEngineName", "databasefulltext");
inputBinderProperties.put("ResultCount", "500");
DataBinder responseBinder = getExecutedResponseBinder(userName, inputBinderProperties);
DataResultSet resultSet = responseBinder.getResultSet("SearchResults");
fields = resultSet.getFields();
resultList = new ArrayList<Properties>();
for (DataObject dataObject : resultSet.getRows())
{
responseProperties = new Properties();
for (Field field : fields)
{
if (field.getType() == Field.Type.DATE && dataObject.getDate(field.getName()) != null)
responseProperties.put(field.getName(), dataObject.getDate(field.getName()));
else
responseProperties.put(field.getName(), dataObject.get(field.getName()));
}
resultList.add(responseProperties);
}
return resultList;
}
i found a solution. when adding a parameter to inputBinderProperties, it works properly
inputBinderProperties.put("folderChildren", ucmFolderId);

Invalid credentials exception while Importing contact list from gmail contacts using Java in Linux only

I have using Google (GDATA) Gmail API for retrieving the contact list from gmail, It is working successfully on windows environment, but when I run the same code on Linux, I get error of Invalid Credentials.
I googled it, but can't get much help,
here is my code
public static String getGmailContactList() {
String response = "";
StringBuilder str = new StringBuilder();
String statusString = "";
ArrayList list = new ArrayList();
ContactsService myService = new ContactsService("");
String email = "xxxxx#gmail.com";
String password = "xxxxxxxx";
try
{
try
{
myService.setUserCredentials(email, password);
}
catch (AuthenticationException ex)
{
ex.printStackTrace();
//****I got exception here when using this code on LINUX ENVIORMENT** ***
}
response = printAllContacts(myService, email);
Iterator itr = list.iterator();
while (itr.hasNext())
{
ArrayList contact = (ArrayList) itr.next();
try
{
str.append(contact.get(1)).append(",");
}
catch (Exception e)
{
log.debug("Exception ocurred inside fethching gmail contact >
>
>
" + e);
str.append("no contacts found");
}
str.substring(0, str.length() - 1);
}
}
catch (Exception ae)
{
response = statusString;
log.debug("Exception ocurred inside ReadContacts : getGmailContactList()" + ae);
}
return response;
}
public static String printAllContacts(ContactsService myService, String emailSent)//
throws ServiceException, IOException
{
URL feedUrl = new URL("http://www.google.com/m8/feeds/contacts/" + emailSent + "/full");
Query myQuery = new Query(feedUrl);
myQuery.setMaxResults(100);
ContactFeed resultFeed = myService.getFeed(myQuery, ContactFeed.class);
String phones = null;
String emails = null;
log.debug(resultFeed.getTitle().getPlainText());
StringBuilder contacts = new StringBuilder();
contacts.append("<?xml version=\"1.0\"><Contacts>");
for (int i = 0; i < resultFeed.getEntries().size(); i++)
{
contacts.append("<Contact>");
ContactEntry entry = resultFeed.getEntries().get(i);
if (entry.hasName())
{
Name name = entry.getName();
if (name.hasFullName())
{
String fullNameToDisplay = name.getFullName().getValue();
if (name.getFullName().hasYomi())
{
fullNameToDisplay += " (" + name.getFullName().getYomi() + ")";
}
contacts.append("<Name>").append(fullNameToDisplay).append("</Name>");
}
else
{
contacts.append("<Name>").append("").append("</Name>");
}
}
else
{
contacts.append("<Name>").append("").append("</Name>");
}
StringBuilder emailIds = new StringBuilder();
if (entry.hasEmailAddresses())
{
List<Email> email = entry.getEmailAddresses();
if (email != null && email.size() > 0)
{
for (Email e : email)
{
emailIds.append(e.getAddress()).append(",");
}
emailIds.trimToSize();
if (emailIds.indexOf(",") != -1)
{
emails = emailIds.substring(0, emailIds.lastIndexOf(","));
}
contacts.append("<Email>").append(emails).append("</Email>");
}
else
{
contacts.append("<Email>").append("").append("</Email>");
}
}
else
{
contacts.append("<Email>").append("").append("</Email>");
}
contacts.append("</Contact>");
}
contacts.append("</Contacts>");
return contacts.toString();
}
so where I am lacking behind, some sort of help will be appriciated
here is the stack trace
com.google.gdata.client.GoogleService$InvalidCredentialsException: Invalid credentials
at com.google.gdata.client.GoogleAuthTokenFactory.getAuthException(GoogleAuthTokenFactory.java:660)
at com.google.gdata.client.GoogleAuthTokenFactory.getAuthToken(GoogleAuthTokenFactory.java:560)
at com.google.gdata.client.GoogleAuthTokenFactory.setUserCredentials(GoogleAuthTokenFactory.java:397)
at com.google.gdata.client.GoogleService.setUserCredentials(GoogleService.java:364)
at com.google.gdata.client.GoogleService.setUserCredentials(GoogleService.java:319)
at com.google.gdata.client.GoogleService.setUserCredentials(GoogleService.java:303)
at com.gmail.ReadContacts.getGmailContactList(ReadContacts.java:55)

Categories