Writes the last transaction id of the primary avatarnode to zookeeper.
490160
static void writeLastTxidToZookeeper(long lastTxid, long totalBlocks,
      long totalInodes, long ssid, Configuration startupConf,
      Configuration confg) throws IOException {
    AvatarZooKeeperClient zk = null;
    LOG.info("Writing lastTxId: " + lastTxid + ", total blocks: " + totalBlocks
        + ", total inodes: " + totalInodes);
    if (lastTxid < 0) {
      LOG.warn("Invalid last transaction id : " + lastTxid
          + " skipping write to zookeeper.");
      return;
    }
    ZookeeperTxId zkTxid = new ZookeeperTxId(ssid, lastTxid, totalBlocks,
        totalInodes);
    int maxTries = startupConf.getInt("dfs.avatarnode.zk.retries", 3);
    for (int i = 0; i < maxTries; i++) {
      try {
        zk = new AvatarZooKeeperClient(confg, null, false);
        zk.registerLastTxId(startupConf.get(NameNode.DFS_NAMENODE_RPC_ADDRESS_KEY), zkTxid);
        return;
      } catch (Exception e) {
        LOG.error("Got Exception when syncing last txid to zk. Will retry...",
            e);
      } finally {
        shutdownZkClient(zk);
      }
    }
    throw new IOException("Cannot connect to zk");
  }
1079346
@Override
    public Row lastRow(Session session, PersistentStore store) {

        readLock.lock();

        try {
            NodeAVL x = getAccessor(store);
            NodeAVL l = x;

            while (l != null) {
                x = l;
                l = x.getRight(store);
            }

            while (session != null && x != null) {
                Row row = x.getRow(store);

                if (session.database.txManager.canRead(session, row)) {
                    break;
                }

                x = last(store, x);
            }

            return x == null ? null
                             : x.getRow(store);
        } finally {
            readLock.unlock();
        }
    }
135635
protected void prepareToAddChildNode() throws IOException {
		// reject modification of already closed document
		if(isOpen==false) {
			throw new IOException("Attempting to write to a closed document!");
		}
		// close previous tag, if applicable
		if(lastChildNode!=null) {
			lastChildNode.close();
			lastChildNode = null;
		}
		writer.write("\n");
	}
619841
private <Q, R> void recordFinalStatus(JobIdentifier<Q, R> jobId, JobStatus<Q, R> jobStatus) {
        try {
            _jobStatusDAO.updateJobStatus(jobId, jobStatus);
        } catch (Exception e) {
            _log.error("Failed to record final status for job: [id={}, status={}]", jobId, jobStatus.getStatus(), e);
        }
    }
391176
private void datanodeDump(PrintWriter out) {
    readLock();
    try {
      synchronized (datanodeMap) {
        out.println("Metasave: Number of datanodes: " + datanodeMap.size());
        for (Iterator<DatanodeDescriptor> it = datanodeMap.values().iterator(); it.hasNext();) {
          DatanodeDescriptor node = it.next();
          out.println(node.dumpDatanode());
        }
      }
    } finally {
      readUnlock();
    }
  }
944363
void doSave(XMLWriter w) throws KNXMLException
	{
		// <expiration timeout=int />
		w.writeEmptyElement(TAG_EXPIRATION, Arrays
			.asList(new Attribute[] { new Attribute(ATTR_TIMEOUT, Integer
				.toString(timeout)) }));
		w.writeElement(TAG_UPDATING, Collections.EMPTY_LIST, null);
		synchronized (updating) {
			for (final Iterator i = updating.iterator(); i.hasNext();)
				((GroupAddress) i.next()).save(w);
		}
		w.endElement();
		w.writeElement(TAG_INVALIDATING, Collections.EMPTY_LIST, null);
		synchronized (invalidating) {
			for (final Iterator i = invalidating.iterator(); i.hasNext();)
				((GroupAddress) i.next()).save(w);
		}
		w.endElement();
	}
