Spring boot Active Directory/LDAP connection - java

I already connect with AD from spring boot for login purposes but i can not mak searches. My configuration is
#Configuration
public class LdapTemplateConfig {
#Bean
public LdapTemplate ldapTemplate() {
LdapTemplate ldapTemplate = new LdapTemplate(ldapContextSource());
return ldapTemplate;
}
#Bean
public LdapContextSource ldapContextSource() {
String url = "ldap://127.0.0.1:389";
String base = "DC=demo1,DC=demo2,DC=demo3,DC=demo4";
LdapContextSource ldapContextSource = new LdapContextSource();
ldapContextSource.setUrl(url);
ldapContextSource.setUserDn(
"CN=User Name,OU=Common Users OU,OU=RDP enabled Users OU,OU=Operator Users OU,OU=Admin Users OU,DC=demo1,DC=demo2,DC=demo3,DC=demo4");
ldapContextSource.setPassword("password");
// ldapContextSource.setReferral("follow");
ldapContextSource.afterPropertiesSet();
return ldapContextSource;
}
}
#Service
public class LDAPServiceImpl {
#Autowired
private LdapTemplate ldapTemplate;
public void getUserDetails(String userName) {
if (null != ldapTemplate) {
List<String> vals = ldapTemplate.search(query().where("objectclass").is("person"),
new AttributesMapper<String>() {
#Override
public String mapFromAttributes(Attributes attributes) throws NamingException {
return attributes.get("sAMAccountName").get().toString();
}
});
for (String s : vals) {
log.info("attr : " + s);
}
} else {
log.info("Templates is null");
}
}
}
So, when i call the function getUserDetails() from controller it returns "Templates is null"

Spring dependency injection can be done via constructor or setter.
#Autowired
private LdapTemplate ldapTemplate;
Your LDAPServiceImpl class does not have constructor taking LdapTemplate as an argument & the ldapTemplate is declared as private. So constructor injection & setter injection both are not possible. To use setter injection, there needs to be a setter method for ldapTemplate like this:
public void setLdapTemplate(LdapTemplate ldapTemplate){
this.ldapTemplate=ldapTemplate;
}

