Defers loading the table to the underlying serializer.  Caches the result in ZooKeeper and passes it along
to the caller, just like {@link #loadAndSerialize(long, java.io.OutputStream)}.
763513
private Set<Long> writeToNode(String path, long uuid, OutputStream out)
            throws KeeperException.NodeExistsException, IOException, UnknownTableException, DroppedTableException {
        ByteArrayOutputStream bufferOut = new ByteArrayOutputStream();
        byte[] tableContent;
        Set<Long> uuids;
        Exception exception = null;

        try {
            // Load the table content from the source
            uuids = _source.loadAndSerialize(uuid, bufferOut);
            tableContent = bufferOut.toByteArray();
        } catch (UnknownTableException | DroppedTableException e) {
            // Record the exception and store the JSON serialized exception as the table content
            exception = e;
            tableContent = JsonHelper.asJson(e).getBytes(Charsets.UTF_8);
            uuids = ImmutableSet.of();
        }

        int nodeContentLength = 4 + 8 * uuids.size() + tableContent.length;  // 4 byte uuid count + 8 bytes per uuid + tableContent
        bufferOut = new ByteArrayOutputStream(nodeContentLength);
        DataOutputStream nodeOut = new DataOutputStream(bufferOut);

        if (exception == null) {
            // Write the actual number of UUIDs associated with the table
            nodeOut.writeInt(uuids.size());
            for (long sourceUuid : uuids) {
                nodeOut.writeLong(sourceUuid);
            }
        } else {
            // Write the exception code (no UUIDs will be written so no size is required)
            nodeOut.writeInt(exception instanceof UnknownTableException ? UNKNOWN_TABLE : DROPPED_TABLE);
        }

        nodeOut.write(tableContent);

        byte[] nodeContent = bufferOut.toByteArray();

        try {
            // Write the content to ZooKeeper
            _curator.create().withMode(CreateMode.PERSISTENT).forPath(path, nodeContent);
            _log.debug("Wrote table for UUID {} to {}", uuid, path);
        } catch (Throwable t) {
            // If the node exists then there was a race condition with another server caching the same table.  Pass
            // to the caller so they can retry reading the value.
            Throwables.propagateIfInstanceOf(t, KeeperException.NodeExistsException.class);
            Throwables.propagateIfInstanceOf(t, IOException.class);
            throw Throwables.propagate(t);
        }

        if (exception != null) {
            // This will always raise the exception
            Throwables.propagateIfPossible(exception, UnknownTableException.class, DroppedTableException.class);
        }

        out.write(tableContent);
        return uuids;
    }
1260101
private void scheduleLoadTicks() {
        Runnable sendLoadToZookeeper = new Runnable() {
            @Override
            public void run() {
                final List<String> loads = new ArrayList<String>();
                synchronized (meters) {
                    for (Map.Entry<String,Meter> entry : meters.entrySet()) {
                        final String workUnit = entry.getKey();
                        loads.add(String.format("/%s/meta/workload/%s", cluster.name, workUnit));
                        loads.add(String.valueOf(entry.getValue().getOneMinuteRate()));
                    }
                }

                Iterator<String> it = loads.iterator();
                while (it.hasNext()) {
                    final String path = it.next();
                    final String rate = it.next();
                    try {
                        ZKUtils.setOrCreate(cluster.zk, path, rate, CreateMode.PERSISTENT);
                    } catch (Exception e) {
                        // should we fail the loop too?
                        LOG.error("Problems trying to store load rate for {} (value {}): ({}) {}",
                                path, rate, e.getClass().getName(), e.getMessage());
                    }
                }

                String nodeLoadPath = String.format("/%s/nodes/%s", cluster.name, cluster.myNodeID);
                try {
                    NodeInfo myInfo = new NodeInfo(cluster.getState().toString(), cluster.zk.get().getSessionId());
                    byte[] myInfoEncoded = JsonUtil.asJSONBytes(myInfo);
                    ZKUtils.setOrCreate(cluster.zk, nodeLoadPath, myInfoEncoded, CreateMode.EPHEMERAL);
                    if (LOG.isDebugEnabled()) {
                        // TODO: Shouldn't be evaluating methods inside of a logging statement.
                        LOG.debug("My load: {}", myLoad());
                    }
                } catch (Exception e) {
                    LOG.error("Error reporting load info to ZooKeeper.", e);
                }
            }
        };

        loadFuture = cluster.scheduleAtFixedRate(sendLoadToZookeeper, 0, 1, TimeUnit.MINUTES);
    }
889535
public void init(final SerializedDataTypeRegistry typeRegistry, final DeserializerRegistry deserRegistry,
            final SerializerRegistry serRegistry) {
        if (initialized) {
            throw new IllegalStateException("Instance already initialized - Don't call the init methods more than once");
        }
        this.typeRegistry = typeRegistry;
        for (final JsonbDeserializer<?> deserializer : deserializers) {
            if (deserializer instanceof DeserializerRegistryRequired) {
                if (deserRegistry == null) {
                    throw new IllegalStateException(
                            "There is at least one deserializer that requires a 'DeserializerRegistry', but you didn't provide one (deserializer="
                                    + deserializer.getClass().getName() + ")");
                }
                final DeserializerRegistryRequired des = (DeserializerRegistryRequired) deserializer;
                des.setRegistry(deserRegistry);
            }
            if (deserializer instanceof SerializedDataTypeRegistryRequired) {
                if (typeRegistry == null) {
                    throw new IllegalStateException(
                            "There is at least one deserializer that requires a 'SerializedDataTypeRegistry', but you didn't provide one (deserializer="
                                    + deserializer.getClass().getName() + ")");
                }
                final SerializedDataTypeRegistryRequired des = (SerializedDataTypeRegistryRequired) deserializer;
                des.setRegistry(typeRegistry);
            }
        }
        for (final JsonbSerializer<?> serializer : serializers) {
            if (serializer instanceof SerializerRegistryRequired) {
                if (serRegistry == null) {
                    throw new IllegalStateException(
                            "There is at least one serializer that requires a 'SerializerRegistry', but you didn't provide one (serializer="
                                    + serializer.getClass().getName() + ")");
                }
                final SerializerRegistryRequired ser = (SerializerRegistryRequired) serializer;
                ser.setRegistry(serRegistry);
            }
            if (serializer instanceof SerializedDataTypeRegistryRequired) {
                if (typeRegistry == null) {
                    throw new IllegalStateException(
                            "There is at least one serializer that requires a 'SerializedDataTypeRegistry', but you didn't provide one (serializer="
                                    + serializer.getClass().getName() + ")");
                }
                final SerializedDataTypeRegistryRequired ser = (SerializedDataTypeRegistryRequired) serializer;
                ser.setRegistry(typeRegistry);
            }
        }
        initialized = true;
    }
1138284
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
		// Call the default implementation to de-serialize our object
		in.defaultReadObject();
		// init transients
		_validateLastModified = new AtomicBoolean(true);
		_cacheKeyGenMutex = new Semaphore(1);
		_isReportCacheInfo = false;
	}
