Implementation of the base writing method.  Operates in two stages:
<br/>
First turns the query result into a JSON message in Stackdriver format
<br/>
Second posts the message to the Stackdriver gateway via HTTP
975292
@Override
	public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception {
		String gatewayMessage = getGatewayMessage(results);

		// message won't be returned if there are no numeric values in the query results
		if (gatewayMessage != null) {
			logger.info(gatewayMessage);
			doSend(gatewayMessage);
		}
	}
14616
private void writeArray(JsonGenerator jsonGenerator, Object[] array, boolean firstInHierarchy) throws IOException, SQLException {
        if(!firstInHierarchy) {
            jsonGenerator.writeStartArray();
        }
        for(int i = 0; i < array.length; i++) {
            if (array[i] instanceof Integer) {
                jsonGenerator.writeNumber((int) array[i]);
            } else if (array[i] instanceof String) {
                if (array[i].equals("{}")) {
                    jsonGenerator.writeStartObject();
                    jsonGenerator.writeEndObject();
                } else {
                    jsonGenerator.writeString((String) array[i]);
                }
            } else if (array[i] instanceof Double) {
                jsonGenerator.writeNumber((double) array[i]);
            } else if (array[i] instanceof Boolean) {
                jsonGenerator.writeBoolean((boolean) array[i]);
            } else if (array[i] instanceof Object[]) {
                writeArray(jsonGenerator, (Object[]) array[i], false);
            }
        }
        if(!firstInHierarchy) {
            jsonGenerator.writeEndArray();
        }
    }
1275102
@Override
  public void write(JsonWriter out, WordTiming wordTiming) throws IOException {
    out.beginArray();

    out.value(wordTiming.getWord());
    out.value(wordTiming.getStartTime());
    out.value(wordTiming.getEndTime());

    out.endArray();
    out.flush();
  }
270428
@Override
  public void writeTop(JsonWriterImpl out, T value)
  {
    out.writeStartArray();
    write(out, value);
    out.writeEndArray();
  }
288986
public void sendMessage(BaseMessage messageOut, BaseInternalMessageProcessor messageOutProcessor)
    {
        int iErrorCode = this.convertToExternal(messageOut, messageOutProcessor);    // Convert my standard message to the external format for this message
        BaseMessage messageReplyIn = null;
        if (iErrorCode != DBConstants.NORMAL_RETURN)
        {
            String strMessageDescription = this.getTask().getLastError(iErrorCode);
            if ((strMessageDescription == null) || (strMessageDescription.length() == 0))
                strMessageDescription = "Error converting to external format";
            iErrorCode = this.getTask().setLastError(strMessageDescription);
            messageReplyIn = BaseMessageProcessor.processErrorMessage(this, messageOut, strMessageDescription);
        }
        else
        {
            Utility.getLogger().info("sendMessage externalTrxMessage = " + messageOut);

            messageReplyIn = this.sendMessageRequest(messageOut);
        }
        if (messageReplyIn != null)    // No reply if null.
        {
            this.setupReplyMessage(messageReplyIn, messageOut, MessageInfoTypeModel.REPLY, MessageTypeModel.MESSAGE_IN);
            Utility.getLogger().info("externalMessageReply: " + messageReplyIn);
            this.processIncomingMessage(messageReplyIn, messageOut);
        }
    }