I solved the problem thanks all for your help
#Configuration
public class LdapTemplateConfig {
private final Logger log = LoggerFactory.getLogger(LdapTemplateConfig.class);
#Bean(name = "ldapTemplate")
// #Scope("singleton")
public LdapTemplate ldapTemplate(LdapContextSource contextSource) {
LdapTemplate ldapTemplate = new LdapTemplate(contextSource);
return ldapTemplate;
}
#Bean(name = "contextSource")
// #Scope("singleton")
public LdapContextSource ldapContextSource() {
String url = "ldap://127.0.0.1:389";
String base = "DC=intranet,DC=demo,DC=com";
if (isConfigurationValid(url, base)) {
LdapContextSource ldapContextSource = new LdapContextSource();
ldapContextSource.setUrl(url);
ldapContextSource.setBase(base);
ldapContextSource.setUserDn(
"CN=Test User,OU=Common Users OU,OU=RDP enabled Users OU,DC=intranet,DC=demo,DC=com");
ldapContextSource.setPassword("password");
ldapContextSource.setReferral("follow");
// lcs.setPooled(false);
// lcs.setDirObjectFactory(DefaultDirObjectFactory.class);
ldapContextSource.afterPropertiesSet();
return ldapContextSource;
}
return null;
}
public boolean isConfigurationValid(String url, String base) {
if ((url == null) || url.isEmpty() || (base == null) || base.isEmpty()) {
log.error("Warning! Your LDAP server is not configured.");
log.info("Did you configure your LDAP settings in your application.yml?");
return false;
} else {
return true;
}
}
}
#Service
public class LDAPServiceImpl {
private final Logger log = LoggerFactory.getLogger(LDAPServiceImpl.class);
#Autowired
LdapTemplate ldapTemplate;
public User getUserDetails(String userName) {
AndFilter filter = new AndFilter();
filter.and(new EqualsFilter("objectclass", "person")).and(new EqualsFilter("employeeID", "700335"));
List<User> users = ldapTemplate.search("", filter.encode(), new UaserAttributesMapper());
if (!users.isEmpty()) {
return users.get(0);
}
return null;
// List<User> list =
// ldapTemplate.search(query().where("sAMAccountName").is("a.keskempes"),
// new UserAttributesMapper());
// if ((list != null) && !list.isEmpty()) {
// return list.get(0);
// }
// return null;
}
private class UaserAttributesMapper implements AttributesMapper<User> {
#Override
public User mapFromAttributes(Attributes attributes) throws NamingException {
User user;
if (attributes == null) {
return null;
}
user = new User();
if (attributes.get("objectclass") != null) {
user.setObjectclass(attributes.get("objectclass").get().toString());
}
if (attributes.get("distinguishedname") != null) {
user.setDistinguishedname(attributes.get("distinguishedname").get().toString());
}
if (attributes.get("userPassword") != null) {
user.setUserPassword(attributes.get("userPassword").get().toString());
}
if (attributes.get("cn") != null) {
user.setCn(attributes.get("cn").get().toString());
}
if (attributes.get("telephoneNumber") != null) {
user.setTelephoneNumber(attributes.get("telephoneNumber").get().toString());
}
// if (attributes.get("lastlogoff") != null) {
// // user.setLastlogoff(DateTimeFormat.forPattern("yyyy-MM-dd
// // HH:mm:ss")
// //
// .parseDateTime(attributes.get("lastlogoff").get().toString()));
// DateTimeFormatter formatter =
// DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
// DateTime dt =
// formatter.parseDateTime(attributes.get("lastlogoff").get().toString());
// user.setLastlogoff(new DateTime(
//
// dt
//
// ));
// }
if (attributes.get("userprincipalname") != null) {
user.setUserprincipalname(attributes.get("userprincipalname").get().toString());
}
if (attributes.get("department") != null) {
user.setDepartment(attributes.get("department").get().toString());
}
if (attributes.get("company") != null) {
user.setCompany(attributes.get("company").get().toString());
}
if (attributes.get("mail") != null) {
user.setMail(attributes.get("mail").get().toString());
}
if (attributes.get("streetAddress") != null) {
user.setStreetAddress(attributes.get("streetAddress").get().toString());
}
if (attributes.get("st") != null) {
user.setSt(attributes.get("st").get().toString());
}
if (attributes.get("postalCode") != null) {
user.setPostalCode(attributes.get("postalCode").get().toString());
}
if (attributes.get("l") != null) {
user.setL(attributes.get("l").get().toString());
}
if (attributes.get("description") != null) {
user.setDescription(attributes.get("description").get().toString());
}
if (attributes.get("c") != null) {
user.setC(attributes.get("c").get().toString());
}
if (attributes.get("countryCode") != null) {
user.setCountryCode(attributes.get("countryCode").get().toString());
}
if (attributes.get("cn") != null) {
user.setCn(attributes.get("cn").get().toString());
}
if (attributes.get("sn") != null) {
user.setSn(attributes.get("sn").get().toString());
}
if (attributes.get("employeeID") != null) {
user.setEmployeeId(attributes.get("employeeID").get().toString());
}
if (attributes.get("lastLogon") != null) {
// user.setLastLogon(DateTimeFormat.forPattern("yyyy-MM-dd
// HH:mm:ss")/*
// .parseDateTime(attributes.get("lastLogon").get().toString()));*/
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss");
DateTime dt = formatter.parseDateTime(attributes.get("lastLogon").get().toString());
user.setLastLogon(new DateTime(
dt
));
}
if (attributes.get("memberof") != null) {
user.setMemberof(attributes.get("memberof").get().toString());
}
if (attributes.get("givenname") != null) {
user.setGivenname(attributes.get("givenname").get().toString());
}
if (attributes.get("logoncount") != null) {
user.setLogoncount(attributes.get("logoncount").get().toString());
}
if (attributes.get("displayName") != null) {
user.setDisplayname(attributes.get("displayName").get().toString());
}
return user;
}
}
}
and into the controller i put
#Autowired
private LDAPServiceImpl lDAPServiceImpl;
com.ppc.ptol2.service.impl.User find = lDAPServiceImpl.getUserDetails("sgad");
as you can see the solution is working perfectly but needds some improvements

Related

Springboot Project use AbstractRoutingDataSource question