483597
@Override
	public void load(final Reader reader) throws IOException {
		lock.writeLock().lock();
		try {
			properties.load(reader);
		} finally {
			lock.writeLock().unlock();
		}
	}
1374467
public void load(ClassLoader classLoader) {
        Map<String, GroovyRunner> map = runnerMap; // direct read
        if (map == null) {
            map = getMap(); // initialize and load (recursive call), result ignored
            if (classLoader == null) {
                // getMap() already loaded using a null classloader
                return;
            }
        }
        writeLock.lock();
        try {
            if (classLoader == null) {
                classLoader = Thread.currentThread().getContextClassLoader();
            }
            cachedValues = null;
            loadDefaultRunners();
            loadWithLock(classLoader);
        } catch (SecurityException se) {
            LOG.log(Level.WARNING, "Failed to get the context ClassLoader", se);
        } catch (ServiceConfigurationError sce) {
            LOG.log(Level.WARNING, "Failed to load GroovyRunner services from ClassLoader " + classLoader, sce);
        } finally {
            writeLock.unlock();
        }
    }
796121
static void deserialize(DataInput in, Serializers serializers)
      throws IOException, ClassNotFoundException {
    int size = in.readInt();
    if (size > 0) {
      StringBuilder msg = new StringBuilder(String.format("Deserialize %d serializer classes:", size));

      if (serializers.serializersArray.length < size) {
        serializers.serializersArray = Arrays.copyOf(serializers.serializersArray, size);
      }

      int max = 0;
      for (int i = 0; i < size; i++) {
        int index = in.readInt();
        max = Math.max(max, index);
        String serializerClassName = in.readUTF();
        try {
          Class<Serializer> serializerClass = (Class<Serializer>) Class.forName(serializerClassName);
          Serializer serializerInstance = serializerClass.newInstance();
          serializers.serializers
              .put(getSerializerType(serializerInstance), new SerializerWrapper(index, serializerInstance));
          serializers.serializersArray[index] = serializerInstance;

          msg.append(String.format("%n  (%d) %s", index, serializerClassName));
        } catch (Exception ex) {
          LOGGER.log(Level.WARNING, (String.format("Can't find the serializer '%s'", serializerClassName)), ex);
        }
      }
      serializers.COUNTER.set(max + 1);

      LOGGER.info(msg.toString());
    }
  }
