001: /*
002: * Copyright 2004-2006 the original author or authors.
003: *
004: * Licensed under the Apache License, Version 2.0 (the "License");
005: * you may not use this file except in compliance with the License.
006: * You may obtain a copy of the License at
007: *
008: * http://www.apache.org/licenses/LICENSE-2.0
009: *
010: * Unless required by applicable law or agreed to in writing, software
011: * distributed under the License is distributed on an "AS IS" BASIS,
012: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013: * See the License for the specific language governing permissions and
014: * limitations under the License.
015: */
016:
017: package org.compass.needle.gigaspaces.store;
018:
019: import java.io.IOException;
020:
021: import com.j_spaces.core.IJSpace;
022: import net.jini.core.lease.Lease;
023: import org.apache.commons.logging.Log;
024: import org.apache.commons.logging.LogFactory;
025: import org.apache.lucene.store.Lock;
026: import org.apache.lucene.store.LockFactory;
027:
028: /**
029: * A locak factory using a {@link FileLock} entry
030: * as a mark that a certain lock is obtained.
031: *
032: * @author kimchy
033: */
034: public class GigaSpaceLockFactory extends LockFactory {
035:
036: private static final Log log = LogFactory
037: .getLog(GigaSpaceLockFactory.class);
038:
039: private IJSpace space;
040:
041: private String indexName;
042:
043: public GigaSpaceLockFactory(IJSpace space, String indexName) {
044: this .space = space;
045: this .indexName = indexName;
046: }
047:
048: public void clearLock(String lockName) throws IOException {
049: try {
050: space.clear(new FileLock(indexName, lockName), null);
051: } catch (Exception e) {
052: throw new GigaSpaceDirectoryException(indexName, lockName,
053: "Failed to clear lock", e);
054: }
055: }
056:
057: public Lock makeLock(String lockName) {
058: return new GigaSpaceLock(lockName);
059: }
060:
061: public class GigaSpaceLock extends Lock {
062:
063: private FileLock fileLock;
064:
065: public GigaSpaceLock(String lockName) {
066: this .fileLock = new FileLock(indexName, lockName);
067: }
068:
069: public boolean isLocked() {
070: try {
071: int count = space.count(fileLock, null);
072: return count > 0;
073: } catch (Exception e) {
074: if (log.isWarnEnabled()) {
075: log.warn(
076: "Failed to check if object is locked on index ["
077: + indexName + "]", e);
078: }
079: }
080: return false;
081: }
082:
083: public boolean obtain() throws IOException {
084: try {
085: space.write(fileLock, null, Lease.FOREVER);
086: } catch (Exception e) {
087: return false;
088: }
089: return true;
090: }
091:
092: public void release() {
093: try {
094: space.clear(fileLock, null);
095: } catch (Exception e) {
096: if (log.isWarnEnabled()) {
097: log.warn("Failed to release locke on index ["
098: + indexName + "]", e);
099: }
100: }
101: }
102: }
103: }
|