618722
public void execute(final HttpQuery query) {
    http_query = query;
    final QueryStats query_stats = 
        new QueryStats(query.getRemoteAddress(), ts_query, query.getHeaders());
    ts_query.setQueryStats(query_stats);
    
    /**
     * Sends the serialized results to the caller. This should be the very
     * last callback executed.
     */
    class CompleteCB implements Callback<Object, ChannelBuffer> {
      @Override
      public Object call(final ChannelBuffer cb) throws Exception {
        query.sendReply(cb);
        return null;
      }
    }
    
    /**
     * After all of the queries have run and we have data (or not) then we
     * need to compile the iterators.
     * This class could probably be improved:
     * First we iterate over the results AND for each result, iterate over
     * the expressions, giving a time synced iterator to each expression that 
     * needs the result set.
     * THEN we iterate over the expressions again and build a DAG to determine
     * if any of the expressions require the output of an expression. If so
     * then we add the expressions to the proper parent and compile them in
     * order.
     * After all of that we're ready to start serializing and iterating
     * over the results.
     */
    class QueriesCB implements Callback<Object, ArrayList<DataPoints[]>> {
      public Object call(final ArrayList<DataPoints[]> query_results) 
        throws Exception {
        
        for (int i = 0; i < query_results.size(); i++) {
          final TSSubQuery sub = ts_query.getQueries().get(i);
          
          Iterator<Entry<String, TSSubQuery>> it = sub_queries.entrySet().iterator();
          while (it.hasNext()) {
            final Entry<String, TSSubQuery> entry = it.next();
            if (entry.getValue().equals(sub)) {
              sub_query_results.put(entry.getKey(), query_results.get(i));
              for (final ExpressionIterator ei : expressions.values()) {
                if (ei.getVariableNames().contains(entry.getKey())) {
                  final TimeSyncedIterator tsi = new TimeSyncedIterator(
                      entry.getKey(), sub.getFilterTagKs(), 
                      query_results.get(i));
                  final NumericFillPolicy fill = fills.get(entry.getKey());
                  if (fill != null) {
                    tsi.setFillPolicy(fill);
                  }
                  ei.addResults(entry.getKey(), tsi);
                  if (LOG.isDebugEnabled()) {
                    LOG.debug("Added results for " + entry.getKey() + 
                        " to " + ei.getId());
                  }
                }
              }
            }
          }
        }

        // handle nested expressions
        final DirectedAcyclicGraph<String, DefaultEdge> graph = 
            new DirectedAcyclicGraph<String, DefaultEdge>(DefaultEdge.class);

        for (final Entry<String, ExpressionIterator> eii : expressions.entrySet()) {
          if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("Expression entry key is %s, value is %s", 
                eii.getKey(), eii.getValue().toString()));
            LOG.debug(String.format("Time to loop through the variable names "
                + "for %s", eii.getKey()));
          }

          if (!graph.containsVertex(eii.getKey())) {
            if (LOG.isDebugEnabled()) {
              LOG.debug("Adding vertex " + eii.getKey());
            }
            graph.addVertex(eii.getKey());
          }

          for (final String var : eii.getValue().getVariableNames()) {
            if (LOG.isDebugEnabled()) {
              LOG.debug(String.format("var is %s", var));
            }

            final ExpressionIterator ei = expressions.get(var);

            if (ei != null) {
              if (LOG.isDebugEnabled()) {
                LOG.debug(String.format("The expression iterator for %s is %s", 
                    var, ei.toString()));
              }

              // TODO - really ought to calculate this earlier
              if (eii.getKey().equals(var)) {
                throw new IllegalArgumentException(
                    "Self referencing expression found: " + eii.getKey());
              }

              if (LOG.isDebugEnabled()) {
                LOG.debug("Nested expression detected. " + eii.getKey() + 
                    " depends on " + var);
              }

              if (!graph.containsVertex(eii.getKey())) {
                if (LOG.isDebugEnabled()) {
                  LOG.debug("Added vertex " + eii.getKey());
                }
                graph.addVertex(eii.getKey());
              } else if (LOG.isDebugEnabled()) {
                LOG.debug("Already contains vertex " + eii.getKey());
              }

              if (!graph.containsVertex(var)) {
                if (LOG.isDebugEnabled()) {
                  LOG.debug("Added vertex " + var);
                }
                graph.addVertex(var);
              } else if (LOG.isDebugEnabled()) {
                LOG.debug("Already contains vertex " + var);
              }

              try {
                if (LOG.isDebugEnabled()) {
                  LOG.debug("Added Edge " + eii.getKey() + " - " + var);
                }
                graph.addDagEdge(eii.getKey(), var);
              } catch (CycleFoundException cfe) {
                throw new IllegalArgumentException("Circular reference found: " + 
                    eii.getKey(), cfe);
              }
            } else if (LOG.isDebugEnabled()) {
              LOG.debug(String.format("The expression iterator for %s is null", var));
            }
          }
        }

        // compile all of the expressions
        final long intersect_start = DateTime.currentTimeMillis();

        final Integer expressionLength = expressions.size();
        final ExpressionIterator[] compile_stack = 
            new ExpressionIterator[expressionLength];
        final TopologicalOrderIterator<String, DefaultEdge> it = 
            new TopologicalOrderIterator<String, DefaultEdge>(graph);

        if (LOG.isDebugEnabled()) {
          LOG.debug(String.format("Expressions Size is %d", expressionLength));
          LOG.debug(String.format("Topology Iterator %s", it.toString()));
        }

        int i = 0;
        while (it.hasNext()) {
          String next = it.next();
          if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("Expression: %s", next));
          }
          ExpressionIterator ei = expressions.get(next);
          if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("Expression Iterator: %s", ei.toString()));
          }
          if (ei == null) {
            LOG.error(String.format("The expression iterator for %s is null", next));
          }
          compile_stack[i] = ei;
          if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("Added expression %s to compile_stack[%d]", 
                next, i));
          }
          i++;
        }

        if (i != expressionLength) {
          throw new IOException(String.format(" Internal Error: Fewer "
              + "expressions where added to the compile stack than "
              + "expressions.size (%d instead of %d)", i, expressionLength));
        }

        if (LOG.isDebugEnabled()) {
          LOG.debug(String.format("compile stack length: %d", compile_stack.length));
        }

        for (int x = compile_stack.length - 1; x >= 0; x--) {
          if (compile_stack[x] == null) {
            throw new NullPointerException(String.format("Item %d in "
                + "compile_stack[] is null", x));
          }
          // look for and add expressions
          for (final String var : compile_stack[x].getVariableNames()) {
            if (LOG.isDebugEnabled()) {
              LOG.debug(String.format("Looking for variable %s for %s", var, 
                  compile_stack[x].getId()));
            }
            ExpressionIterator source = expressions.get(var);
            if (source != null) {
              compile_stack[x].addResults(var, source.getCopy());
              if (LOG.isDebugEnabled()) {
                LOG.debug(String.format("Adding expression %s to %s", 
                    source.getId(), compile_stack[x].getId()));
              }
            }
          }
          compile_stack[x].compile();
          if (LOG.isDebugEnabled()) {
            LOG.debug(String.format("Successfully compiled %s", 
                compile_stack[x].getId()));
          }
        }

        if (LOG.isDebugEnabled()) {
          LOG.debug("Finished compilations in " +
              (DateTime.currentTimeMillis() - intersect_start) + " ms");
        }
        
        return serialize()
            .addCallback(new CompleteCB())
            .addErrback(new ErrorCB());
      }
    }
    
    /**
     * Callback executed after we have resolved the metric, tag names and tag
     * values to their respective UIDs. This callback then runs the actual 
     * queries and fetches their results.
     */
    class BuildCB implements Callback<Deferred<Object>, net.opentsdb.core.Query[]> {
      @Override
      public Deferred<Object> call(final net.opentsdb.core.Query[] queries) {
        final ArrayList<Deferred<DataPoints[]>> deferreds = 
            new ArrayList<Deferred<DataPoints[]>>(queries.length);
        
        for (final net.opentsdb.core.Query query : queries) {
          deferreds.add(query.runAsync());
        }
        return Deferred.groupInOrder(deferreds).addCallback(new QueriesCB())
            .addErrback(new ErrorCB());
      }
    }
    
    // TODO - only run the ones that will be involved in an output. Folks WILL
    // ask for stuff they don't need.... *sigh*
    ts_query.buildQueriesAsync(tsdb)
      .addCallback(new BuildCB())
      .addErrback(new ErrorCB());
  }