My project uses springboot+springDataJpa+shiro.
Because my server database uses the master and salve method, so I need to call my code to connect to the two databases, I designed to use the AbstractRoutingDataSource + aop method. Now I have a problem, I think it may be caused by shiro.
I know that the connection switching is performed by the getconnection() method of AbstractRoutingDataSource, and I cannot manually control this method. The problem now is that my getconnection() is executed at most twice in an interface request. Let me post my code and describe it:
#Order(0)
#Aspect
#Component
public class RoutingAopAspect {
#Around("#annotation(targetDataSource)")
public Object routingWithDataSource(ProceedingJoinPoint joinPoint, TargetDataSource targetDataSource) throws Throwable {
try {
DynamicRoutingDataSourceContext.setRoutingDataSource(targetDataSource.value());
return joinPoint.proceed();
} finally {
DynamicRoutingDataSourceContext.removeRoutingDataSource();
}
}
}
public class DynamicRoutingDataSourceContext {
public static final String MASTER = "master";
public static final String SLAVE = "slave";
private static final ThreadLocal<Object> threadLocalDataSource = new ThreadLocal<>();
public static void setRoutingDataSource(Object dataSource) {
if (dataSource == null) {
throw new NullPointerException();
}
threadLocalDataSource.set(dataSource);
// System.err.println(Thread.currentThread().getName()+" set RoutingDataSource : " + dataSource);
}
public static Object getRoutingDataSource() {
Object dataSourceType = threadLocalDataSource.get();
if (dataSourceType == null) {
threadLocalDataSource.set(DynamicRoutingDataSourceContext.MASTER);
return getRoutingDataSource();
}
// System.err.println(Thread.currentThread().getName()+" get RoutingDataSource : " + dataSourceType);
return dataSourceType;
}
public static void removeRoutingDataSource() {
threadLocalDataSource.remove();
// System.err.println(Thread.currentThread().getName()+" remove RoutingDataSource");
}
}
#EnableTransactionManagement
#Configuration
public class DataSourceConfig {
#Value("${datasource.master.url}")
private String masterUrl;
#Value("${datasource.master.username}")
private String masterUsername;
#Value("${datasource.master.password}")
private String masterPassword;
#Value("${dataSource.driverClass}")
private String masterDriverClassName;
#Value("${datasource.slave.url}")
private String slaveUrl;
#Value("${datasource.slave.username}")
private String slaveUsername;
#Value("${datasource.slave.password}")
private String slavePassword;
#Value("${dataSource.driverClass}")
private String slaveDriverClassName;
#Bean(name = "masterDataSource")
public DataSource masterDataSource(){
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(masterUrl);
datasource.setUsername(masterUsername);
datasource.setPassword(masterPassword);
datasource.setDriverClassName(masterDriverClassName);
return datasource;
}
#Bean(name = "slaveDataSource")
public DataSource slaveDataSource(){
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(slaveUrl);
datasource.setUsername(slaveUsername);
datasource.setPassword(slavePassword);
datasource.setDriverClassName(slaveDriverClassName);
return datasource;
}
#Primary
#Bean
public DynamicRoutingDataSource dynamicDataSource(#Qualifier(value = "masterDataSource") DataSource masterDataSource,
#Qualifier(value = "slaveDataSource") DataSource slaveDataSource) {
Map<Object, Object> targetDataSources = new HashMap<>(2);
targetDataSources.put(DynamicRoutingDataSourceContext.MASTER, masterDataSource);
targetDataSources.put(DynamicRoutingDataSourceContext.SLAVE, slaveDataSource);
DynamicRoutingDataSource dynamicRoutingDataSource = new DynamicRoutingDataSource();
dynamicRoutingDataSource.setTargetDataSources(targetDataSources);
dynamicRoutingDataSource.setDefaultTargetDataSource(masterDataSource);
dynamicRoutingDataSource.afterPropertiesSet();
return dynamicRoutingDataSource;
}
}
public class DynamicRoutingDataSourceContext {
public static final String MASTER = "master";
public static final String SLAVE = "slave";
private static final ThreadLocal<Object> threadLocalDataSource = new ThreadLocal<>();
public static void setRoutingDataSource(Object dataSource) {
if (dataSource == null) {
throw new NullPointerException();
}
threadLocalDataSource.set(dataSource);
// System.err.println(Thread.currentThread().getName()+" set RoutingDataSource : " + dataSource);
}
public static Object getRoutingDataSource() {
Object dataSourceType = threadLocalDataSource.get();
if (dataSourceType == null) {
threadLocalDataSource.set(DynamicRoutingDataSourceContext.MASTER);
return getRoutingDataSource();
}
// System.err.println(Thread.currentThread().getName()+" get RoutingDataSource : " + dataSourceType);
return dataSourceType;
}
public static void removeRoutingDataSource() {
threadLocalDataSource.remove();
// System.err.println(Thread.currentThread().getName()+" remove RoutingDataSource");
}
}
This is the relevant basic configuration of AbstractRoutingDataSource.
I defined an aspect to get the parameters of #TargetDataSource in the method. This parameter is a data source that needs to be executed currently. I think there is no problem with my configuration.
Then I will use #TargetDataSource on my service method, and I use shiro, shiro’s doGetAuthorizationInfo() method and doGetAuthenticationInfo() are executed before my service, and both methods need to call my userservice .
Then the problem now is that after calling the doGetAuthorizationInfo() and doGetAuthenticationInfo() methods, they will automatically execute the getconnection() method of AbstractRoutingDataSource to switch the data source, and then execute to my own service, it will not execute the getconnection() method. , This is what I said getconnection() is executed at most twice in an interface request.
#Slf4j
#Component
public class ShiroRealm extends AuthorizingRealm {
#Autowired
#Lazy
private UserService userService;
#Autowired
CacheUtil cacheUtil;
#Override
public boolean supports(AuthenticationToken token) {
return token instanceof JwtToken;
}
#Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
String username = JwtUtil.getClaim(principals.toString(), "username");
User user = userService.getUserByUsername(username);
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
simpleAuthorizationInfo.addRole(user.getRole());
return simpleAuthorizationInfo;
}
#Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) {
String token = (String) auth.getCredentials();
String username = JwtUtil.getClaim(token, "username");
if (username == null) {
throw new AuthenticationException("token invalid");
}
User user = userService.getUserByUsername(username);
if (user == null) {
throw new AuthenticationException("User didn't existed!");
}
if (JwtUtil.verify(token, username, user.getPassword(), TokenType.ACCESS_TOKEN) &&
cacheUtil.hasKey(CacheKey.ACCESS_TOKEN_KEY + token)
) {
return new SimpleAuthenticationInfo(token, token, "userRealm");
}
throw new AuthenticationException("Token expired or incorrect");
}
}
#Service
public class PageServiceImpl implements PageService {
#Autowired
PageRepository pageRepository;
#Override
#TargetDataSource("slave")
#Transactional(rollbackFor = Exception.class)
public List<Page> adminFindAll() {
List<Page> pageList = pageRepository.findAll();
if (pageList.isEmpty()) {
throw new CustomNotFoundException("page list not found");
}
return pageList;
}
}
I don’t know if my description is clear. If it is not clear, please ask questions. I hope to get your help, thanks very much!