1130780
public void write(ObjectWriter out, PersistedNodeData nodeData) throws IOException
   {
      // write id
      out.writeInt(SerializationConstants.PERSISTED_NODE_DATA);

      // TransientItemData
      out.writeString(nodeData.getQPath().getAsString());
      out.writeString(nodeData.getIdentifier());

      if (nodeData.getParentIdentifier() != null)
      {
         out.writeByte(SerializationConstants.NOT_NULL_DATA);
         out.writeString(nodeData.getParentIdentifier());
      }
      else
         out.writeByte(SerializationConstants.NULL_DATA);

      out.writeInt(nodeData.getPersistedVersion());
      // -------------------

      out.writeInt(nodeData.getOrderNumber());

      // primary type
      out.writeString(nodeData.getPrimaryTypeName().getAsString());

      // mixins
      InternalQName[] mixinNames = nodeData.getMixinTypeNames();

      if (mixinNames != null)
      {
         out.writeByte(SerializationConstants.NOT_NULL_DATA);
         out.writeInt(mixinNames.length);
         for (int i = 0; i < mixinNames.length; i++)
         {
            out.writeString(mixinNames[i].getAsString());
         }
      }
      else
      {
         out.writeByte(SerializationConstants.NULL_DATA);
      }

      ACLWriter wr = new ACLWriter();

      AccessControlList acl = nodeData.getACL();
      if (acl != null)
      {
         out.writeByte(SerializationConstants.NOT_NULL_DATA);
         wr.write(out, acl);
      }
      else
      {
         out.writeByte(SerializationConstants.NULL_DATA);
      }
   }
1153973
public static void writeCatalogToZK(ZooKeeper zk,
                                        long genId,
                                        byte[] catalogBytes,
                                        byte[] catalogHash,
                                        byte[] deploymentBytes)
        throws KeeperException, InterruptedException
    {
        // use default version 0 as start
        ByteBuffer versionAndBytes = makeCatalogAndDeploymentBytes(0, genId,
                catalogBytes, catalogHash, deploymentBytes);
        zk.create(VoltZK.catalogbytes,
                versionAndBytes.array(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
    }
133557
void writeCachedLastAccessedTimes(Connection nukerCon) throws Exception {
        if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
            LoggingUtil.SESSION_LOGGER_WAS.entering(methodClassName, methodNames[WRITE_CACHED_LAST_ACCESSED_TIMES]);
        }

        // create a copy for the updates, then atomically clear the table
        // the hashtable table clone is shallow, it will not dup the keys/elements
        Hashtable updTab = (Hashtable) cachedLastAccessedTimes.clone();
        cachedLastAccessedTimes.clear();
        Enumeration updEnum = updTab.keys();
        String id = null;
        PreparedStatement ps = null;
        boolean psClose = false;

        while (updEnum.hasMoreElements()) {

            id = (String) updEnum.nextElement();
            Long timeObj = (Long) updTab.get(id);
            long time = timeObj.longValue();
            try {
                ps = nukerCon.prepareStatement(asyncUpdate);
                setPSLong(ps, 1, time);
                ps.setString(2, id);
                ps.setString(3, id);
                ps.setString(4, getIStore().getId());

                ps.executeUpdate();
                ps.close();
                psClose = true;
                if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                    LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[WRITE_CACHED_LAST_ACCESSED_TIMES], "handleAsyncUpdates"
                                                                                                                                    + " - Updating LastAccess for " + id);
                }
            } catch (Exception se1) {
                //                if (isStaleConnectionException(se1)) {
                //                    com.ibm.ws.ffdc.FFDCFilter.processException(se1, "com.ibm.ws.session.store.db.DatabaseHashMap.writeCachedLastAccessedTimes", "2102", id);
                //                    if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled()&&LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                //                        LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[WRITE_CACHED_LAST_ACCESSED_TIMES], "StaleConnectionException");
                //                    }
                //                    throw se1;
                //                } else {
                com.ibm.ws.ffdc.FFDCFilter.processException(se1, "com.ibm.ws.session.store.db.DatabaseHashMap.writeCachedLastAccessedTimes", "2109", id);
                LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[WRITE_CACHED_LAST_ACCESSED_TIMES], "DatabaseHashMap.handleAsyncError");
                LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[WRITE_CACHED_LAST_ACCESSED_TIMES], "CommonMessage.sessionid", id);
                LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[WRITE_CACHED_LAST_ACCESSED_TIMES], "CommonMessage.exception", se1);
                throw se1;
                //                }
            } finally {
                if (!psClose && ps != null) {
                    closeStatement(ps);
                }
            }
        }

    }