964372
def execute
      # Here is the order of operations:
      # -> setting @data_sent
      # -> executing before_request_execution callback
      # -> executing the HTTP request
      # -> setting @response
      # -> setting @data_received
      # -> executing after_request_execution callback

      # Setting @data_sent
      params = Rack::Utils.parse_nested_query(URI.parse(@http_request.path).query)
      # Since that's how it will be interpreted anyway on the server, we merge the POST params to the GET params,
      # but it's not supposed to happen: either every params is prepared for GET/query params, or as POST body
      params.merge!(Rack::Utils.parse_nested_query(@http_request.body.to_s))

      # About: Hash[{}.map{|k,v| [k, v.join] }]
      # it transforms the following hash:
      # {"accept"=>["*/*"], "user-agent"=>["TheBigDB RubyWrapper/X.Y.Z"], "host"=>["computer.host"]}
      # into the following hash:
      # {"accept"=>"*/*", "user-agent"=>"TheBigDB RubyWrapper/X.Y.Z", "host"=>"computer.host"}
      # which is way more useful and cleaner.
      @data_sent = {
        "headers" => Hash[@http_request.to_hash.map{|k,v| [k, v.join] }],
        "host" => @http.address,
        "port" => @http.port,
        "path" => URI.parse(@http_request.path).path,
        "method" => @http_request.method,
        "params" => params
      }

      # Executing callback
      TheBigDB.before_request_execution.call(self)

      # Here is where the request is actually executed
      @http_response = TheBigDB.http_request_executor.call(@http, @http_request)

      # Setting @response
      begin
        # We parse the JSON answer and return it.
        @response = JSON(@http_response.body)
      rescue JSON::ParserError => e
        @response = {"status" => "error", "error" => {"code" => "0000", "description" => "The server gave an invalid JSON body:\n#{@http_response.body}"}}
      end

      # Setting @data_received
      @data_received = {
        "headers" => Hash[@http_response.to_hash.map{|k,v| [k, v.join] }],
        "content" => @response
      }

      # Executing callback
      TheBigDB.after_request_execution.call(self)

      # Raising exception if asked
      if TheBigDB.raise_on_api_status_error and @response["status"] == "error"
        raise ApiStatusError.new(@response["error"]["code"])
      end

      self
    end
