summaryrefslogtreecommitdiffstats
path: root/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java
diff options
context:
space:
mode:
authorPatrick Brady <pb071s@att.com>2017-02-15 23:11:26 -0800
committerPatrick Brady <pb071s@att.com>2017-02-15 23:13:06 -0800
commit1c192d2dd68724e292b6a30f463085a262e1e813 (patch)
treed0e2b3a396e169863cd0efaa835c8675e9d5aaac /appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java
parentc69ba05c7508aa7d7f675189a45c8c87569369ef (diff)
Moving all files to root directory
Change-Id: Ica5535fd6ec85f350fe1640b42137b49f83f10f0 Signed-off-by: Patrick Brady <pb071s@att.com>
Diffstat (limited to 'appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java')
-rw-r--r--appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/inmemory/LockManagerInMemoryImpl.java130
-rw-r--r--appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/inmemory/LockValue.java43
-rw-r--r--appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/JdbcLockManager.java51
-rw-r--r--appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/Messages.java47
-rw-r--r--appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/MySqlConnectionFactory.java34
-rw-r--r--appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/optimistic/LockRecord.java71
-rw-r--r--appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/optimistic/MySqlLockManager.java32
-rw-r--r--appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/optimistic/SqlLockManager.java263
8 files changed, 671 insertions, 0 deletions
diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/inmemory/LockManagerInMemoryImpl.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/inmemory/LockManagerInMemoryImpl.java
new file mode 100644
index 000000000..309e2790c
--- /dev/null
+++ b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/inmemory/LockManagerInMemoryImpl.java
@@ -0,0 +1,130 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * openECOMP : APP-C
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights
+ * reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.appc.lockmanager.impl.inmemory;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.openecomp.appc.lockmanager.api.LockException;
+import org.openecomp.appc.lockmanager.api.LockManager;
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+
+
+public class LockManagerInMemoryImpl implements LockManager {
+
+ private static LockManagerInMemoryImpl instance = null;
+ private Map<String, LockValue> lockedVNFs;
+
+ private static final EELFLogger debugLogger = EELFManager.getInstance().getDebugLogger();
+
+ private LockManagerInMemoryImpl() {
+ lockedVNFs = new ConcurrentHashMap<>();
+ }
+
+ public static LockManager getLockManager() {
+ if(instance == null) {
+ instance = new LockManagerInMemoryImpl();
+ }
+ return instance;
+ }
+
+ @Override
+ public boolean acquireLock(String resource, String owner) throws LockException {
+ return acquireLock(resource, owner, 0);
+ }
+
+ @Override
+ public boolean acquireLock(String resource, String owner, long timeout) throws LockException {
+ debugLogger.debug("Try to acquire lock on resource " + resource + " with owner " + owner);
+ long now = System.currentTimeMillis();
+ LockValue lockValue = lockedVNFs.get(resource);
+ if (lockValue != null) {
+ if (lockIsMine(lockValue, owner, now) || hasExpired(lockValue, now)) {
+ setExpirationTime(resource, owner, timeout, now);
+ debugLogger.debug("Locked successfully resource " + resource + " with owner " + owner + " for " + timeout + " ms");
+ return hasExpired(lockValue, now);
+ }
+ else {
+ debugLogger.debug("Owner " + owner + " tried to lock resource " + resource + " but it is already locked by owner " + lockValue.getOwner());
+ throw new LockException("Owner " + owner + " tried to lock resource " + resource + " but it is already locked by owner " + lockValue.getOwner());
+ }
+ }
+ else {
+ setExpirationTime(resource, owner, timeout, now);
+ debugLogger.debug("Locked successfully resource " + resource + " with owner " + owner + " for " + timeout + " ms");
+ return true;
+ }
+ }
+
+ @Override
+ public void releaseLock(String resource, String owner) throws LockException {
+ debugLogger.debug("Try to release lock on resource " + resource + " with owner " + owner);
+ long now = System.currentTimeMillis();
+ LockValue lockValue = lockedVNFs.get(resource);
+ if (lockValue != null) {
+ if (!hasExpired(lockValue, now)) {
+ if (isOwner(lockValue, owner)) {
+ debugLogger.debug("Unlocked successfully resource " + resource + " with owner " + owner);
+ lockedVNFs.remove(resource);
+ }
+ else {
+ debugLogger.debug("Unlock failed. Tried to release lock on resource " + resource + " from owner " + owner + " but it is held by a different owner");
+ throw new LockException("Unlock failed. Tried to release lock on resource " + resource + " from owner " + owner + " but it is held by a different owner");
+ }
+ }
+ else {
+ lockedVNFs.remove(resource);
+ debugLogger.debug("Unlock failed. lock on resource " + resource + " has expired");
+ throw new LockException("Unlock failed. lock on resource " + resource + " has expired");
+ }
+
+ }
+ else {
+ debugLogger.debug("Tried to release lock on resource " + resource + " from owner " + owner + " but there is not lock on this resource");
+ throw new LockException("Tried to release lock on resource " + resource + " from owner " + owner + " but there is not lock on this resource");
+ }
+ }
+
+ @Override
+ public boolean isLocked(String resource) {
+ return lockedVNFs.get(resource)!=null?true:false;
+ }
+
+ private boolean lockIsMine(LockValue lockValue, String owner, long now) {
+ return isOwner(lockValue, owner) && !hasExpired(lockValue, now);
+ }
+
+ private boolean isOwner(LockValue lockValue, String owner) {
+ return lockValue.getOwner() != null && lockValue.getOwner().equals(owner);
+ }
+
+ private boolean hasExpired(LockValue lockValue, long now) {
+ return (lockValue.getExpirationTime() != 0 && now > lockValue.getExpirationTime());
+ }
+
+ private void setExpirationTime(String resource, String owner, long timeout, long now) {
+ long expirationTime = timeout == 0 ? 0 : now + timeout;
+ LockValue lockValue = new LockValue(owner, expirationTime);
+ lockedVNFs.put(resource, lockValue);
+ }
+}
diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/inmemory/LockValue.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/inmemory/LockValue.java
new file mode 100644
index 000000000..abdd494d9
--- /dev/null
+++ b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/inmemory/LockValue.java
@@ -0,0 +1,43 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * openECOMP : APP-C
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights
+ * reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.appc.lockmanager.impl.inmemory;
+
+
+public class LockValue {
+
+ private String owner;
+ private long expirationTime;
+
+ LockValue(String owner, long expirationTime) {
+ this.owner = owner;
+ this.expirationTime = expirationTime;
+ }
+
+ String getOwner() {
+ return owner;
+ }
+
+ long getExpirationTime() {
+ return expirationTime;
+ }
+
+}
diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/JdbcLockManager.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/JdbcLockManager.java
new file mode 100644
index 000000000..97a5cc339
--- /dev/null
+++ b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/JdbcLockManager.java
@@ -0,0 +1,51 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * openECOMP : APP-C
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights
+ * reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.appc.lockmanager.impl.sql;
+
+import java.sql.Connection;
+
+import org.openecomp.appc.dao.util.JdbcConnectionFactory;
+import org.openecomp.appc.lockmanager.api.LockManager;
+
+public abstract class JdbcLockManager implements LockManager {
+
+ private static final String DEF_TABLE_LOCK_MANAGEMENT = "LOCK_MANAGEMENT";
+
+ private JdbcConnectionFactory connectionFactory;
+ protected String tableName = DEF_TABLE_LOCK_MANAGEMENT;
+
+ public void setConnectionFactory(JdbcConnectionFactory connectionFactory) {
+ this.connectionFactory = connectionFactory;
+ }
+
+ public void setTableName(String tableName) {
+ this.tableName = tableName;
+ }
+
+ protected Connection openDbConnection() {
+ return connectionFactory.openDbConnection();
+ }
+
+ protected void closeDbConnection(Connection connection) {
+ connectionFactory.closeDbConnection(connection);
+ }
+}
diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/Messages.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/Messages.java
new file mode 100644
index 000000000..0399726b5
--- /dev/null
+++ b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/Messages.java
@@ -0,0 +1,47 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * openECOMP : APP-C
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights
+ * reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.appc.lockmanager.impl.sql;
+
+public enum Messages {
+
+ ERR_NULL_LOCK_OWNER("Cannot acquire lock for resource [%s]: lock owner must be specified"),
+ ERR_LOCK_LOCKED_BY_OTHER("Cannot lock resource [%s] for [%s]: already locked by [%s]"),
+ ERR_UNLOCK_NOT_LOCKED("Error unlocking resource [%s]: resource is not locked"),
+ ERR_UNLOCK_LOCKED_BY_OTHER("Error unlocking resource [%s] by [%s]: resource is locked by [%s]"),
+ EXP_LOCK("Error locking resource [%s]."),
+ EXP_UNLOCK("Error unlocking resource [%s]."),
+ ;
+
+ private String message;
+
+ Messages(String message) {
+ this.message = message;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public String format(Object... s) {
+ return String.format(message, s);
+ }
+}
diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/MySqlConnectionFactory.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/MySqlConnectionFactory.java
new file mode 100644
index 000000000..4ccd0c453
--- /dev/null
+++ b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/MySqlConnectionFactory.java
@@ -0,0 +1,34 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * openECOMP : APP-C
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights
+ * reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.appc.lockmanager.impl.sql;
+
+import java.sql.DriverManager;
+import java.sql.SQLException;
+
+import org.openecomp.appc.dao.util.DefaultJdbcConnectionFactory;
+
+public class MySqlConnectionFactory extends DefaultJdbcConnectionFactory {
+
+ protected void registedDriver() throws SQLException {
+ DriverManager.registerDriver(new com.mysql.jdbc.Driver());
+ }
+}
diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/optimistic/LockRecord.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/optimistic/LockRecord.java
new file mode 100644
index 000000000..d66804488
--- /dev/null
+++ b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/optimistic/LockRecord.java
@@ -0,0 +1,71 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * openECOMP : APP-C
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights
+ * reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.appc.lockmanager.impl.sql.optimistic;
+
+class LockRecord {
+
+ private String resource;
+ private String owner;
+ private long updated;
+ private long timeout;
+ private long ver;
+
+ LockRecord(String resource) {
+ this.resource = resource;
+ }
+
+ public String getResource() {
+ return resource;
+ }
+
+ public String getOwner() {
+ return owner;
+ }
+
+ public void setOwner(String owner) {
+ this.owner = owner;
+ }
+
+ public long getUpdated() {
+ return updated;
+ }
+
+ public void setUpdated(long updated) {
+ this.updated = updated;
+ }
+
+ public long getTimeout() {
+ return timeout;
+ }
+
+ public void setTimeout(long timeout) {
+ this.timeout = timeout;
+ }
+
+ public long getVer() {
+ return ver;
+ }
+
+ public void setVer(long ver) {
+ this.ver = ver;
+ }
+}
diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/optimistic/MySqlLockManager.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/optimistic/MySqlLockManager.java
new file mode 100644
index 000000000..e80133620
--- /dev/null
+++ b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/optimistic/MySqlLockManager.java
@@ -0,0 +1,32 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * openECOMP : APP-C
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights
+ * reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.appc.lockmanager.impl.sql.optimistic;
+
+import java.sql.SQLException;
+
+public class MySqlLockManager extends SqlLockManager {
+
+ @Override
+ protected boolean isDuplicatePkError(SQLException e) {
+ return (e.getErrorCode() == 1062);
+ }
+}
diff --git a/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/optimistic/SqlLockManager.java b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/optimistic/SqlLockManager.java
new file mode 100644
index 000000000..52c75d2b2
--- /dev/null
+++ b/appc-dispatcher/appc-dispatcher-common/lock-manager-lib/lock-manager-impl/src/main/java/org/openecomp/appc/lockmanager/impl/sql/optimistic/SqlLockManager.java
@@ -0,0 +1,263 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * openECOMP : APP-C
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights
+ * reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ */
+
+package org.openecomp.appc.lockmanager.impl.sql.optimistic;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+
+import org.openecomp.appc.lockmanager.api.LockException;
+import org.openecomp.appc.lockmanager.api.LockRuntimeException;
+import org.openecomp.appc.lockmanager.impl.sql.JdbcLockManager;
+import org.openecomp.appc.lockmanager.impl.sql.Messages;
+
+abstract class SqlLockManager extends JdbcLockManager {
+
+ private static final String SQL_LOAD_LOCK_RECORD = "SELECT * FROM %s WHERE RESOURCE_ID=?";
+ private static final String SQL_INSERT_LOCK_RECORD = "INSERT INTO %s (RESOURCE_ID, OWNER_ID, UPDATED, TIMEOUT, VER) VALUES (?, ?, ?, ?, ?)";
+ private static final String SQL_UPDATE_LOCK_RECORD = "UPDATE %s SET OWNER_ID=?, UPDATED=?, TIMEOUT=?, VER=? WHERE RESOURCE_ID=? AND VER=?";
+// private static final String SQL_DELETE_LOCK_RECORD = "DELETE FROM %s WHERE RESOURCE_ID=? AND VER=?";
+ private static final String SQL_CURRENT_TIMESTAMP = "SELECT CURRENT_TIMESTAMP()";
+
+ private String sqlLoadLockRecord;
+ private String sqlInsertLockRecord;
+ private String sqlUpdateLockRecord;
+// private String sqlDeleteLockRecord;
+
+ @Override
+ public boolean acquireLock(String resource, String owner) throws LockException {
+ return acquireLock(resource, owner, 0);
+ }
+
+ @Override
+ public boolean acquireLock(String resource, String owner, long timeout) throws LockException {
+ if(owner == null) {
+ throw new LockRuntimeException(Messages.ERR_NULL_LOCK_OWNER.format(resource));
+ }
+ boolean res = false;
+ Connection connection = openDbConnection();
+ try {
+ res = lockResource(connection, resource, owner, timeout);
+ } finally {
+ closeDbConnection(connection);
+ }
+ return res;
+ }
+
+ @Override
+ public void releaseLock(String resource, String owner) throws LockException {
+ Connection connection = openDbConnection();
+ try {
+ unlockResource(connection, resource, owner);
+ } finally {
+ closeDbConnection(connection);
+ }
+ }
+
+ @Override
+ public boolean isLocked(String resource) {
+ Connection connection=openDbConnection();
+ try {
+ LockRecord lockRecord=loadLockRecord(connection,resource);
+ if(lockRecord==null){
+ return false;
+ }else{
+ if(lockRecord.getOwner()==null){
+ return false;
+ }else if(isLockExpired(lockRecord, connection)){
+ return false;
+ }else{
+ return true;
+ }
+ }
+ } catch (SQLException e) {
+ throw new LockRuntimeException(Messages.EXP_LOCK.format(resource));
+ }finally {
+ closeDbConnection(connection);
+ }
+ }
+
+ private boolean lockResource(Connection connection, String resource, String owner, long timeout) throws LockException {
+ try {
+ boolean res = false;
+ LockRecord lockRecord = loadLockRecord(connection, resource);
+ if(lockRecord != null) {
+ // lock record already exists
+ String currentOwner = lockRecord.getOwner();
+ if(currentOwner != null) {
+ if(isLockExpired(lockRecord, connection)) {
+ currentOwner = null;
+ } else if(!owner.equals(currentOwner)) {
+ throw new LockException(Messages.ERR_LOCK_LOCKED_BY_OTHER.format(resource, owner, currentOwner));
+ }
+ }
+ // set new owner on the resource lock record
+ if(!updateLockRecord(connection, resource, owner, timeout, lockRecord.getVer())) {
+ // try again - maybe same owner updated the record
+ lockResource(connection, resource, owner, timeout);
+ }
+ if(currentOwner == null) {
+ // no one locked the resource before
+ res = true;
+ }
+ } else {
+ // resource record does not exist in lock table => create new record
+ try {
+ addLockRecord(connection, resource, owner, timeout);
+ res = true;
+ } catch(SQLException e) {
+ if(isDuplicatePkError(e)) {
+ // try again - maybe same owner inserted the record
+ lockResource(connection, resource, owner, timeout);
+ } else {
+ throw e;
+ }
+ }
+ }
+ return res;
+ } catch(SQLException e) {
+ throw new LockRuntimeException(Messages.EXP_LOCK.format(resource), e);
+ }
+ }
+
+ protected boolean isDuplicatePkError(SQLException e) {
+ return e.getSQLState().startsWith("23");
+ }
+
+ private void unlockResource(Connection connection, String resource, String owner) throws LockException {
+ try {
+ LockRecord lockRecord = loadLockRecord(connection, resource);
+ if(lockRecord != null) {
+ // check if expired
+ if(isLockExpired(lockRecord, connection)) {
+ // lock is expired => no lock
+ lockRecord = null;
+ }
+ }
+ if((lockRecord == null) || (lockRecord.getOwner() == null)) {
+ // resource is not locked
+ throw new LockException(Messages.ERR_UNLOCK_NOT_LOCKED.format(resource));
+ }
+ String currentOwner = lockRecord.getOwner();
+ if(!owner.equals(currentOwner)) {
+ throw new LockException(Messages.ERR_UNLOCK_LOCKED_BY_OTHER.format(resource, owner, currentOwner));
+ }
+ if (!updateLockRecord(connection, resource, null, 0, lockRecord.getVer())) {
+ unlockResource(connection, resource, owner);
+ }
+ // TODO delete record from table on lock release?
+// deleteLockRecord(connection, resource, lockRecord.getVer());
+ } catch(SQLException e) {
+ throw new LockRuntimeException(Messages.EXP_UNLOCK.format(resource), e);
+ }
+ }
+
+ protected LockRecord loadLockRecord(Connection connection, String resource) throws SQLException {
+ LockRecord res = null;
+ if(sqlLoadLockRecord == null) {
+ sqlLoadLockRecord = String.format(SQL_LOAD_LOCK_RECORD, tableName);
+ }
+ try(PreparedStatement statement = connection.prepareStatement(sqlLoadLockRecord)) {
+ statement.setString(1, resource);
+ try(ResultSet resultSet = statement.executeQuery()) {
+ if(resultSet.next()) {
+ res = new LockRecord(resource);
+ res.setOwner(resultSet.getString(2));
+ res.setUpdated(resultSet.getLong(3));
+ res.setTimeout(resultSet.getLong(4));
+ res.setVer(resultSet.getLong(5));
+ }
+ }
+ }
+ return res;
+ }
+
+ protected void addLockRecord(Connection connection, String resource, String owner, long timeout) throws SQLException {
+ if(sqlInsertLockRecord == null) {
+ sqlInsertLockRecord = String.format(SQL_INSERT_LOCK_RECORD, tableName);
+ }
+ try(PreparedStatement statement = connection.prepareStatement(sqlInsertLockRecord)) {
+ statement.setString(1, resource);
+ statement.setString(2, owner);
+ statement.setLong(3, getCurrentTime(connection));
+ statement.setLong(4, timeout);
+ statement.setLong(5, 1);
+ statement.executeUpdate();
+ }
+ }
+
+ protected boolean updateLockRecord(Connection connection, String resource, String owner, long timeout, long ver) throws SQLException {
+ if(sqlUpdateLockRecord == null) {
+ sqlUpdateLockRecord = String.format(SQL_UPDATE_LOCK_RECORD, tableName);
+ }
+ try(PreparedStatement statement = connection.prepareStatement(sqlUpdateLockRecord)) {
+ long newVer = (ver >= Long.MAX_VALUE) ? 1 : (ver + 1);
+ statement.setString(1, owner);
+ statement.setLong(2, getCurrentTime(connection));
+ statement.setLong(3, timeout);
+ statement.setLong(4, newVer);
+ statement.setString(5, resource);
+ statement.setLong(6, ver);
+ return (statement.executeUpdate() != 0);
+ }
+ }
+
+// protected void deleteLockRecord(Connection connection, String resource, long ver) throws SQLException {
+// if(sqlDeleteLockRecord == null) {
+// sqlDeleteLockRecord = String.format(SQL_DELETE_LOCK_RECORD, tableName);
+// }
+// try(PreparedStatement statement = connection.prepareStatement(sqlDeleteLockRecord)) {
+// statement.setString(1, resource);
+// statement.setLong(2, ver);
+// statement.executeUpdate();
+// }
+// }
+
+ private boolean isLockExpired(LockRecord lockRecord, Connection connection) throws SQLException {
+ long timeout = lockRecord.getTimeout();
+ if(timeout == 0) {
+ return false;
+ }
+ long updated = lockRecord.getUpdated();
+ long now = getCurrentTime(connection);
+ long expiration = updated + timeout;
+ return (now > expiration);
+ }
+
+ private long getCurrentTime(Connection connection) throws SQLException {
+ long res = -1;
+ if(connection != null) {
+ try(PreparedStatement statement = connection.prepareStatement(SQL_CURRENT_TIMESTAMP)) {
+ try(ResultSet resultSet = statement.executeQuery()) {
+ if(resultSet.next()) {
+ res = resultSet.getTimestamp(1).getTime();
+ }
+ }
+ }
+ }
+ if(res == -1) {
+ res = System.currentTimeMillis();
+ }
+ return res;
+ }
+}