72662
private void putNodeToStore(final Node<K, V> node) {
		final int nodeid = node.id;
		final int index = (nodeid < 0 ? -nodeid : nodeid);
		final WriteBuffer wbuf = storage.set(index);
		final ByteBuffer buf = wbuf.buf();
		if (node.isDeleted()) { 	// This block is for delete
			if (cleanBlocksOnFree) {
				buf.clear();
				int cx = (blockSize >> 3); // division by 8
				while (cx-- > 0) {
					buf.putLong(0);	// Fill with zeroes
				}
				buf.flip();
			} else {
				node.clean(buf); 	// Generate zeroed minimal buffer
			}
			freeBlocks.set(index); 	// Mark block as free
		} else {
			node.serialize(buf);
		}
		wbuf.save();
		if (enableDirtyCheck) {
			dirtyCheck.clear(index);
		}
		if (enableIOStats) {
			getIOStat(nodeid).incPhysWrite();
		}
	}
835429
@Override
    public void end() {
        final EntityManager em = entityManager.get();

        // Let's not penalize users for calling end() multiple times.
        if (null == em) {
          return;
        }

        final EntityTransaction tx = em.getTransaction();

        if(tx.isActive()) {
            LOG.warn("There was an active transaction at the end of a request");
            tx.commit();
        }

        em.close();
        entityManager.remove();
    }
735725
void writeTransactionIdFile(StorageDirectory sd, long txid) throws IOException {
    if (txid < -1) {
      // -1 is valid when formatting
      throw new IOException("Bad txid: " + txid);
    }
    File txIdFile = getStorageFile(sd, NameNodeFile.SEEN_TXID);
    OutputStream fos = new AtomicFileOutputStream(txIdFile);
    try {
      fos.write(String.valueOf(txid).getBytes());
      fos.write('\n');
      fos.close();
      fos = null;
    } finally {
      IOUtils.cleanup(LOG, fos);
    }
  }
1182745
public void put(@NotNull final PersistentStoreTransaction txn,
                    final long localId,
                    @NotNull final ByteIterable value,
                    @Nullable final ByteIterable oldValue,
                    final int propertyId,
                    @NotNull final ComparableValueType type) {
        final Store valueIdx = getOrCreateValueIndex(txn, propertyId);
        final ByteIterable key = PropertyKey.propertyKeyToEntry(new PropertyKey(localId, propertyId));
        final Transaction envTxn = txn.getEnvironmentTransaction();
        primaryStore.put(envTxn, key, value);
        final ByteIterable secondaryValue = LongBinding.longToCompressedEntry(localId);
        boolean success;
        if (oldValue == null) {
            success = allPropsIndex.put(envTxn, IntegerBinding.intToCompressedEntry(propertyId), secondaryValue);
        } else {
            success = deleteFromStore(envTxn, valueIdx, secondaryValue, createSecondaryKeys(store.getPropertyTypes(), oldValue, type));
        }
        if (success) {
            for (final ByteIterable secondaryKey : createSecondaryKeys(store.getPropertyTypes(), value, type)) {
                valueIdx.put(envTxn, secondaryKey, secondaryValue);
            }
        }
        checkStatus(success, "Failed to put");
    }
932378
public void quiesceStandby(long txId) throws IOException {
    if (currentAvatar != Avatar.STANDBY) {
      throw new IOException("This is not the standby avatar");
    }
    standby.quiesce(txId);
  }
431644
public static ResourceClaim claimExpiring(ZooKeeperConnection zooKeeperConnection, int poolSize, String znode)
            throws IOException {
        return claimExpiring(zooKeeperConnection, poolSize, znode, DEFAULT_TIMEOUT);
    }
691910
private void sendSnapshotTxnId(SnapshotInfo toRestore) {
        long txnId = toRestore != null ? toRestore.txnId : 0;
        String jsonData = toRestore != null ? toRestore.toJSONObject().toString() : "{}";
        LOG.debug("Sending snapshot ID " + txnId + " for restore to other nodes");
        try {
            m_zk.create(VoltZK.restore_snapshot_id, jsonData.getBytes(Constants.UTF8ENCODING),
                        Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
        } catch (Exception e) {
            VoltDB.crashGlobalVoltDB("Failed to create Zookeeper node: " + e.getMessage(),
                                     false, e);
        }
    }
1146331
static void releaseTicket(ZooKeeper zookeeper, String lockNode, String ticket)
            throws KeeperException, InterruptedException {

        logger.debug("Releasing ticket {}.", ticket);
        try {
            zookeeper.delete(lockNode + "/" + ticket, -1);
        } catch (KeeperException e) {
            if (e.code() != KeeperException.Code.NONODE) {
                // If it the node is already gone, than that is fine, otherwise:
                throw e;
            }
        }
    }