489969
@Override
	public void internalWrite(Server server, Query query, ImmutableList<Result> results) throws Exception {
		this.startOutput();
		for (String formattedResult : messageFormatter.formatResults(results, server)) {
				log.debug("Sending result: {}", formattedResult);
				this.sendOutput(formattedResult);
		}
		this.finishOutput();
	}
478353
private void write(Symbol symbol, BitWriter bitwriter)
            throws JSONException {
        try {
            Symbol back = symbol.back;
            if (back != null) {
                this.width += 1;
                write(back, bitwriter);
                if (back.zero == symbol) {
                    bitwriter.zero();
                } else {
                    bitwriter.one();
                }
            }
        } catch (Throwable e) {
            throw new JSONException(e);
        }
    }
1200173
public Writer write(Writer writer) throws JSONException {
		try {
			boolean b = false;
			Iterator keys = keys();
			writer.write('{');

			while (keys.hasNext()) {
				if (b) {
					writer.write(',');
				}
				Object k = keys.next();
				writer.write(quote(k.toString()));
				writer.write(':');
				Object v = this.map.get(k);
				if (v instanceof JSONObject) {
					((JSONObject) v).write(writer);
				} else if (v instanceof JSONArray) {
					((JSONArray) v).write(writer);
				} else {
					writer.write(valueToString(v));
				}
				b = true;
			}
			writer.write('}');
			return writer;
		} catch (IOException e) {
			throw new JSONException(e);
		}
	}
209348
@Override
  public void write(byte []buffer, int offset, int length,
                    boolean isEnd)
    throws IOException
  {
    int position = _position;
    
    if (length < 0) {
      throw new IllegalArgumentException();
    }
    
    if (_indexAddress < position + length) {
      throw new IllegalArgumentException(L.l("Segment write overflow pos=0x{0} len=0x{1} entry-head=0x{2} seg-len=0x{3}. {4}",
                                          Long.toHexString(_position),
                                          Long.toHexString(length),
                                          Long.toHexString(_indexAddress),
                                          Long.toHexString(_segment.length()),
                                          _segment));
    }
    

    //try (StoreWrite sOut = _readWrite.openWrite(_segment.getAddress(),
    //                                                _segment.getLength())) {
    
    _sOut.write(_segment.getAddress() + position, buffer, offset, length);

    _position = position + length;
      
    _isDirty = true;
  }
1028368
function JSONReporter(detector) {
  BaseReporter.call(this, detector);

  detector.on('start', function() {
    process.stdout.write('[');
  });

  detector.on('end', function() {
    process.stdout.write("]\n");
  });
}
1109743
@Broadcast(writeEntity = false)
    @POST
    @Produces("application/json")
    public Response broadcast(Message message) {
        return new Response(message.author, message.message);
    }