807722
private Deferred<ChannelBuffer> serialize() throws Exception {
    final long start = System.currentTimeMillis();
    // buffers and an array list to stored the deferreds
    final ChannelBuffer response = ChannelBuffers.dynamicBuffer();
    final OutputStream output_stream = new ChannelBufferOutputStream(response);

    final JsonGenerator json = JSON.getFactory().createGenerator(output_stream);
    json.writeStartObject();
    json.writeFieldName("outputs");
    json.writeStartArray();

    // We want the serializer to execute serially so we need to create a callback
    // chain so that when one DPsResolver is finished, it triggers the next to
    // start serializing.
    final Deferred<Object> cb_chain = new Deferred<Object>();

    // default to the expressions if there, or fall back to the metrics
    final List<Output> outputs;
    if (query.getOutputs() == null || query.getOutputs().isEmpty()) {
      if (query.getExpressions() != null && !query.getExpressions().isEmpty()) {
        outputs = new ArrayList<Output>(query.getExpressions().size());
        for (final Expression exp : query.getExpressions()) {
          outputs.add(Output.Builder().setId(exp.getId()).build());
        }
      } else if (query.getMetrics() != null && !query.getMetrics().isEmpty()) {
        outputs = new ArrayList<Output>(query.getMetrics().size());
        for (final Metric metric : query.getMetrics()) {
          outputs.add(Output.Builder().setId(metric.getId()).build());
        }
      } else {
        throw new IllegalArgumentException(
            "How did we get here?? No metrics or expressions??");
      }
    } else {
      outputs = query.getOutputs();
    }

    for (final Output output : outputs) {
      if (expressions != null) {
        final ExpressionIterator it = expressions.get(output.getId());
        if (it != null) {
          cb_chain.addCallback(new SerializeExpressionIterator(tsdb, json, 
              output, it, ts_query));
          continue;
        }
      }

      if (query.getMetrics() != null && !query.getMetrics().isEmpty()) {
        final TSSubQuery sub = sub_queries.get(output.getId());
        if (sub != null) {
          final TimeSyncedIterator it = new TimeSyncedIterator(output.getId(), 
              sub.getFilterTagKs(), sub_query_results.get(output.getId()));
          cb_chain.addCallback(new SerializeSubIterator(tsdb, json, output, it));
          continue;
        }
      } else {
        LOG.warn("Couldn't find a variable matching: " + output.getId() + 
            " in query " + query);
      }
    }
  
    /** Final callback to close out the JSON array and return our results */
    class FinalCB implements Callback<ChannelBuffer, Object> {
      public ChannelBuffer call(final Object obj)
          throws Exception {
        json.writeEndArray();
        
//        ts_query.getQueryStats().setTimeSerialization(
//            DateTime.currentTimeMillis() - start);
        ts_query.getQueryStats().markSerializationSuccessful();

        // dump overall stats as an extra object in the array
//        if (true) {
//          final QueryStats stats = ts_query.getQueryStats();
//          json.writeFieldName("statsSummary");
//          json.writeStartObject();
//          //json.writeStringField("hostname", TSDB.getHostname());
//          //json.writeNumberField("runningQueries", stats.getNumRunningQueries());
//          json.writeNumberField("datapoints", stats.getAggregatedSize());
//          json.writeNumberField("rawDatapoints", stats.getSize());
//          //json.writeNumberField("rowsFetched", stats.getRowsFetched());
//          json.writeNumberField("aggregationTime", stats.getTimeAggregation());
//          json.writeNumberField("serializationTime", stats.getTimeSerialization());
//          json.writeNumberField("storageTime", stats.getTimeStorage());
//          json.writeNumberField("timeTotal", 
//              ((double)stats.getTimeTotal() / (double)1000000));
//          json.writeEndObject();
//        }
        
        // dump the original query
        if (true) {
          json.writeFieldName("query");
          json.writeObject(QueryExecutor.this.query);
        }
        // IMPORTANT Make sure the close the JSON array and the generator
        json.writeEndObject();
        json.close();
        return response;
      }
    }

    // trigger the callback chain here
    cb_chain.callback(null);
    return cb_chain.addCallback(new FinalCB());
  }
1008362
@Override
    public synchronized boolean load() {
        Either<Void, T> oldData = data;
        String oldKey = versionedKey;
        try {
            if (isOutOfDate()) {
                String newVersionedKey = (String) connection.get(key)
                                                            .get();
                data = Either.right((T) nonAtomicload(newVersionedKey));
                versionedKey = newVersionedKey;
            } else {
                return false;
            }
        } catch (Throwable e) {
            data = oldData;
            versionedKey = oldKey;
            logger.debug(e.getMessage(), e);
            throw ExceptionSoftener.throwSoftenedException(e);
        }
        return true;
    }
