public String getTextForGesture(long parId, Point topLeft, Point bottomRight) { try { Paragraph p = lockManager.getParFromId(parId); int parY = documentPanel.textPane.modelToView(p.getOffset()).y; topLeft.y = topLeft.y + parY; bottomRight.y = bottomRight.y + parY; int startOffset = documentPanel.textPane.viewToModel(topLeft); int endOffset = documentPanel.textPane.viewToModel(bottomRight); while (startOffset > 0 && Character.isLetterOrDigit((document.getText(startOffset - 1, 1).charAt(0)))) startOffset--; while (endOffset < document.getLength() && Character.isLetterOrDigit((document.getText(endOffset, 1).charAt(0)))) endOffset++; String text = document.getText(startOffset, endOffset - startOffset); return text; } catch (Exception e) { System.out.println("EditorClient: addGestureAction. error identifying text"); e.printStackTrace(); return ""; } // return "PLACEBO"; }
public long getParIdForGesture(long startParId, int y) { Paragraph startPar = lockManager.getParFromId(startParId); int startParY = documentPanel.getYValueFromOffset(startPar.getOffset()); int offset = documentPanel.getOffsetFromPoint(new Point(25, startParY + y)); return lockManager.getParFromOffset(offset).getID(); }
public void sendHighlights() { // send highlights to everybody try { Iterator i = highlights.getHighlights().iterator(); while (i.hasNext()) { Highlights.Highlight h = (Highlights.Highlight) i.next(); Paragraph sPar = lockManager.getParFromOffset(h.getStart()); Paragraph ePar = lockManager.getParFromOffset(h.getEnd()); if (EditorServer_Debug) { System.out.println("StartPar: " + sPar.toString()); System.out.println("EndPar: " + ePar.toString()); } Message.HighlightAddMsg msg = new Message.HighlightAddMsg( -1, h.getId(), h.getType().getId(), sPar.getID(), ePar.getID(), h.getStart() - sPar.getOffset(), h.getEnd() - ePar.getOffset()); textChannel.sendToOthers(client, new Data(msg)); } } catch (Exception e) { System.err.println("EditorServer: sendHighlights: error sending msg"); if (EditorServer_Debug) e.printStackTrace(); } }
/** ロック開放後同一カテゴリとキーでロック取得可能. */ @Test public void ロック開放後同一カテゴリとキーでロック取得可能() { Lock lock = LockManager.getLock(Lock.CATEGORY_ODATA, "aaa", null, null); lock.release(); Lock lock2 = LockManager.getLock(Lock.CATEGORY_ODATA, "aaa", null, null); assertNotNull(lock2); lock2.release(); }
/** 違うカテゴリであれば同キー名での連続取得が可能. */ @Test public void 違うカテゴリであれば同キー名での連続取得が可能() { Lock lockOData = LockManager.getLock(Lock.CATEGORY_ODATA, "aaa", null, null); Lock lockDav = LockManager.getLock(Lock.CATEGORY_DAV, "aaa", null, null); assertNotNull(lockOData); assertNotNull(lockDav); lockDav.release(); lockOData.release(); }
/** * Commit or abort a given transaction; release all locks associated to the transaction. * * @param tid the ID of the transaction requesting the unlock * @param commit a flag indicating whether we should commit or abort */ public void transactionComplete(TransactionId tid, boolean commit) throws IOException { if (commit) { Set<PageId> dirtiedFlushedPages = transactionsToDirtiedFlushedPages.get(tid); for (PageId pageId : pageIdToPages.keySet()) { Page page = pageIdToPages.get(pageId); if (tid.equals(page.isDirty())) { flushPage(pageId); // use current page contents as the before-image // for the next transaction that modifies this page. page.setBeforeImage(); } else if (dirtiedFlushedPages != null && dirtiedFlushedPages.contains(pageId)) { page.setBeforeImage(); } } } else { for (PageId pageId : pageIdToPages.keySet()) { Page page = pageIdToPages.get(pageId); if (tid.equals(page.isDirty())) { pageIdToPages.put(pageId, page.getBeforeImage()); page.markDirty(false, null); } } } transactionsToDirtiedFlushedPages.remove(tid); lockManager.releasePages(tid); // if commit, flush dirty pages associated with transaction // if !commit, restore dirty pages associated with transaction to // previous // state // release all locks (and other state? don't think there is any) }
@Override protected void configure() throws JournalException { writeLock = LockManager.lockExclusive(getLocation()); if (writeLock == null || !writeLock.isValid()) { close(); throw new JournalException("Journal is already open for APPEND at %s", getLocation()); } if (txLog.isEmpty()) { commit(Tx.TX_NORMAL, 0L, 0L); } txLog.head(tx); File meta = new File(getLocation(), JournalConfiguration.FILE_NAME); if (!meta.exists()) { try (UnstructuredFile hb = new UnstructuredFile(meta, 12, JournalMode.APPEND)) { getMetadata().write(hb); } } super.configure(); beginTx(); rollback(); rollbackPartitionDirs(); if (tx.journalMaxRowID > 0 && getPartitionCount() <= Rows.toPartitionIndex(tx.journalMaxRowID)) { beginTx(); commit(); } if (getMetadata().getLag() != -1) { this.partitionCleaner = new PartitionCleaner(this, getLocation().getName()); this.partitionCleaner.start(); } }
/** * Retryが指定回数行われる. * * @throws InterruptedException InterruptedException */ @Test @Ignore public void Retryが指定回数行われる() throws InterruptedException { LockManager originalLm = LockManager.singleton; LockManager.singleton = new RetryCountingLockManager(); RetryCountingLockManager rclm = (RetryCountingLockManager) LockManager.singleton; try { LockManager.getLock(Lock.CATEGORY_ODATA, "aaa", null, null); } catch (DcCoreException e) { assertEquals(DcCoreException.class, e.getClass()); } finally { // doGetLock呼び出し回数 は 最初の呼び出しの1回と + リトライ回数 となる assertEquals(LockManager.getLockRetryTimes() + 1, rclm.getCount); LockManager.singleton = originalLm; } }
@Override public final void close() { if (open) { if (partitionCleaner != null) { partitionCleaner.halt(); partitionCleaner = null; } try { if (isCommitOnClose()) { commit(); purgeUnusedTempPartitions(txLog); } super.close(); if (writeLock != null) { LockManager.release(writeLock); writeLock = null; } if (discardTxtRaf != null) { try { discardSink.close(); discardTxtRaf.close(); } catch (IOException e) { LOGGER.warn("Failed to close discard file"); } } } catch (JournalException e) { throw new JournalRuntimeException(e); } } }
public void textInserted(Message.TextInsertMsg m) { if (EditorServer_Debug) System.err.println("EditorServer-> textInserted."); try { int ClientId = m.getClientId(); int offset = m.getOffset(); String characterInserted = m.getText(); if (EditorServer_Debug) System.out.println("EditorServer-> textInserted : *" + characterInserted + "*"); Vector pars = lockManager.textInserted(m.getPar(), offset, characterInserted, ClientId); textChannel.sendToOthers(client, new Data(m)); EditorClient c = getEditorClient(ClientId); // new condition inserted to avoid timestamp generation if the character // is a newline if (characterInserted.equals("\n")) { if (EditorServer_Debug) System.out.println("EditorServer-> textInserted : attempting to insert a newLine"); } c.addTextInsertAction(System.currentTimeMillis(), pars, offset, characterInserted); clientsPanel.updateActionTableFor(c); updateParagraphList(); } catch (Exception e) { System.err.println("EditorServer-> textInserted: error receiving-sending msg"); if (EditorServer_Debug) e.printStackTrace(); } }
public void textInserted(Message.TextPasteMsg m) { try { int SenderId = m.getClientId(); int offset = m.getOffset(); String textPasted = m.getText(); if (EditorServer_Debug) System.err.println("EditorServer->textinserted : PASTED by : " + SenderId); Vector pars = null; try { pars = lockManager.textInserted(m.getPar(), offset, textPasted, SenderId); if (EditorServer_Debug) System.err.println("\n+=*%EditorServer--> textInserted recovered VECTOR..."); } catch (Exception e) { System.err.println("\n+=*%EditorServer--> textInserted VECTOR error "); } textChannel.sendToOthers(client, new Data(m)); EditorClient SenderClient = getEditorClient(SenderId); SenderClient.addTextPasteAction(System.currentTimeMillis(), pars, offset, textPasted); clientsPanel.updateActionTableFor(SenderClient); updateParagraphList(); } catch (Exception e) { System.err.println("\nEditorServer--> textPasted: error sending msg"); if (EditorServer_Debug) e.printStackTrace(); } }
/** * Creates a BufferPool that caches up to numPages pages. * * @param numPages maximum number of pages in this buffer pool. */ public BufferPool(int numPages) { this.maxPages = numPages; this.pageIdToPages = new HashMap<PageId, Page>(); this.transactionsToDirtiedFlushedPages = new HashMap<TransactionId, Set<PageId>>(); this.lockManager = LockManager.create(); currentPages = new AtomicInteger(0); }
public void purgeUnusedTempPartitions(TxLog txLog) throws JournalException { final Tx tx = new Tx(); final String lagPartitionName = hasIrregularPartition() ? getIrregularPartition().getName() : null; File[] files = getLocation() .listFiles( new FileFilter() { public boolean accept(File f) { return f.isDirectory() && f.getName().startsWith(Constants.TEMP_DIRECTORY_PREFIX) && (lagPartitionName == null || !lagPartitionName.equals(f.getName())); } }); if (files != null) { Arrays.sort(files); for (int i = 0; i < files.length; i++) { if (!txLog.isEmpty()) { txLog.head(tx); if (files[i].getName().equals(tx.lagName)) { continue; } } // get exclusive lock Lock lock = LockManager.lockExclusive(files[i]); try { if (lock != null && lock.isValid()) { LOGGER.trace("Purging : %s", files[i]); if (!Files.delete(files[i])) { LOGGER.info("Could not purge: %s", files[i]); } } else { LOGGER.trace("Partition in use: %s", files[i]); } } finally { LockManager.release(lock); } } } }
/** 同じキー名での取得は2回目以降のものはブロックされる. */ @Test public void 同じキー名での取得は2回目以降のものはブロックされる() { Lock lock = null; Lock lock2 = null; String lockName = "lk" + new Date().getTime(); try { lock = LockManager.getLock(Lock.CATEGORY_ODATA, lockName, null, null); lock2 = LockManager.getLock(Lock.CATEGORY_ODATA, lockName, null, null); } catch (DcCoreException e) { assertEquals(DcCoreException.class, e.getClass()); } finally { lock.release(); if (lock2 != null) { lock2.release(); } } }
public V get(K key) { V v = cache.getIfPresent(key); if (v == null) { try { lockManager.hold(locks, key); if (v == null) { v = loader.load(key); cache.put(key, v); } } catch (Exception ex) { PGException.pgThrow(ex); } finally { lockManager.release(locks, key); } } return v; }
public void sendDocumentState(int clientId) { Message.DocumentStateMsg msg = new Message.DocumentStateMsg(clientId, lockManager.getDocumentAsXML()); try { clientChannel.sendToOthers(client, new Data(msg)); } catch (Exception e) { System.err.println("EditorServer: sendDocumentState: error sending msg"); if (EditorServer_Debug) e.printStackTrace(); } }
public void lockReleased(Message.LockReleaseMsg m) { if (EditorServer_Debug) System.err.println("EditorServer: lockReleased."); lockManager.lockReleased(m.getStartPar(), m.getEndPar(), m.getClientId()); try { textChannel.sendToOthers(client, new Data(m)); } catch (Exception e) { System.err.println("EditorServer: lockReleased: error sending lock released"); if (EditorServer_Debug) e.printStackTrace(); } }
/** * Check access on the new superior entry if it exists. If the entry does not exist or the DN * cannot be locked then false is returned. * * @param superiorDN The DN of the new superior entry. * @param op The modifyDN operation to check access on. * @return True if access is granted to the new superior entry. * @throws DirectoryException If a problem occurs while trying to retrieve the new superior entry. */ private boolean aciCheckSuperiorEntry(DN superiorDN, LocalBackendModifyDNOperation op) throws DirectoryException { boolean ret = false; final Lock entryLock = LockManager.lockRead(superiorDN); if (entryLock == null) { Message message = WARN_ACI_HANDLER_CANNOT_LOCK_NEW_SUPERIOR_USER.get(String.valueOf(superiorDN)); logError(message); return false; } try { Entry superiorEntry = DirectoryServer.getEntry(superiorDN); if (superiorEntry != null) { AciLDAPOperationContainer operationContainer = new AciLDAPOperationContainer(op, (ACI_IMPORT), superiorEntry); ret = accessAllowed(operationContainer); } } finally { LockManager.unlock(superiorDN, entryLock); } return ret; }
public void textDeleted(Message.TextCutMsg m) { if (EditorServer_Debug) System.err.println("EditorServer ->textCut."); try { long StartPar = m.getStartPar(); long EndPar = m.getEndPar(); int StartOffset = m.getStartOffset(); int EndOffset = m.getEndOffset(); String text = lockManager.getText(StartPar, StartOffset, EndPar, EndOffset); Vector pars = lockManager.textDeleted(StartPar, StartOffset, EndPar, EndOffset); textChannel.sendToOthers(client, new Data(m)); EditorClient c = getEditorClient(m.getClientId()); c.addTextCutAction(System.currentTimeMillis(), pars, StartOffset, EndOffset, text); clientsPanel.updateActionTableFor(c); updateParagraphList(); } catch (Exception e) { System.err.println("EditorServer---> textDeleted(cut): error sending msg"); if (EditorServer_Debug) e.printStackTrace(); } }
/** * Retrieve the specified page with the associated permissions. Will acquire a lock and may block * if that lock is held by another transaction. * * <p>The retrieved page should be looked up in the buffer pool. If it is present, it should be * returned. If it is not present, it should be added to the buffer pool and returned. If there is * insufficient space in the buffer pool, an page should be evicted and the new page should be * added in its place. * * @param tid the ID of the transaction requesting the page * @param pid the ID of the requested page * @param perm the requested permissions on the page * @throws DbException * @throws TransactionAbortedException */ public Page getPage(TransactionId tid, PageId pid, Permissions perm) throws DbException, TransactionAbortedException { lockManager.acquireLock(tid, pid, perm); if (pageIdToPages.containsKey(pid)) { return pageIdToPages.get(pid); } if (currentPages.get() == maxPages) { evictPage(); } int tableId = pid.getTableId(); Catalog catalog = Database.getCatalog(); DbFile dbFile = catalog.getDatabaseFile(tableId); Page page = dbFile.readPage(pid); pageIdToPages.put(pid, page); currentPages.incrementAndGet(); return page; }
public void lockRequested(Message.LockRequestMsg m) { if (EditorServer_Debug) System.err.println("EditorServer -> lockRequested."); /* java.util.Timer t = new java.util.Timer() ; t.schedule(new TimerTask() { public void run() { client.lockDenied(id) ; } }, 3000) ; */ if (lockManager.lockRequested(m.getStartPar(), m.getEndPar(), m.getClientId())) { if (EditorServer_Debug) System.out.println("Lock Granted"); Message.LockGrantMsg reply = new Message.LockGrantMsg( m.getClientId(), m.getStartPar(), m.getEndPar(), m.getIdNumber()); try { textChannel.sendToOthers(client, new Data(reply)); } catch (Exception e) { System.err.println("EditorServer: lockRequested: error sending lock granted"); if (EditorServer_Debug) e.printStackTrace(); } } else { if (EditorServer_Debug) System.out.println("Lock Denied"); // send lock denied to sender Message.LockDenyMsg reply = new Message.LockDenyMsg(m.getClientId(), m.getIdNumber()); try { textChannel.sendToOthers(client, new Data(reply)); } catch (Exception e) { System.err.println("EditorServer: lockRequested: error sending lock denied"); if (EditorServer_Debug) e.printStackTrace(); } } }
@Override public void release(LockManager lockManager, Object resource, KernelTransaction tx) { lockManager.releaseWriteLock(resource, tx); }
private TaskExecutor(Context context) { mContext = context.getApplicationContext(); mTaskQueue = new LinkedList<Task>(); mLockManager = LockManager.get(mContext); }
/** * Creates a new Lock for reading and increments counter for active readers. The lock is tracked * if lock tracking is enabled. This method is not thread safe itself, the calling method is * expected to handle synchronization issues. * * @return a read lock. */ protected Lock createReadLock() { return activeReaders.createLock("Read"); }
/** * Blocks current thread until there are no reader locks active. * * @throws InterruptedException */ protected void waitForActiveReaders() throws InterruptedException { activeReaders.waitForActiveLocks(); }
/** * Blocks current thread until after the writer lock is released (if active). * * @throws InterruptedException */ protected void waitForActiveWriter() throws InterruptedException { activeWriter.waitForActiveLocks(); }
/** If one or more readers are active */ protected boolean isReaderActive() { return activeReaders.isActiveLock(); }
/** If a writer is active */ protected boolean isWriterActive() { return activeWriter.isActiveLock(); }
/** * Creates a new Lock for writing. The lock is tracked if lock tracking is enabled. This method is * not thread safe itself for performance reasons, the calling method is expected to handle * synchronization issues. * * @return a write lock. */ protected Lock createWriteLock() { return activeWriter.createLock("Write"); }
/** ロックが取得可能. */ @Test public void ロックが取得可能() { Lock lock = LockManager.getLock(Lock.CATEGORY_ODATA, "aaa", null, null); assertNotNull(lock); lock.release(); }