Hibernate/JPA validation failing when connecting to AS400 - java

I'm developing a Tomcat-based webapp I'm trying to get to talk to an existing AS400 data store. I've copied most of the settings from an existing web app which works, but when I run my new app I get this:
2013-08-08 13:50:11,988 ERROR [RMI TCP Connection(3)-127.0.0.1] org.hibernate.tool.hbm2ddl.SchemaValidator - could not get database metadata
java.sql.SQLException: [SQL5016] Qualified object name SYSSEQUENCES not valid.
at com.ibm.as400.access.JDError.throwSQLException(JDError.java:646)
at com.ibm.as400.access.JDError.throwSQLException(JDError.java:617)
at com.ibm.as400.access.AS400JDBCStatement.commonPrepare(AS400JDBCStatement.java:1578)
at com.ibm.as400.access.AS400JDBCStatement.executeQuery(AS400JDBCStatement.java:2138)
at org.apache.tomcat.dbcp.dbcp.DelegatingStatement.executeQuery(DelegatingStatement.java:208)
at org.apache.tomcat.dbcp.dbcp.DelegatingStatement.executeQuery(DelegatingStatement.java:208)
at org.hibernate.tool.hbm2ddl.DatabaseMetadata.initSequences(DatabaseMetadata.java:151)
at org.hibernate.tool.hbm2ddl.DatabaseMetadata.<init>(DatabaseMetadata.java:69)
at org.hibernate.tool.hbm2ddl.SchemaValidator.validate(SchemaValidator.java:132)
at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:378)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1872)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:906)
at org.hibernate.ejb.HibernatePersistence.createContainerEntityManagerFactory(HibernatePersistence.java:74)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:288)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:310)
[SNIP]
Seems like it's failing looking for the SYSSEQUENCES object (presumably a table) but there's no such table in my schema, or anywhere that I'm aware of. Why is it doing this and how can I correct it?
Here's the SERVER.XML resource that I'm using to connect:
<Resource
name="jdbc/myresource"
auth="Container"
driverClassName="com.ibm.as400.access.AS400JDBCDriver"
maxActive="20"
maxIdle="10"
maxWait="5000"
password="mypassword"
testOnBorrow="true"
type="javax.sql.DataSource"
url="jdbc:as400://mysystem.mycompany.com;libraries=LIB1 LIB2 LIB3;dateformat=iso;timeformat=iso;prompt=false;naming=system;transaction isolation=none"
username="myusername"
validationQuery="SELECT * from sysibm/sysdummy1"/>
Here's my PERSISTENCE.XML:
<persistence-unit name="myPersistenceUnit">
<properties>
<property name="hibernate.generate_statistics" value="true" />
<property name="hibernate.cache.use_structured_entries" value="true" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.jdbc.batch_size" value="100" />
<property name="hibernate.dialect" value="org.hibernate.dialect.DB2400Dialect" />
<property name="hibernate.hbm2ddl.auto" value="validate" />
</properties>
</persistence-unit>