312106
@Override
    public WRITE_ACTION writeOrAddToQ(H2WriteQEntry entry) throws FlowControlException {
        synchronized (qSync) {

            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "process write entry with qStatus: " + qStatus + " entry: " + entry.hashCode());
            }
            if (entry.getFrameType() == FrameTypes.DATA) {
                decreaseConnectionWindowUpdateWriteLimit(entry.getPayloadLength());
            }

            if (qStatus == Q_STATUS.NOT_IN_USE) {
                // perform the write on this thread, outside the sync block
                qStatus = Q_STATUS.BYPASSED;
                entry.setServicedOnQ(false);

            } else if ((qStatus == Q_STATUS.ACTIVE) || (qStatus == Q_STATUS.STAND_BY)) {
                // queue is in use, so add this write entry to the queue/tree and leave
                entry.setServicedOnQ(true);
                addEntryToQ(entry);
                return WRITE_ACTION.QUEUED;

            } else if (qStatus == Q_STATUS.BYPASSED) {
                // queue is not in use, but needs to be now, since we are want to write with a write outstanding.
                entry.setServicedOnQ(true);
                qStatus = Q_STATUS.STAND_BY;
                addEntryToQ(entry);
                // wait for outstanding request to complete before allowing the queue thread to make more write requests
                try {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "waiting to start write Q thread");
                    }
                    qSync.wait();
                    qStatus = Q_STATUS.ACTIVE;
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "start write Q thread");
                    }
                    startQThread();
                    return WRITE_ACTION.QUEUED;
                } catch (InterruptedException e) {
                    // TODO: handle this somehow
                }

            } else if ((qStatus == Q_STATUS.QUIT) || (qStatus == Q_STATUS.FINISHED)) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "do not process write - Q told to quit");
                }
                return WRITE_ACTION.CONNECTION_QUIT;
            }
        } // end synchronized

        // Determined from above that we are to handle this write on the callers thread
        if (!(entry.getServicedOnQ())) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "perform write on caller's thread");
            }
            return writeEntry(entry);
        }

        // should never get here
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "uh-oh we're confused: WRITE_ACTION.CONFUSED");
        }
        return WRITE_ACTION.CONFUSED;
    }
750172
void writeProcessingInstruction(final Writer output, final String name, final String value)
            throws SAXException {
        try {
            output.write(LESS_THAN);
            output.write(QUESTION);
            output.write(name);
            if (value != null) {
                output.write(STRING_BLANK);
                output.write(value);
            }
            output.write(QUESTION);
            output.write(GREATER_THAN);
        } catch (IOException e) {
            throw new SAXException(e);
        }
    }
56578
@Override
  public void write(ByteCodeWriter out)
    throws IOException
  {
    out.writeUTF8Const(getName());

    TempOutputStream ts = new TempOutputStream();
    //ts.openWrite();
    //WriteStream ws = new WriteStream(ts);
    ByteCodeWriter o2 = new ByteCodeWriter(ts, out.getJavaClass());

    o2.writeShort(_methods.size());
    for (int i = 0; i < _methods.size(); i++) {
      BootstrapMethod method = _methods.get(i);
      
      o2.writeShort(method.getMethodRef());
      o2.writeShort(method.getArgumentSize());
      
      for (ConstantPoolEntry entry : method.getArguments()) {
        o2.writeShort(entry.getIndex());
      }
    }
    
    ts.close();
    
    out.writeInt(ts.getLength());
    
    TempBuffer ptr = ts.getHead();

    for (; ptr != null; ptr = ptr.next()) {
      out.write(ptr.buffer(), 0, ptr.length());
    }

    ts.destroy();
  }
379245
public synchronized void writeJSON(String outputDirectory, boolean bForceWrite) {
        logger.entering(new Object[] { outputDirectory, bForceWrite });

        long currentTime = System.currentTimeMillis();
        if (!bForceWrite && (currentTime - previousTime < ONE_MINUTE)) {
            return;
        }
        previousTime = currentTime;

        parseCompletedTest();

        generateReports(outputDirectory);

        logger.exiting();
    }