How to use an object that got return in another class

I have this class, that returns an object, if the email, password and category (enum) are correct:
public class LoginManager {
private static LoginManager instance = new LoginManager();
private LoginManager() {
super();
}
public static LoginManager getInstance() {
return instance;
}
public ClientFacade login(String email, String password, ClientType clientType) throws SQLException {
if (clientType == ClientType.Administrator) {
AdminFacade adminFacade = new AdminFacade();
if (adminFacade.login(email, password) == true) {
return adminFacade;
} else {
return null;
}
} else if (clientType == ClientType.Company) {
CompanyFacade companyFacade = new CompanyFacade();
if (companyFacade.login(email, password) == true) {
return companyFacade;
} else {
return null;
}
} else if (clientType == ClientType.Customer) {
CustomerFacade customerFacade = new CustomerFacade();
if (customerFacade.login(email, password) == true) {
return customerFacade;
} else {
return null;
}
} else {
return null;
}
}
}
How do I use that object in another class?
This is the other class, that is supposed to use the object that return:
public class Test {
CouponsDBDAO coupDBD = new CouponsDBDAO();
CouponExpirationDailyJob dailyJob =
new CouponExpirationDailyJob(coupDBD, false);
LoginManager Log = LoginManager.getInstance();
public void testAll() {
try {
Log.login("admin#admin.com", "admin", ClientType.Administrator); {
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
}
How do I use now the adminFacade for example?
try
LoginManager Log = new LoginManager();
public void testAll() {
try {
ClientFacade facade = Log.login("admin#admin.com", "admin", ClientType.Administrator);
facade.DoSomethingUseful();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}

How to fix API authentication problem in Kotlin Android app?

I developed an API in Laravel for reading some data with authentication. Now in my app I need to send the token in my header for API to respond. Every time i login with app, I'm getting token without problem, but i can't provide token in header and it's returning a null token response. Now every time i reopen my app everything is fine but problem appear only when i login.
Please read my code and say if you found the bug.
This is my (AppServer.kt). I use this for adding the token to my header
class AppServer private constructor(private val client: INetworkClient) : IAppServer {
private val gson = Gson()
companion object {
private var instance: AppServer? = null
fun getInstance(): AppServer {
val token = AppLoggedInUser.getInstance()?.userProfile?.userToken ?: ""
if (instance == null)
instance = AppServer(
MixedNetworkClient(
mHeaders = mutableMapOf(
Headers.CONTENT_TYPE to "application/json",
"X-Requested-With" to "XMLHttpRequest",
"Authorization" to "Bearer $token"
),
mBasePath = "https://myWebsiteURL.com/"
)
)
return instance!!
}
}
override fun getPurchasedItems(): Observable<Pair<ResponseState, List<OrderInfo>?>> {
return Observable.create<Pair<ResponseState, List<OrderInfo>?>> { emitter ->
val (items, statusCode, msg, error) =
client.get(
"api/users/${AppLoggedInUser.getInstance().userProfile.userId}/orders",
{ responseStr ->
try {
val orders = mutableListOf<OrderInfo>()
val jArray = JSONArray(responseStr)
for (i in 0 until jArray.length()) {
val jObject = jArray.getJSONObject(i)
val order =
gson.fromJson<OrderInfo>(jObject.toString(), OrderInfo::class.java)
if (order.isPaymentSuccessful)
orders.add(order)
}
if (orders.isEmpty())
emitter.onNext(pair(empty(), null))
else
emitter.onNext(pair(success(), orders))
} catch (t: Throwable) {
Timber.e(t)
emitter.onNext(pair(ResponseState.internalError(t), null))
}
})
}.attachSchedulers()
}
override fun getDiscountDetailsById(id: Int): Observable<Pair<ResponseState, DiscountDetails?>> {
return Observable.create<Pair<ResponseState, DiscountDetails?>> { emitter ->
try {
client.post("api/post", listOf("post_id" to id.toString())) { responseStr ->
val jObject = JSONObject(responseStr)
var discount: DiscountDetails? = null
if (jObject.has("ID"))
discount =
gson.fromJson<DiscountDetails>(jObject.toString(), DiscountDetails::class.java)
if (discount != null)
emitter.onNext(pair(success(), discount))
else
emitter.onNext(pair(notFound404(), null))
}
} catch (t: Throwable) {
Timber.e(t)
emitter.onNext(pair(ResponseState.internalError(t), null))
}
}.attachSchedulers()
}
}
and this is my (AppLoggedInUser.java) I use it for getting my current user token.
package com.fartaak.gilantakhfif.utilities;
import android.content.Context;
import com.fartaak.gilantakhfif.backend.server.ParsingGSON;
import com.fartaak.gilantakhfif.model.UserProfile;
public class AppLoggedInUser extends AppPreferences {
public static final String NAM_LOGIN_SdPs = "login";
public static final String KEY_USER_TOKEN = "tokenPor";
private static AppLoggedInUser mInstance;
private final String KEY_LOGIN = "prefP";
private boolean isCompletelyRegistered;
public static void init(Context context) {
if (mInstance == null) {
mInstance = new AppLoggedInUser(context);
}
}
public static AppLoggedInUser getInstance() {
if (mInstance != null) {
return mInstance;
} else {
throw new IllegalStateException(
"you should call init to initialize only once per app launch before calling getInstance");
}
}
private AppLoggedInUser(Context context) {
super(NAM_LOGIN_SdPs, context);
}
public String getUserToken() {
return getField(KEY_USER_TOKEN);
}
public void clearUserProfile() {
removeField(KEY_LOGIN);
}
public UserProfile getUserProfile() {
String data = getField(KEY_LOGIN);
if (data == null) {
return null;
}
//return new Gson().fromJson(data, UserProfile.class);
return ParsingGSON.getInstance().getParsingJSONObject(data, UserProfile.class, null);
}
public boolean isRegisterCompleted() {
if (!isCompletelyRegistered) {
UserProfile userProfile = getUserProfile();
if (userProfile.getUserName() == null) {
return false;
} else {
isCompletelyRegistered = true;
}
}
return true;
}
public boolean isUserProfile() {
return isField(KEY_LOGIN);
}
public void setUserProfile(UserProfile userProfile) {
String json = ParsingGSON.getInstance().toJSONObject(userProfile, UserProfile.class, null);
setField(KEY_LOGIN, json);
}
}
I think the problem is with my second class.

JDBC Multi-Row INSERT peformance is horrible

Why would I be getting linear performance on increasing batch sizes for this Spring JDBC implementation. Is there some further tuning I might do (apart from an explain, indice review, and database settings tuning)? I should mention I am running this code against a MySQL 5.6 instance hosted on an AWS db.r3.2xlarge class RDS server.
#Repository
public class JdbcRatePlanLevelCostPriceLogRepository implements Insertable<RatePlanLevelCostPriceLog> {
#Autowired
JdbcTemplate jdbcTemplate;
private static final String INSERT_STATEMENT = InsertStatementBuilder.build();
#Override
public RatePlanLevelCostPriceLog insert(RatePlanLevelCostPriceLog entity) {
jdbcTemplate.execute(INSERT_STATEMENT, new SingleCallbackImpl(entity));
return entity;
}
#Override
public List<RatePlanLevelCostPriceLog> insert(List<RatePlanLevelCostPriceLog> entities) {
jdbcTemplate.batchUpdate(INSERT_STATEMENT, new BatchPreparedStatementSetter() {
#Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
RatePlanLevelCostPriceLog entity = entities.get(i);
PreparedStatementTranslator.translate(ps, entity);
}
#Override
public int getBatchSize() {
return entities.size();
}
});
return entities;
}
private static class InsertStatementBuilder {
static String build() {
StringBuffer colsBuffer = new StringBuffer();
StringBuffer valuesBuffer = new StringBuffer();
colsBuffer.append("INSERT INTO rate_plan_level_cost_price_log(");
valuesBuffer.append("VALUES (");
// handle the #NotNull fields
colsBuffer.append("hotel_id");
colsBuffer.append(",rate_plan_id");
colsBuffer.append(",stay_date");
colsBuffer.append(",rate_plan_level");
colsBuffer.append(",person_count");
colsBuffer.append(",length_of_stay_in_days");
colsBuffer.append(",rpcp_log_seq_num");
colsBuffer.append(",log_action_type_id");
colsBuffer.append(",active_status_type_id");
colsBuffer.append(",supplier_update_date");
colsBuffer.append(",create_date");
colsBuffer.append(",supplier_update_tpid");
colsBuffer.append(",supplier_update_tuid");
colsBuffer.append(",supplier_log_seq_num");
// handle the optional fields
colsBuffer.append(",cost_amount");
colsBuffer.append(",cost_code");
colsBuffer.append(",price_amount");
colsBuffer.append(",change_request_id");
colsBuffer.append(",change_request_id_old");
colsBuffer.append(",lar_amount");
colsBuffer.append(",lar_margin_amount");
colsBuffer.append(",lar_taxes_and_fees_amount");
valuesBuffer.append("?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?");
colsBuffer.append(")");
valuesBuffer.append(")");
return String.join(" ", colsBuffer.toString(), valuesBuffer.toString());
}
}
private static class PreparedStatementTranslator {
static void translate(PreparedStatement ps, RatePlanLevelCostPriceLog entity) throws SQLException {
int i = 0;
// handle the #NotNull fields
ps.setInt(++i, entity.getHotelId());
ps.setInt(++i, entity.getRatePlanId());
ps.setTimestamp(++i, new Timestamp(entity.getStayDate().getTime()));
ps.setInt(++i, entity.getRatePlanLevel());
ps.setInt(++i, entity.getPersonCount());
ps.setInt(++i, entity.getLengthOfStayInDays());
ps.setInt(++i, entity.getRpcpLogSeqNum());
ps.setInt(++i, entity.getLogActionTypeId());
ps.setInt(++i, entity.getActiveStatusTypeId());
ps.setTimestamp(++i, new Timestamp(entity.getSupplierUpdateDate().getTime()));
ps.setTimestamp(++i, new Timestamp(entity.getCreateDate().getTime()));
ps.setInt(++i, entity.getSupplierUpdateTpid());
ps.setInt(++i, entity.getSupplierUpdateTuid());
ps.setInt(++i, entity.getSupplierLogSeqNum());
// handle the optional fields
if (entity.getCostAmount() != null) {
ps.setDouble(++i, entity.getCostAmount());
} else {
ps.setNull(++i, Types.DOUBLE);
}
if (entity.getCostCode() != null) {
ps.setString(++i, entity.getCostCode());
} else {
ps.setNull(++i, Types.VARCHAR);
}
if (entity.getPriceAmount() != null) {
ps.setDouble(++i, entity.getPriceAmount());
} else {
ps.setNull(++i, Types.DOUBLE);
}
if (entity.getChangeRequestId() != null) {
ps.setInt(++i, entity.getChangeRequestId());
} else {
ps.setNull(++i, Types.INTEGER);
}
if (entity.getChangeRequestIdOld() != null) {
ps.setInt(++i, entity.getChangeRequestIdOld());
} else {
ps.setNull(++i, Types.INTEGER);
}
if (entity.getLarAmount() != null) {
ps.setDouble(++i, entity.getLarAmount());
} else {
ps.setNull(++i, Types.DOUBLE);
}
if (entity.getLarMarginAmount() != null) {
ps.setDouble(++i, entity.getLarMarginAmount());
} else {
ps.setNull(++i, Types.DOUBLE);
}
if (entity.getLarTaxesAndFeesAmount() != null) {
ps.setDouble(++i, entity.getLarTaxesAndFeesAmount());
} else {
ps.setNull(++i, Types.DOUBLE);
}
}
}
private class SingleCallbackImpl implements PreparedStatementCallback<Boolean> {
private final RatePlanLevelCostPriceLog entity;
SingleCallbackImpl(RatePlanLevelCostPriceLog entity) {
this.entity = entity;
}
#Override
public Boolean doInPreparedStatement(PreparedStatement ps) throws SQLException,
DataAccessException {
PreparedStatementTranslator.translate(ps, entity);
return ps.execute();
}
}
}
It takes ~250 ms to execute a single record insert and then N * 250 ms for batches of N.

Could not find java.beans.propertydescriptor on android

my app uses another projects which contains references to classes as java.beans.propertydescriptor which is not contained by android libraries.
The situation is the next: my project contains the .jar files with this another projects as libraries. I read that the solution is use an opensource class. I found it, but i dont know how can i add this class to the android .jar file. So, how can i add this class to the android java.beans library?
This is the class i have found:
package java.beans;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Vector;
import org.apache.harmony.beans.internal.nls.Messages;
public class PropertyDescriptor extends FeatureDescriptor {
private Method getter;
private Method setter;
private Class<?> propertyEditorClass;
private boolean constrained;
private boolean bound;
public PropertyDescriptor(String propertyName, Class<?> beanClass,
String getterName, String setterName) throws IntrospectionException {
super();
if (beanClass == null) {
throw new IntrospectionException(Messages.getString("beans.03")); //$NON-NLS-1$
}
if (propertyName == null || propertyName.length() == 0) {
throw new IntrospectionException(Messages.getString("beans.04")); //$NON-NLS-1$
}
this.setName(propertyName);
this.setDisplayName(propertyName);
if (setterName != null) {
if (hasMethod(beanClass, setterName)) {
setWriteMethod(beanClass, setterName);
} else {
throw new IntrospectionException(Messages.getString("beans.20")); //$NON-NLS-1$
}
}
if (getterName != null) {
if (hasMethod(beanClass, getterName)) {
setReadMethod(beanClass, getterName);
} else {
throw new IntrospectionException(Messages.getString("beans.1F")); //$NON-NLS-1$
}
}
}
public PropertyDescriptor(String propertyName, Method getter, Method setter)
throws IntrospectionException {
super();
if (propertyName == null || propertyName.length() == 0) {
throw new IntrospectionException(Messages.getString("beans.04")); //$NON-NLS-1$
}
this.setName(propertyName);
this.setDisplayName(propertyName);
setWriteMethod(setter);
setReadMethod(getter);
}
public PropertyDescriptor(String propertyName, Class<?> beanClass)
throws IntrospectionException {
String getterName;
String setterName;
if (beanClass == null) {
throw new IntrospectionException(Messages.getString("beans.03")); //$NON-NLS-1$
}
if (propertyName == null || propertyName.length() == 0) {
throw new IntrospectionException(Messages.getString("beans.04")); //$NON-NLS-1$
}
this.setName(propertyName);
this.setDisplayName(propertyName);
getterName = createDefaultMethodName(propertyName, "is"); //$NON-NLS-1$
if (hasMethod(beanClass, getterName)) {
setReadMethod(beanClass, getterName);
} else {
getterName = createDefaultMethodName(propertyName, "get"); //$NON-NLS-1$
if (hasMethod(beanClass, getterName)) {
setReadMethod(beanClass, getterName);
}
}
setterName = createDefaultMethodName(propertyName, "set"); //$NON-NLS-1$
if (hasMethod(beanClass, setterName)) {
setWriteMethod(beanClass, setterName);
}
if (getter == null && setter == null) {
throw new IntrospectionException(Messages.getString(
"beans.01", propertyName)); //$NON-NLS-1$
}
}
public void setWriteMethod(Method setter) throws IntrospectionException {
if (setter != null) {
int modifiers = setter.getModifiers();
if (!Modifier.isPublic(modifiers)) {
throw new IntrospectionException(Messages.getString("beans.05")); //$NON-NLS-1$
}
Class<?>[] parameterTypes = setter.getParameterTypes();
if (parameterTypes.length != 1) {
throw new IntrospectionException(Messages.getString("beans.06")); //$NON-NLS-1$
}
Class<?> parameterType = parameterTypes[0];
Class<?> propertyType = getPropertyType();
if (propertyType != null && !propertyType.equals(parameterType)) {
throw new IntrospectionException(Messages.getString("beans.07")); //$NON-NLS-1$
}
}
this.setter = setter;
}
public void setReadMethod(Method getter) throws IntrospectionException {
if (getter != null) {
int modifiers = getter.getModifiers();
if (!Modifier.isPublic(modifiers)) {
throw new IntrospectionException(Messages.getString("beans.0A")); //$NON-NLS-1$
}
Class<?>[] parameterTypes = getter.getParameterTypes();
if (parameterTypes.length != 0) {
throw new IntrospectionException(Messages.getString("beans.08")); //$NON-NLS-1$
}
Class<?> returnType = getter.getReturnType();
if (returnType.equals(Void.TYPE)) {
throw new IntrospectionException(Messages.getString("beans.33")); //$NON-NLS-1$
}
Class<?> propertyType = getPropertyType();
if ((propertyType != null) && !returnType.equals(propertyType)) {
throw new IntrospectionException(Messages.getString("beans.09")); //$NON-NLS-1$
}
}
this.getter = getter;
}
public Method getWriteMethod() {
return setter;
}
public Method getReadMethod() {
return getter;
}
#Override
public boolean equals(Object object) {
boolean result = (object != null && object instanceof PropertyDescriptor);
if (result) {
PropertyDescriptor pd = (PropertyDescriptor) object;
boolean gettersAreEqual = (this.getter == null)
&& (pd.getReadMethod() == null) || (this.getter != null)
&& (this.getter.equals(pd.getReadMethod()));
boolean settersAreEqual = (this.setter == null)
&& (pd.getWriteMethod() == null) || (this.setter != null)
&& (this.setter.equals(pd.getWriteMethod()));
boolean propertyTypesAreEqual = this.getPropertyType() == pd
.getPropertyType();
boolean propertyEditorClassesAreEqual = this
.getPropertyEditorClass() == pd.getPropertyEditorClass();
boolean boundPropertyAreEqual = this.isBound() == pd.isBound();
boolean constrainedPropertyAreEqual = this.isConstrained() == pd
.isConstrained();
result = gettersAreEqual && settersAreEqual
&& propertyTypesAreEqual && propertyEditorClassesAreEqual
&& boundPropertyAreEqual && constrainedPropertyAreEqual;
}
return result;
}
public void setPropertyEditorClass(Class<?> propertyEditorClass) {
this.propertyEditorClass = propertyEditorClass;
}
public Class<?> getPropertyType() {
Class<?> result = null;
if (getter != null) {
result = getter.getReturnType();
} else if (setter != null) {
Class<?>[] parameterTypes = setter.getParameterTypes();
result = parameterTypes[0];
}
return result;
}
public Class<?> getPropertyEditorClass() {
return propertyEditorClass;
}
public void setConstrained(boolean constrained) {
this.constrained = constrained;
}
public void setBound(boolean bound) {
this.bound = bound;
}
public boolean isConstrained() {
return constrained;
}
public boolean isBound() {
return bound;
}
boolean hasMethod(Class<?> beanClass, String methodName) {
Method[] methods = findMethods(beanClass, methodName);
return (methods.length > 0);
}
String createDefaultMethodName(String propertyName, String prefix) {
String result = null;
if (propertyName != null) {
String bos = propertyName.substring(0, 1).toUpperCase();
String eos = propertyName.substring(1, propertyName.length());
result = prefix + bos + eos;
}
return result;
}
Method[] findMethods(Class<?> aClass, String methodName) {
Method[] allMethods = aClass.getMethods();
Vector<Method> matchedMethods = new Vector<Method>();
Method[] result;
for (Method method : allMethods) {
if (method.getName().equals(methodName)) {
matchedMethods.add(method);
}
}
result = new Method[matchedMethods.size()];
for (int j = 0; j < matchedMethods.size(); ++j) {
result[j] = matchedMethods.elementAt(j);
}
return result;
}
void setReadMethod(Class<?> beanClass, String getterName) {
boolean result = false;
Method[] getters = findMethods(beanClass, getterName);
for (Method element : getters) {
try {
setReadMethod(element);
result = true;
} catch (IntrospectionException ie) {
}
if (result) {
break;
}
}
}
void setWriteMethod(Class<?> beanClass, String setterName)
throws IntrospectionException {
boolean result = false;
Method[] setters = findMethods(beanClass, setterName);
for (Method element : setters) {
try {
setWriteMethod(element);
result = true;
} catch (IntrospectionException ie) {
}
if (result) {
break;
}
}
}
public PropertyEditor createPropertyEditor(Object bean) {
PropertyEditor editor;
if (propertyEditorClass == null) {
return null;
}
if (!PropertyEditor.class.isAssignableFrom(propertyEditorClass)) {
// beans.48=Property editor is not assignable from the
// PropertyEditor interface
throw new ClassCastException(Messages.getString("beans.48")); //$NON-NLS-1$
}
try {
Constructor<?> constr;
try {
// try to look for the constructor with single Object argument
constr = propertyEditorClass.getConstructor(Object.class);
editor = (PropertyEditor) constr.newInstance(bean);
} catch (NoSuchMethodException e) {
// try no-argument constructor
constr = propertyEditorClass.getConstructor();
editor = (PropertyEditor) constr.newInstance();
}
} catch (Exception e) {
// beans.47=Unable to instantiate property editor
RuntimeException re = new RuntimeException(
Messages.getString("beans.47"), e); //$NON-NLS-1$
throw re;
}
return editor;
}
}
Thanks.
I downloaded from this page https://code.google.com/p/openbeans/downloads/detail?name=openbeans-1.0.jar the openbean.jar. Then, i imported this jar to the project and changed the references at imported library.
Then export again the project as .jar library and import in the android project.

Categories