Examining the stack trace the issue begins at org.hibernate.tool.hbm2ddl.DatabaseMetadata.initSequences.
The initSequences method checks the dialect for sequence support:
DatabaseMetadata.initSequences
private void initSequences(Connection connection, Dialect dialect) throws SQLException {
if ( dialect.supportsSequences() ) {
String sql = dialect.getQuerySequencesString();
DB2400Dialect reports that it does not:
DB2400Dialect.java
public class DB2400Dialect extends DB2Dialect {
#Override
public boolean supportsSequences() {
return false;
}
For reference the base DB2Dialect does support sequences and references sysibm.syssequences:
DB2Dialect.java
#Override
public boolean supportsSequences() {
return true;
}
#Override
public String getQuerySequencesString() {
return "select seqname from sysibm.syssequences";
}
It would appear that either your dialect is not being set properly or your version of DB2400Dialect is reporting that it does support sequences.

Try using the following:
public class DB2AS400Dialect extends DB2400Dialect {
#Override
public String getQuerySequencesString() {
return null;
}
}
Since the Dialect class does the following:
public SequenceInformationExtractor getSequenceInformationExtractor() {
if ( getQuerySequencesString() == null ) {
return SequenceInformationExtractorNoOpImpl.INSTANCE;
}
else {
return SequenceInformationExtractorLegacyImpl.INSTANCE;
}
}
Instead of consulting the boolean value if the dialect supports sequences.

Related

Serverless framework with java MySQL conexion

I'm new with serverless framework. I'm trying to make a test of a simple application with maven, spring, hibernate, jpa, mysql and serverless.
this is my project
As a restApi works ok, but when I invoke the function in serverless terminal the information came null, because is not getting the info from the db.
this is my code
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="serverless-java" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.serverless.persistence.Wizard</class>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://mydb.uiyfuas7434.us-east-1.rds.amazonaws.com:3306/mydb" />
<property name="hibernate.connection.username" value="root" />
<property name="hibernate.connection.password" value="1234" />
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<!-- Important -->
<property name="hibernate.connection.provider_class" value="org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider" />
<property name="hibernate.c3p0.max_size" value="10" />
<property name="hibernate.c3p0.min_size" value="0" />
<property name="hibernate.c3p0.acquire_increment" value="1" />
<property name="hibernate.c3p0.idle_test_period" value="120" />
<property name="hibernate.c3p0.max_statements" value="0" />
<property name="hibernate.c3p0.timeout" value="240" />
<!-- Features -->
<property name="hibernate.connection.autoReconnect" value = "true"/>
<property name="hibernate.show_sql" value = "false" />
<property name="hibernate.connection.autoReconnectForPools" value = "true"/>
<property name="hibernate.connection.is-connection-validation-required" value = "true"/>
</properties>
</persistence-unit>
</persistence>
my Handler class
public class Handler implements RequestHandler<Map<String, Object>, ApiGatewayResponse> {
private static final Logger logger = LoggerFactory.getLogger(TestService.class);
#Autowired
private IBaseService service;
#Override
public ApiGatewayResponse handleRequest(Map<String, Object> input, Context context) {
List<Wizard> prueba = service.getWizards();
Map<String, Wizard> response = new HashMap<>();
Response responseBody = new Response("success", response);
try {
for (Wizard entity : prueba) {
response.put(entity.getName(), entity);
}
responseBody.setInput(response);
} catch (Exception e) {
logger.error(e.getMessage(), e);
responseBody.setMessage("Fail: " + e.getMessage());
}
return ApiGatewayResponse.builder().setStatusCode(200).setObjectBody(responseBody)
.setHeaders(Collections.singletonMap("This is a test", "AWS Lambda & serverless")).build();
}
}
my serverless.yml
service: aws-java-maven # NOTE: update this with your service name
provider:
name: aws
runtime: java8
iamRoleStatements:
- Effect: "Allow"
Action:
- "mysql:*"
Resource: "*"
package:
artifact: target/hello-dev.jar
functions:
get-transactions:
handler: com.serverless.Handler

How can I generate UTF8 table using hibernate

I am using hibernate version: 4.3.8.Final
In web.xml i have:
`
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
<property name="hibernate.validator.apply_to_ddl" value="true" />
<property name="hibernate.connection.CharSet" value="utf8" />
<property name="hibernate.connection.characterEncoding" value="utf8" />
<property name="hibernate.connection.useUnicode" value="true" />
<property name="connection.provider_class" value="org.hibernate.connection.C3P0ConnectionProvider"/>
<property name="hibernate.c3p0.min_size" value="5"/>
<property name="hibernate.c3p0.max_size" value="20"/>
<property name="hibernate.c3p0.timeout" value="300"/>
<property name="hibernate.c3p0.max_statements" value="50"/>
<property name="hibernate.c3p0.idle_test_period" value="300"/>`
When I run app, hibernate generate all table in: latin1_swedish_ci
I read a lot of pages on google, but nothing help me.
How can I generate utf8 table using hibernate? IT IS POSSIBLE?
Thank you for any help.
If you check the org.hibernate.dialect.MySQL5InnoDBDialect implementation you'll find this :
package org.hibernate.dialect;
/**
* #author Gavin King, Scott Marlow
*/
public class MySQL5InnoDBDialect extends MySQL5Dialect {
public boolean supportsCascadeDelete() {
return true;
}
public String getTableTypeString() {
return " ENGINE=InnoDB";
}
public boolean hasSelfReferentialForeignKeyBug() {
return true;
}
}
So you can see in getTableTypeString the return value, what you can do is extends the MySQLDialect class and override getTableTypeString method to return
"ENGINE=InnoDB DEFAULT CHARSET=utf8";
Otherwise (you can try a lazy solution) try with adding UseUnicode=true&characterEncoding=utf8 at the end of your database connection url

Tomcat + Hibernate - can't persist any data

I have a problem with my new app. It's webapp with JAX-RS REST API, I have placed it on Tomcat 9.
Everything was good, my app can fetch data from localhost database (PSQL). I don't know why, but when i want to persist data -> it's returning me no error at all, but there is no mark after persisting data on database.
#POST
#Produces(MediaType.APPLICATION_JSON )
#Path("/register")
public Response register(#FormParam("email") String email, #FormParam("password") String password,
#FormParam("phoneNumber") String phoneNumber) {
UserEntity newUser = new UserEntity();
newUser.setEmail(email);
newUser.setPassword(password);
newUser.setPhoneNumber(phoneNumber);
newUser.setEntryDate(new Date());
AuthorizationDAO.put(newUser);
and DAO method:
public static <T extends AbstractTechnicalEntity> void put(T entity) {
em.persist(entity);
}
It's not a problem with connection - as I said, I can select data from this database, even from this table.
persistence.xml - > database conf
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/*****" />
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver" />
<property name="javax.persistence.jdbc.user" value="******" />
<property name="javax.persistence.jdbc.password" value="*****" />
<property name="hibernate.show_sql" value="true" />
</properties>
Any ideas?

WebSphere no persistent classes found for query class

I'm new to WebSphere and am trying to host a simple website that I can log into using an Oracle database.
I can get to my website, but when I try and log in I get the following warning and am not able to log in:
[WARNING ] Detected JSESSIONID with invalid length; expected length of 23, found 28, setting: 99D3CCB2FF585D3B3E80293BFA1C to null.
[WARNING ] HHH000183: no persistent classes found for query class: select a FROM com.model.User a where username = 'user'
No entity found for query
The warning no persistent classes found for query class: is being thrown when I try and create the query to log in inside of my CommonServiceImple.java:
Query query = getEntityManager().createQuery("select a FROM " + className + " a where username = '" + username + "'");
The No entity found for query is caused in the next line trying to run the query. This is because the query object is null because of the previous warning: Object obj = query.getSingleResult();.
server.xml
<dataSource id="jdbc/test" jndiName="jdbc/test" type="javax.sql.DataSource">
<jdbcDriver id="oracle-driver" libraryRef="oracle-lib">
<library></library>
</jdbcDriver>
<connectionManager id="ConnectionManager" minPoolSize="1" numConnectionsPerThreadLocal="10"/>
<properties.oracle URL="jdbc:oracle:thin:#crappie.ddvc.local:1521:STILOG" password="password" user="user"/>
</dataSource>
<library id="oracle-lib">
<fileset dir="C:/Users/user/workspace/WebAdmin/WebContent/WEB-INF/lib/" includes="ojdbc6.jar"/>
</library>
web.xml
<resource-ref>
<description>DataSource</description>
<res-ref-name>jdbc/test</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
<mapped-name>jdbc/test</mapped-name>
</resource-ref>
ibm-web-bnd.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-bnd
xmlns="http://websphere.ibm.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://websphere.ibm.com/xml/ns/javaee http://websphere.ibm.com/xml/ns/javaee/ibm-web-bnd_1_0.xsd"
version="1.0">
<virtual-host name="default_host" />
<resource-ref name="jdbc/test" binding-name="jdbc/test"/>
</web-bnd>
persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="pu1">
</persistence-unit>
</persistence>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd">
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="commonService" class="com.service.CommonServiceImpl"/>
<bean id="mainMenuService" class="com.service.MainMenuServiceImpl"/>
<bean id="storeFilterService" class="com.service.StoreFilterServiceImpl"/>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="database" value="ORACLE" />
<property name="showSql" value="true" />
</bean>
</property>
<property name="persistenceUnitManager" ref="pum"/>
<property name="persistenceUnitName" value="pu1" />
<property name="jpaProperties">
<props>
<prop key="org.hibernate.envers.store_data_at_delete">true</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>jdbc/test</value>
</property>
<property name="cache"
value="true"/>
<property name="lookupOnStartup"
value="true"/>
<property name="resourceRef"
value="true"/>
</bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="pum"
class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="persistenceXmlLocations">
<list>
<value>classpath:META-INF/persistence.xml</value>
</list>
</property>
<property name="defaultDataSource" ref="dataSource"></property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="loginAction" scope="prototype" class="com.action.LoginAction">
<constructor-arg ref="commonService" />
</bean>
<bean id="userAction" scope="prototype" class="com.action.UserAction">
<constructor-arg ref="commonService" />
</bean>
</beans>
Nothing interesting in User.java
#Entity
#Table(name="WEB_PAGE_USERS")
public class User {
#Id
#GeneratedValue(strategy=GenerationType.AUTO, generator="seq")
#SequenceGenerator(name="seq", sequenceName="WEB_PAGE_USERS_ID_SEQ")
private Integer id;
private String username;
private String password;
private String name;
//...
}
Or the ComonServiceImpl.java
#Transactional
public class CommonServiceImpl implements CommonService{
private EntityManager em;
#PersistenceContext(unitName="pu1")
public void setEntityManager(EntityManager em) {
this.em = em;
}
// MTD added for explicit order by
#SuppressWarnings("unchecked")
public List<Object> findAll(String name) {
getEntityManager().clear();
String sql = "select a FROM " + name + " a";
Query query = getEntityManager().createQuery(sql);
return query.getResultList();
}
//...(other sql selects, updates, inserts)
}
LoginAction.java
public class LoginAction extends ActionSupport {
private static final long serialVersionUID = 1L;
private CommonService service;
private String username;
private String password;
private String environment;
public LoginAction(CommonService service) {
this.service = service;
}
public String execute() throws Exception {
return Action.SUCCESS;
}
#SuppressWarnings({ "unchecked", "static-access" })
public String login() throws Exception {
//Encrypt input password
CEncrypt cEncrypt = new CEncrypt();
String encryptedPwd = cEncrypt.encryptString(password);
//Get user by Username
User user = (User) service.findUser(username, User.class.getName());
//Check if input password is the same as the password in the database & login
if (user!=null && user.getPassword().equals(encryptedPwd)) {
#SuppressWarnings("rawtypes")
Map session = ActionContext.getContext().getSession();
session.put("logged-in","true");
session.put("loggedIn", "true");
session.put("WebAdminUserID", user.getUsername());
session.put("WebAdminUsername", user.getName());
session.put("WebAdminID", user.getRole_id());
return Action.SUCCESS;
} else {
return Action.ERROR;
}
}
//...
}
UPDATE
I was able to test my connection to the datasource by manually calling the lookup. But since my website is built on the persistence unit I would like to fix that error instead of re-writing the project to call the connection directly like this:
public String getEnvironment() {
try
{
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource test = (DataSource)envCtx.lookup("jdbc/test");
Connection con = test.getConnection();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from WEB_PAGE_USERS where username = 'user'");
while(rs.next()){
System.out.println("username="+rs.getString("username")+", password="+rs.getString("password")+", role id="+rs.getString("role_id"));
}
// environment = "[" + (String)envCtx.lookup("Environment") + "]";
} catch (Exception e)
{
System.out.println("Environment Exception: " + e.getMessage());
}
return environment;
}
Which does return the correct data username=user, password=password, role id=1
To fix my answer I had to add every model class I had with the #Entity annotation to my persistence.xml file. It seems that even though I am using an entityManager I still needed to specify all of the #Entity classes (normally in Tomcat the entityManager would automatically find all of the classes).
Also I was getting that [WARNING ] Detected JSESSIONID with invalid length; expected length of 23, found 28, setting: 99D3CCB2FF585D3B3E80293BFA1C to null. warning which was causing my session to be cleared each time a page loaded (makes it hard to stay logged in). So I increased the length to 28 in the server.xml on WebSphere.
server.xml
<server description="new server">
<!-- Enable features -->
<featureManager>
<feature>jsp-2.2</feature>
<feature>jndi-1.0</feature>
<feature>jdbc-4.0</feature>
<feature>localConnector-1.0</feature>
<feature>servlet-3.0</feature>
<feature>jaxrs-1.1</feature>
</featureManager>
<!-- To access this server from a remote client add a host attribute to the following element, e.g. host="*" -->
<httpEndpoint host="localhost" httpPort="9080" httpsPort="9443" id="defaultHttpEndpoint"/>
<dataSource id="jdbc/test" jndiName="jdbc/test" type="javax.sql.DataSource">
<jdbcDriver id="oracle-driver" libraryRef="oracle-lib"/>
<connectionManager id="ConnectionManager" minPoolSize="1" numConnectionsPerThreadLocal="10"/>
<properties.oracle URL="jdbc:oracle:thin:#crappie.local:1521:STILOG" password="password" user="user"/>
</dataSource>
<library id="oracle-lib">
<fileset dir="C:/Users/user/workspace/WebAdmin/WebContent/WEB-INF/lib/" includes="ojdbc6.jar"/>
</library>
<applicationMonitor updateTrigger="mbean"/>
<webApplication id="WebAdmin" location="WebAdmin.war" name="WebAdmin"/>
<httpSession idLength="28"></httpSession>
</server>
persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="pu1">
<class>com.model.App</class>
<class>com.model.AudioType</class>
<class>com.model.AuditRevisionEntity</class>
<class>com.model.ClosedGroup</class>
<class>com.model.ClosedSchedule</class>
<class>com.model.ClosedScheduleGroup</class>
<class>com.model.Department</class>
<class>com.model.Dnis</class>
<class>com.model.DnisVoiceTalent</class>
<class>com.model.GlobalXferGroupTemplate</class>
<class>com.model.Language</class>
<class>com.model.Location</class>
<class>com.model.MainMenu</class>
<class>com.model.NameValue</class>
<class>com.model.NameValueFunction</class>
<class>com.model.NameValueType</class>
<class>com.model.Peg</class>
<class>com.model.PegType</class>
<class>com.model.PharmacyConfig</class>
<class>com.model.Promo</class>
<class>com.model.PromoMessage</class>
<class>com.model.PromoSchedule</class>
<class>com.model.PromoType</class>
<class>com.model.Role</class>
<class>com.model.Schedule</class>
<class>com.model.ScheduleHours</class>
<class>com.model.ScheduleRecording</class>
<class>com.model.ScheduleType</class>
<class>com.model.Server</class>
<class>com.model.SpecialSchedule</class>
<class>com.model.SpecialScheduleRecording</class>
<class>com.model.Store</class>
<class>com.model.StoreAudio</class>
<class>com.model.StoreClosedGroup</class>
<class>com.model.StoreDepartment</class>
<class>com.model.StorePromo</class>
<class>com.model.StoreSchedule</class>
<class>com.model.StoreSpcSchedule</class>
<class>com.model.StoreType</class>
<class>com.model.StoreXferGroup</class>
<class>com.model.SystemMaintenance</class>
<class>com.model.TargetSystem</class>
<class>com.model.Timezone</class>
<class>com.model.Title</class>
<class>com.model.User</class>
<class>com.model.UserWebPage</class>
<class>com.model.UserWebPageAccess</class>
<class>com.model.UserWebPageClassType</class>
<class>com.model.VoiceTalent</class>
</persistence-unit>
</persistence>

Implementation of timeout in LDAP

I have been handling an application in which we are using LDAP to fetch user details. Sometimes it will take more time to fetch user details. I want to implement time out on methods that fetch details so that we can avoid hanging transactions in server in worst case.
Here we are using LdapUtil class in which we have configured LdapTemplate class to fetch the required details.
How can we implement timeout on LDAP methods?
(In this case ldapTemplate.search(...) methods)
public class LdapUtil {
#Autowired(required = true)
#Qualifier(value = "ldapTemplateApp")
LdapTemplate ldapTemplate;
public Set < ProductGroup > findProducts(String UserId) {
final Set < ProductGroup > products = newHashSet();
// Lookup the user
String usrFilter = String.format(USERID_FILTER, globalUserId);
ldapTemplate.search("ou=Members", usrFilter, // note this line
new NameClassPairCallbackHandler() {
public void handleNameClassPair(NameClassPair nameClassPair) {
SearchResult result = (SearchResult) nameClassPair;
String user = result.getNameInNamespace();
String GrpFilter = String.format(GROUP_FILTER, user);
List < String > zonePrefixes = ldapTemplate.search("Zones", GrpFilter, // note this line
new AttributesMapper() {
public Object mapFromAttributes(Attributes attributes) throws NamingException {
return substringBeforeLast((String) attributes.get("cn").get(), "-") + "-";
}
});
}
});
products.remove(null);
return newHashSet(products);
}
}
We have one LDAP.xml in which ldapTemplete is configured
<beans xmlns="------">
<!-- LDAP -->
<bean id="contextSourceApp" class="org.springframework.ldap.pool.factory.PoolingContextSource">
<property name="contextSource" ref="contextSourceTargetApp" />
<property name="dirContextValidator">
<bean id="dirContextValidator"
class="org.springframework.ldap.pool.validation.DefaultDirContextValidator"/>
</property>
<property name="testOnBorrow" value="true" />
</bean>
<bean id="contextSourceTargetApp" class="org.springframework.ldap.core.support.LdapContextSource">
<property name="url" value="${ldap.url}" />
<property name="base" value="${ldap.base.}" />
<property name="userDn" value="${ldap.user}" />
<property name="password" value="${ldap.password}" />
<property name="pooled" value="false" />
</bean>
<bean id="ldapTemplateApp" class="org.springframework.ldap.core.LdapTemplate">
<constructor-arg ref="contextSourceApp" />
</bean>
I have few queries:
How can we implement the TIMEOUT for LDAP methods and how to configure it?(In which class of LDAP framework timeout settings will be there)
Is there any way to configure them in xml file i.e. LDAP.xml(in this case)?
I found a solution.
I have added the following property in my ldap.xml file. So far it worked for me.
<bean id="contextSourceTargetApp"
class="org.springframework.ldap.core.support.LdapContextSource">
<property name="baseEnvironmentProperties">
<map>
<entry key="com.sun.jndi.ldap.connect.timeout" value="5000" />
</map>
</property>
</bean>
Please post any other solution if you have any idea about LDAP timeout implementation.
For ActiveDirectoryLdapAuthenticationProvider the solution with ldap.xml file did not work for me. Instead I added a jndi.properties file to the classpath with the following content:
com.sun.jndi.ldap.connect.timeout=500

Categories

Resources