862481
@VisibleForTesting
    LogMetadata loadMetadata() throws DataLogInitializationException {
        try {
            Stat storingStatIn = new Stat();
            byte[] serializedMetadata = this.zkClient.getData().storingStatIn(storingStatIn).forPath(this.logNodePath);
            LogMetadata result = LogMetadata.SERIALIZER.deserialize(serializedMetadata);
            result.withUpdateVersion(storingStatIn.getVersion());
            return result;
        } catch (KeeperException.NoNodeException nne) {
            // Node does not exist: this is the first time we are accessing this log.
            log.warn("{}: No ZNode found for path '{}{}'. This is OK if this is the first time accessing this log.",
                    this.traceObjectId, this.zkClient.getNamespace(), this.logNodePath);
            return null;
        } catch (Exception ex) {
            throw new DataLogInitializationException(String.format("Unable to load ZNode contents for path '%s%s'.",
                    this.zkClient.getNamespace(), this.logNodePath), ex);
        }
    }
782272
@SuppressWarnings("unchecked")
  private T readReference(Class<T> type, BufferInput<?> buffer, Serializer serializer) {
    ReferencePool<?> pool = pools.get(type);
    if (pool == null) {
      Constructor<?> constructor = constructorMap.get(type);
      if (constructor == null) {
        try {
          constructor = type.getDeclaredConstructor(ReferenceManager.class);
          constructor.setAccessible(true);
          constructorMap.put(type, constructor);
        } catch (NoSuchMethodException e) {
          throw new SerializationException("failed to instantiate reference: must provide a single argument constructor", e);
        }
      }

      pool = new ReferencePool<>(createFactory(constructor));
      pools.put(type, pool);
    }
    T object = (T) pool.acquire();
    object.readObject(buffer, serializer);
    return object;
  }
900008
public static void loadResource(final String serializerId,
      @SuppressWarnings("rawtypes") final Map<String, ArtifactSerializer> artifactSerializers,
      final String resourcePath, final Map<String, Object> resources) {

    final File resourceFile = new File(resourcePath);
    if (resourceFile != null) {
      final String resourceId = IOUtils
          .normalizeLexiconName(resourceFile.getName());
      final ArtifactSerializer<?> serializer = artifactSerializers
          .get(serializerId);
      final InputStream resourceIn = IOUtils.openFromFile(resourceFile);
      try {
        resources.put(resourceId, serializer.create(resourceIn));
      } catch (final InvalidFormatException e) {
        e.printStackTrace();
      } catch (final IOException e) {
        e.printStackTrace();
      } finally {
        try {
          resourceIn.close();
        } catch (final IOException e) {
        }
      }
    }
  }
962500
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
        GetField fields = in.readFields();
        classLoaderIdentifier = (String) fields.get(CLASS_LOADER_IDENTIFIER, null);

        // Note that further processing is required in JEEMetadataContextProviderImpl.deserializeThreadContext
        // in order to re-establish the thread context based on the metadata identifier if not defaulted.
    }
285589
public void loadFully(boolean skip, Protocol protocol) throws SQLException {
    if (fetchSize != 0) {
      fetchSize = 0;
      if (resultSet != null) {
        if (skip) {
          resultSet.close();
        } else {
          resultSet.fetchRemaining();
        }
      } else {
        SelectResultSet firstResult = executionResults.peekFirst();
        if (firstResult != null) {
          if (skip) {
            firstResult.close();
          } else {
            firstResult.fetchRemaining();
          }
        }
      }
    }

    if (protocol.hasMoreResults()) {
      protocol.getResult(this);
    }
  }
1232920
@Override
	protected void serializeTo(RawDataBuffer out)
    {
        super.serializeTo(out);
        out.writeInt(sessionId.asInt());
        out.writeInt(consumerId.asInt());
        MessageSerializer.serializeTo(message, out);
        out.writeBoolean(donePrefetching);
    }
501538
public Deferred<TreeMap<byte[], Span>> fetch() {
    if(tags.isEmpty()) {
      return Deferred.fromResult(null);
    }
    startFetch();
    return results;
  }
1219187
private <T> T loadDataFromCache(final Class<T> clazz, final Object cacheKey, final long maxTimeInCacheBeforeExpiry) throws CacheLoadingException, CacheCreationException {
        return cacheManager.loadDataFromCache(clazz, cacheKey, maxTimeInCacheBeforeExpiry);
    }