text:
require File.expand_path("../../spec_helper", __FILE__)
require 'chef/resource_reporter'

describe Chef::ResourceReporter do
  before(:all) do
    @reporting_toggle_default = Chef::Config[:enable_reporting]
    Chef::Config[:enable_reporting] = true
  end

  after(:all) do
    Chef::Config[:enable_reporting] = @reporting_toggle_default
  end

  before do
    @node = Chef::Node.new
    @node.name("spitfire")
    @rest_client = double("Chef::REST (mock)")
    @rest_client.stub(:post_rest).and_return(true)
    @resource_reporter = Chef::ResourceReporter.new(@rest_client)
    @new_resource      = Chef::Resource::File.new("/tmp/a-file.txt")
    @cookbook_name = "monkey"
    @new_resource.cookbook_name = @cookbook_name
    @cookbook_version = double("Cookbook::Version", :version => "1.2.3")
    @new_resource.stub(:cookbook_version).and_return(@cookbook_version)
    @current_resource  = Chef::Resource::File.new("/tmp/a-file.txt")
    @start_time = Time.new
    @end_time = Time.new + 20
    @events = Chef::EventDispatch::Dispatcher.new
    @run_context = Chef::RunContext.new(@node, {}, @events)
    @run_status = Chef::RunStatus.new(@node, @events)
    @run_id = @run_status.run_id
    Time.stub(:now).and_return(@start_time, @end_time)
  end

  context "when first created" do

    it "has no updated resources" do
      @resource_reporter.should have(0).updated_resources
    end

    it "reports a successful run" do
      @resource_reporter.status.should == "success"
    end

    it "assumes the resource history feature is supported" do
      @resource_reporter.reporting_enabled?.should be_true
    end

    it "should have no error_descriptions" do
      @resource_reporter.error_descriptions.should eq({})
      # @resource_reporter.error_descriptions.should be_empty
      # @resource_reporter.should have(0).error_descriptions
    end

  end

  context "after the chef run completes" do

    before do
    end

    it "reports a successful run" do
      pending "refactor how node gets set."
      @resource_reporter.status.should == "success"
    end
  end

  context "when chef fails" do
    before do
      @rest_client.stub(:create_url).and_return("reports/nodes/spitfire/runs/#{@run_id}");
      @rest_client.stub(:raw_http_request).and_return({"result"=>"ok"});
      @rest_client.stub(:post_rest).and_return({"uri"=>"https://example.com/reports/nodes/spitfire/runs/#{@run_id}"});

    end

    context "before converging any resources" do
      before do
        @resource_reporter.run_started(@run_status)
        @exception = Exception.new
        @resource_reporter.run_failed(@exception)
      end

      it "sets the run status to 'failure'" do
        @resource_reporter.status.should == "failure"
      end

      it "keeps the exception data" do
        @resource_reporter.exception.should == @exception
      end
    end

    context "when a resource fails before loading current state" do
      before do
        @exception = Exception.new
        @exception.set_backtrace(caller)
        @resource_reporter.resource_action_start(@new_resource, :create)
        @resource_reporter.resource_failed(@new_resource, :create, @exception)
        @resource_reporter.resource_completed(@new_resource)
      end

      it "collects the resource as an updated resource" do
        @resource_reporter.should have(1).updated_resources
      end

      it "collects the desired state of the resource" do
        update_record = @resource_reporter.updated_resources.first
        update_record.new_resource.should == @new_resource
      end
    end

    # TODO: make sure a resource that is skipped because of `not_if` doesn't
    # leave us in a bad state.

    context "once the a resource's current state is loaded" do
      before do
        @resource_reporter.resource_action_start(@new_resource, :create)
        @resource_reporter.resource_current_state_loaded(@new_resource, :create, @current_resource)
      end

      context "and the resource was not updated" do
        before do
          @resource_reporter.resource_up_to_date(@new_resource, :create)
        end

        it "has no updated resources" do
          @resource_reporter.should have(0).updated_resources
        end
      end

      context "and the resource was updated" do
        before do
          @new_resource.content("this is the old content")
          @current_resource.content("this is the new hotness")
          @resource_reporter.resource_updated(@new_resource, :create)
          @resource_reporter.resource_completed(@new_resource)
        end

        it "collects the updated resource" do
          @resource_reporter.should have(1).updated_resources
        end

        it "collects the old state of the resource" do
          update_record = @resource_reporter.updated_resources.first
          update_record.current_resource.should == @current_resource
        end

        it "collects the new state of the resource" do
          update_record = @resource_reporter.updated_resources.first
          update_record.new_resource.should == @new_resource
        end

        context "and a subsequent resource fails before loading current resource" do
          before do
            @next_new_resource = Chef::Resource::Service.new("apache2")
            @exception = Exception.new
            @exception.set_backtrace(caller)
            @resource_reporter.resource_failed(@next_new_resource, :create, @exception)
            @resource_reporter.resource_completed(@next_new_resource)
          end

          it "collects the desired state of the failed resource" do
            failed_resource_update = @resource_reporter.updated_resources.last
            failed_resource_update.new_resource.should == @next_new_resource
          end

          it "does not have the current state of the failed resource" do
            failed_resource_update = @resource_reporter.updated_resources.last
            failed_resource_update.current_resource.should be_nil
          end
        end
      end

      # Some providers, such as RemoteDirectory and some LWRPs use other
      # resources for their implementation. These should be hidden from reporting
      # since we only care about the top-level resource and not the sub-resources
      # used for implementation.
      context "and a nested resource is updated" do
        before do
          @implementation_resource = Chef::Resource::CookbookFile.new("/preseed-file.txt")
        @resource_reporter.resource_action_start(@implementation_resource , :create)
        @resource_reporter.resource_current_state_loaded(@implementation_resource, :create, @implementation_resource)
        @resource_reporter.resource_updated(@implementation_resource, :create)
        @resource_reporter.resource_completed(@implementation_resource)
        @resource_reporter.resource_updated(@new_resource, :create)
        @resource_reporter.resource_completed(@new_resource)
      end

        it "does not collect data about the nested resource" do
          @resource_reporter.should have(1).updated_resources
        end
      end

      context "and a nested resource runs but is not updated" do
        before do
          @implementation_resource = Chef::Resource::CookbookFile.new("/preseed-file.txt")
          @resource_reporter.resource_action_start(@implementation_resource , :create)
          @resource_reporter.resource_current_state_loaded(@implementation_resource, :create, @implementation_resource)
          @resource_reporter.resource_up_to_date(@implementation_resource, :create)
          @resource_reporter.resource_completed(@implementation_resource)
          @resource_reporter.resource_updated(@new_resource, :create)
          @resource_reporter.resource_completed(@new_resource)
        end

        it "does not collect data about the nested resource" do
          @resource_reporter.should have(1).updated_resources
        end
      end

      context "and the resource failed to converge" do
        before do
          @exception = Exception.new
          @exception.set_backtrace(caller)
          @resource_reporter.resource_failed(@new_resource, :create, @exception)
          @resource_reporter.resource_completed(@new_resource)
        end

        it "collects the resource as an updated resource" do
          @resource_reporter.should have(1).updated_resources
        end

        it "collects the desired state of the resource" do
          update_record = @resource_reporter.updated_resources.first
          update_record.new_resource.should == @new_resource
        end

        it "collects the current state of the resource" do
          update_record = @resource_reporter.updated_resources.first
          update_record.current_resource.should == @current_resource
        end
      end

    end
  end

  describe "when generating a report for the server" do

    before do
      @rest_client.stub(:create_url).and_return("reports/nodes/spitfire/runs/#{@run_id}");
      @rest_client.stub(:raw_http_request).and_return({"result"=>"ok"});
      @rest_client.stub(:post_rest).and_return({"uri"=>"https://example.com/reports/nodes/spitfire/runs/#{@run_id}"});

      @resource_reporter.run_started(@run_status)
    end

    context "when the new_resource does not have a string for name and identity" do
      context "the new_resource name and id are nil" do
        before do
          @bad_resource = Chef::Resource::File.new("/tmp/nameless_file.txt")
          @bad_resource.stub(:name).and_return(nil)
          @bad_resource.stub(:identity).and_return(nil)
          @resource_reporter.resource_action_start(@bad_resource, :create)
          @resource_reporter.resource_current_state_loaded(@bad_resource, :create, @current_resource)
          @resource_reporter.resource_updated(@bad_resource, :create)
          @resource_reporter.resource_completed(@bad_resource)
          @run_status.stop_clock
          @report = @resource_reporter.prepare_run_data
          @first_update_report = @report["resources"].first
        end

        it "resource_name in prepared_run_data is a string" do
          @first_update_report["name"].class.should == String
        end

        it "resource_id in prepared_run_data is a string" do
          @first_update_report["id"].class.should == String
        end
      end

      context "the new_resource name and id are hashes" do
        before do
          @bad_resource = Chef::Resource::File.new("/tmp/filename_as_hash.txt")
          @bad_resource.stub(:name).and_return({:foo=>:bar})
          @bad_resource.stub(:identity).and_return({:foo=>:bar})
          @resource_reporter.resource_action_start(@bad_resource, :create)
          @resource_reporter.resource_current_state_loaded(@bad_resource, :create, @current_resource)
          @resource_reporter.resource_updated(@bad_resource, :create)
          @resource_reporter.resource_completed(@bad_resource)
          @run_status.stop_clock
          @report = @resource_reporter.prepare_run_data
          @first_update_report = @report["resources"].first
        end
        # Ruby 1.8.7 flattens out hash to string using join instead of inspect, resulting in
        # irb(main):001:0> {:foo => :bar}.to_s
        # => "foobar"
        # instead of the expected
        # irb(main):001:0> {:foo => :bar}.to_s
        # => "{:foo=>:bar}"
        # Hence checking for the class instead of the actual value.
        it "resource_name in prepared_run_data is a string" do
          @first_update_report["name"].class.should == String
        end

        it "resource_id in prepared_run_data is a string" do
          @first_update_report["id"].class.should == String
        end
      end
    end

    shared_examples_for "a successful client run" do
      before do
        # TODO: add inputs to generate expected output.

        # expected_data = {
        #    "action" : "end",
        #    "resources" : [
        #       {
        #         "type" : "file",
        #         "id" : "/etc/passwd",
        #         "name" : "User Defined Resource Block Name",
        #         "duration" : "1200",
        #         "result" : "modified",
        #         "before" : {
        #              "state" : "exists",
        #              "group" : "root",
        #              "owner" : "root",
        #              "checksum" : "xyz"
        #         },
        #         "after" : {
        #              "state" : "modified",
        #              "group" : "root",
        #              "owner" : "root",
        #              "checksum" : "abc"
        #         },
        #         "delta" : ""
        #      },
        #      {...}
        #     ],
        #    "status" : "success"
        #    "data" : ""
        # }
        @resource_reporter.resource_action_start(new_resource, :create)
        @resource_reporter.resource_current_state_loaded(new_resource, :create, current_resource)
        @resource_reporter.resource_updated(new_resource, :create)
        @resource_reporter.resource_completed(new_resource)
        @run_status.stop_clock
        @report = @resource_reporter.prepare_run_data
        @first_update_report = @report["resources"].first
      end

      it "includes the run's status" do
        @report.should have_key("status")
      end

      it "includes a list of updated resources" do
        @report.should have_key("resources")
      end

      it "includes an updated resource's type" do
        @first_update_report.should have_key("type")
      end

      it "includes an updated resource's initial state" do
        @first_update_report["before"].should == current_resource.state
      end

      it "includes an updated resource's final state" do
        @first_update_report["after"].should == new_resource.state
      end

      it "includes the resource's name" do
        @first_update_report["name"].should == new_resource.name
      end

      it "includes the resource's id attribute" do
        @first_update_report["id"].should == new_resource.identity
      end

      it "includes the elapsed time for the resource to converge" do
        # TODO: API takes integer number of milliseconds as a string. This
        # should be an int.
        @first_update_report.should have_key("duration")
        @first_update_report["duration"].to_i.should be_within(100).of(0)
      end

      it "includes the action executed by the resource" do
        # TODO: rename as "action"
        @first_update_report["result"].should == "create"
      end

      it "includes the cookbook name of the resource" do
        @first_update_report.should have_key("cookbook_name")
        @first_update_report["cookbook_name"].should == @cookbook_name
      end

      it "includes the cookbook version of the resource" do
        @first_update_report.should have_key("cookbook_version")
        @first_update_report["cookbook_version"].should == "1.2.3"
      end

      it "includes the total resource count" do
        @report.should have_key("total_res_count")
        @report["total_res_count"].should == "1"
      end

      it "includes the data hash" do
        @report.should have_key("data")
        @report["data"].should == {}
      end

      it "includes the run_list" do
        @report.should have_key("run_list")
        @report["run_list"].should == @run_status.node.run_list.to_json
      end

      it "includes the end_time" do
        @report.should have_key("end_time")
        @report["end_time"].should == @run_status.end_time.to_s
      end

    end

    context "when the resource is a File" do
      let(:new_resource) { @new_resource }
      let(:current_resource) { @current_resource }

      it_should_behave_like "a successful client run"
    end

    context "when the resource is a RegistryKey with binary data" do
      let(:new_resource) do
        resource = Chef::Resource::RegistryKey.new('Wubba\Lubba\Dub\Dubs')
        resource.values([ { :name => 'rick', :type => :binary, :data => 255.chr * 1 } ])
        resource.stub(:cookbook_name).and_return(@cookbook_name)
        resource.stub(:cookbook_version).and_return(@cookbook_version)
        resource
      end

      let(:current_resource) do
        resource = Chef::Resource::RegistryKey.new('Wubba\Lubba\Dub\Dubs')
        resource.values([ { :name => 'rick', :type => :binary, :data => 255.chr * 1 } ])
        resource
      end

      it_should_behave_like "a successful client run"
    end

    context "for an unsuccessful run" do

      before do
        @backtrace = ["foo.rb:1 in `foo!'","bar.rb:2 in `bar!","'baz.rb:3 in `baz!'"]
        @node = Chef::Node.new
        @node.name("spitfire")
        @exception = ArgumentError.new
        @exception.stub(:inspect).and_return("Net::HTTPServerException")
        @exception.stub(:message).and_return("Object not found")
        @exception.stub(:backtrace).and_return(@backtrace)
        @resource_reporter.run_list_expand_failed(@node, @exception)
        @resource_reporter.run_failed(@exception)
        @report = @resource_reporter.prepare_run_data
      end

      it "includes the exception type in the event data" do
        @report.should have_key("data")
        @report["data"]["exception"].should have_key("class")
        @report["data"]["exception"]["class"].should == "Net::HTTPServerException"
      end

      it "includes the exception message in the event data" do
        @report["data"]["exception"].should have_key("message")
        @report["data"]["exception"]["message"].should == "Object not found"
      end

      it "includes the exception trace in the event data" do
        @report["data"]["exception"].should have_key("backtrace")
        @report["data"]["exception"]["backtrace"].should == @backtrace.to_json
      end

      it "includes the error inspector output in the event data" do
        @report["data"]["exception"].should have_key("description")
        @report["data"]["exception"]["description"].should include({"title"=>"Error expanding the run_list:", "sections"=>[{"Unexpected Error:" => "ArgumentError: Object not found"}]})
      end

    end

    context "when new_resource does not have a cookbook_name" do
      before do
        @bad_resource = Chef::Resource::File.new("/tmp/a-file.txt")
        @bad_resource.cookbook_name = nil

        @resource_reporter.resource_action_start(@bad_resource, :create)
        @resource_reporter.resource_current_state_loaded(@bad_resource, :create, @current_resource)
        @resource_reporter.resource_updated(@bad_resource, :create)
        @resource_reporter.resource_completed(@bad_resource)
        @run_status.stop_clock
        @report = @resource_reporter.prepare_run_data
        @first_update_report = @report["resources"].first
      end

      it "includes an updated resource's initial state" do
        @first_update_report["before"].should == @current_resource.state
      end

      it "includes an updated resource's final state" do
        @first_update_report["after"].should == @new_resource.state
      end

      it "includes the resource's name" do
        @first_update_report["name"].should == @new_resource.name
      end

      it "includes the resource's id attribute" do
        @first_update_report["id"].should == @new_resource.identity
      end

      it "includes the elapsed time for the resource to converge" do
        # TODO: API takes integer number of milliseconds as a string. This
        # should be an int.
        @first_update_report.should have_key("duration")
        @first_update_report["duration"].to_i.should be_within(100).of(0)
      end

      it "includes the action executed by the resource" do
        # TODO: rename as "action"
        @first_update_report["result"].should == "create"
      end

      it "does not include a cookbook name for the resource" do
        @first_update_report.should_not have_key("cookbook_name")
      end

      it "does not include a cookbook version for the resource" do
        @first_update_report.should_not have_key("cookbook_version")
      end
    end

    context "when including a resource that overrides Resource#state" do
      before do
        @current_state_resource = Chef::Resource::WithState.new("Stateful", @run_context)
        @current_state_resource.state = nil

        @new_state_resource = Chef::Resource::WithState.new("Stateful", @run_context)
        @new_state_resource.state = "Running"
        @resource_reporter.resource_action_start(@new_state_resource, :create)
        @resource_reporter.resource_current_state_loaded(@new_state_resource, :create, @current_state_resource)
        @resource_reporter.resource_updated(@new_state_resource, :create)
        @resource_reporter.resource_completed(@new_state_resource)
        @run_status.stop_clock
        @report = @resource_reporter.prepare_run_data
        @first_update_report = @report["resources"].first
      end

      it "sets before to {} instead of nil" do
        @first_update_report.should have_key("before")
        @first_update_report['before'].should eq({})
      end

      it "sets after to {} instead of 'Running'" do
        @first_update_report.should have_key("after")
        @first_update_report['after'].should eq({})
      end
    end

  end

  describe "when updating resource history on the server" do
    before do
      @resource_reporter.run_started(@run_status)
      @run_status.start_clock
    end

    context "when the server does not support storing resource history" do
      before do
        # 404 getting the run_id
        @response = Net::HTTPNotFound.new("a response body", "404", "Not Found")
        @error = Net::HTTPServerException.new("404 message", @response)
        @rest_client.should_receive(:post_rest).
          with("reports/nodes/spitfire/runs", {:action => :start, :run_id => @run_id,
                                               :start_time => @start_time.to_s},
               {'X-Ops-Reporting-Protocol-Version' => Chef::ResourceReporter::PROTOCOL_VERSION}).
          and_raise(@error)
      end

      it "assumes the feature is not enabled" do
        @resource_reporter.run_started(@run_status)
        @resource_reporter.reporting_enabled?.should be_false
      end

      it "does not send a resource report to the server" do
        @resource_reporter.run_started(@run_status)
        @rest_client.should_not_receive(:post_rest)
        @resource_reporter.run_completed(@node)
      end

      it "prints an error about the 404" do
        Chef::Log.should_receive(:debug).with(/404/)
        @resource_reporter.run_started(@run_status)
      end

    end

    context "when the server returns a 500 to the client" do
      before do
        # 500 getting the run_id
        @response = Net::HTTPInternalServerError.new("a response body", "500", "Internal Server Error")
        @error = Net::HTTPServerException.new("500 message", @response)
        @rest_client.should_receive(:post_rest).
          with("reports/nodes/spitfire/runs", {:action => :start, :run_id => @run_id, :start_time => @start_time.to_s},
               {'X-Ops-Reporting-Protocol-Version' => Chef::ResourceReporter::PROTOCOL_VERSION}).
          and_raise(@error)
      end

      it "assumes the feature is not enabled" do
        @resource_reporter.run_started(@run_status)
        @resource_reporter.reporting_enabled?.should be_false
      end

      it "does not send a resource report to the server" do
        @resource_reporter.run_started(@run_status)
        @rest_client.should_not_receive(:post_rest)
        @resource_reporter.run_completed(@node)
      end

      it "prints an error about the error" do
        Chef::Log.should_receive(:info).with(/500/)
        @resource_reporter.run_started(@run_status)
      end
    end

    context "when the server returns a 500 to the client and enable_reporting_url_fatals is true" do
      before do
        @enable_reporting_url_fatals = Chef::Config[:enable_reporting_url_fatals]
        Chef::Config[:enable_reporting_url_fatals] = true
        # 500 getting the run_id
        @response = Net::HTTPInternalServerError.new("a response body", "500", "Internal Server Error")
        @error = Net::HTTPServerException.new("500 message", @response)
        @rest_client.should_receive(:post_rest).
          with("reports/nodes/spitfire/runs", {:action => :start, :run_id => @run_id, :start_time => @start_time.to_s},
               {'X-Ops-Reporting-Protocol-Version' => Chef::ResourceReporter::PROTOCOL_VERSION}).
          and_raise(@error)
      end

      after do
        Chef::Config[:enable_reporting_url_fatals] = @enable_reporting_url_fatals
      end

      it "fails the run and prints an message about the error" do
        Chef::Log.should_receive(:error).with(/500/)
        lambda {
          @resource_reporter.run_started(@run_status)
        }.should raise_error(Net::HTTPServerException)
      end
    end

    context "after creating the run history document" do
      before do
        response = {"uri"=>"https://example.com/reports/nodes/spitfire/runs/@run_id"}
        @rest_client.should_receive(:post_rest).
          with("reports/nodes/spitfire/runs", {:action => :start, :run_id => @run_id, :start_time => @start_time.to_s},
               {'X-Ops-Reporting-Protocol-Version' => Chef::ResourceReporter::PROTOCOL_VERSION}).
          and_return(response)
        @resource_reporter.run_started(@run_status)
      end

      it "creates a run document on the server at the start of the run" do
        @resource_reporter.run_id.should == @run_id
      end

      it "updates the run document with resource updates at the end of the run" do
        # update some resources...
        @resource_reporter.resource_action_start(@new_resource, :create)
        @resource_reporter.resource_current_state_loaded(@new_resource, :create, @current_resource)
        @resource_reporter.resource_updated(@new_resource, :create)

        @resource_reporter.stub(:end_time).and_return(@end_time)
        @expected_data = @resource_reporter.prepare_run_data

        post_url = "https://chef_server/example_url"
        response = {"result"=>"ok"}

        @rest_client.should_receive(:create_url).
          with("reports/nodes/spitfire/runs/#{@run_id}").
          ordered.
          and_return(post_url)
        @rest_client.should_receive(:raw_http_request).ordered do |method, url, headers, data|
          method.should eq(:POST)
          url.should eq(post_url)
          headers.should eq({'Content-Encoding' => 'gzip',
                             'X-Ops-Reporting-Protocol-Version' => Chef::ResourceReporter::PROTOCOL_VERSION
          })
          data_stream = Zlib::GzipReader.new(StringIO.new(data))
          data = data_stream.read
          data.should eq(@expected_data.to_json)
          response
        end

        @resource_reporter.run_completed(@node)
      end
    end
  end
end


text:
package org.apache.camel.component.jetty9;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.camel.RuntimeCamelException;
import org.apache.camel.component.jetty.CamelHttpClient;
import org.apache.camel.component.jetty.JettyHttpComponent;
import org.apache.camel.component.jetty.JettyHttpEndpoint;
import org.apache.camel.spi.annotations.Component;
import org.apache.camel.support.IntrospectionSupport;
import org.eclipse.jetty.client.HttpClientTransport;
import org.eclipse.jetty.server.AbstractConnector;
import org.eclipse.jetty.server.ConnectionFactory;
import org.eclipse.jetty.server.ForwardedRequestCustomizer;
import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.SslConnectionFactory;
import org.eclipse.jetty.util.ssl.SslContextFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component("jetty")
public class JettyHttpComponent9 extends JettyHttpComponent {

    private static final Logger LOG = LoggerFactory.getLogger(JettyHttpComponent9.class);

    protected CamelHttpClient createCamelHttpClient(HttpClientTransport transport, SslContextFactory sslContextFactory) {
        return new CamelHttpClient9(transport, sslContextFactory);
    }

    protected JettyHttpEndpoint createEndpoint(URI endpointUri, URI httpUri) throws URISyntaxException {
        return new JettyHttpEndpoint9(this, endpointUri.toString(), httpUri);
    }

    protected AbstractConnector createConnectorJettyInternal(Server server,
                                                      JettyHttpEndpoint endpoint,
                                                      SslContextFactory sslcf) {
        try {
            String host = endpoint.getHttpUri().getHost();
            int port = endpoint.getPort();
            org.eclipse.jetty.server.HttpConfiguration httpConfig = new org.eclipse.jetty.server.HttpConfiguration();
            httpConfig.setSendServerVersion(endpoint.isSendServerVersion());
            httpConfig.setSendDateHeader(endpoint.isSendDateHeader());

            if (requestBufferSize != null) {
                // Does not work
                //httpConfig.setRequestBufferSize(requestBufferSize);
            }
            if (requestHeaderSize != null) {
                httpConfig.setRequestHeaderSize(requestHeaderSize);
            }
            if (responseBufferSize != null) {
                httpConfig.setOutputBufferSize(responseBufferSize);
            }
            if (responseHeaderSize != null) {
                httpConfig.setResponseHeaderSize(responseHeaderSize);
            }
            if (useXForwardedForHeader) {
                httpConfig.addCustomizer(new ForwardedRequestCustomizer());
            }
            HttpConnectionFactory httpFactory = new org.eclipse.jetty.server.HttpConnectionFactory(httpConfig);

            ArrayList<ConnectionFactory> connectionFactories = new ArrayList<>();
            ServerConnector result = new org.eclipse.jetty.server.ServerConnector(server);
            if (sslcf != null) {
                httpConfig.addCustomizer(new org.eclipse.jetty.server.SecureRequestCustomizer());
                SslConnectionFactory scf = new org.eclipse.jetty.server.SslConnectionFactory(sslcf, "HTTP/1.1");
                connectionFactories.add(scf);
                // The protocol name can be "SSL" or "SSL-HTTP/1.1" depending on the version of Jetty
                result.setDefaultProtocol(scf.getProtocol());
            }
            connectionFactories.add(httpFactory);
            for (ConnectionFactory cf : connectionFactories) {
                result.addConnectionFactory(cf);
            }
            result.setPort(port);
            if (host != null) {
                result.setHost(host);
            }
            if (sslcf != null) {
                if (getSslSocketConnectorProperties() != null && "https".equals(endpoint.getProtocol())) {
                    // must copy the map otherwise it will be deleted
                    Map<String, Object> properties = new HashMap<>(getSslSocketConnectorProperties());
                    IntrospectionSupport.setProperties(sslcf, properties);
                    if (properties.size() > 0) {
                        throw new IllegalArgumentException("There are " + properties.size()
                            + " parameters that couldn't be set on the SocketConnector."
                            + " Check the uri if the parameters are spelt correctly and that they are properties of the SelectChannelConnector."
                            + " Unknown parameters=[" + properties + "]");
                    }
                }

                LOG.info("Connector on port: {} is using includeCipherSuites: {} excludeCipherSuites: {} includeProtocols: {} excludeProtocols: {}",
                    port, sslcf.getIncludeCipherSuites(), sslcf.getExcludeCipherSuites(), sslcf.getIncludeProtocols(), sslcf.getExcludeProtocols());
            }

            return result;
        } catch (Exception e) {
            throw RuntimeCamelException.wrapRuntimeCamelException(e);
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
'use strict'

const prettier = require('prettier')
const glob = require('glob')
const fs = require('fs')
const globPattern =
  '{app/{src,test}/**/*.{ts,tsx,js},app/webpack.*.js,script/!(*.ps1|*.bat|setup-macos-keychain)}'
const prettierOptions = {
  parser: 'typescript',
  singleQuote: true,
  trailingComma: 'es5',
  semi: false,
  printWidth: 80,
}

glob(globPattern, (err, matches) => {
  if (err) {
    console.error(err)
    process.exit(1)
  }

  const uglyFiles = []
  const matchCount = matches.length

  for (const match of matches) {
    const fileContents = fs.readFileSync(match, 'utf8')
    const isPretty = prettier.check(fileContents, prettierOptions)

    if (!isPretty) {
      uglyFiles.push(match)
    }
  }

  if (uglyFiles.length === 0) {
    console.log('This is some pretty code')
  } else {
    console.log(
      `${uglyFiles.length} out of ${matchCount} code files are ugly. Please run 'npm run prettify' to make the following files pretty:`
    )

    for (const file of uglyFiles) {
      console.log(`\t${file}`)
    }

    process.exit(1)
  }
})


text:
package com.leanstacks.ws.model;

import java.io.Serializable;
import java.time.Instant;

import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.validation.constraints.NotNull;

/**
 * The parent class for all reference entities (i.e. reference data as opposed to transactional data).
 *
 * @see com.leanstacks.ws.model.TransactionalEntity
 *
 * @author Matt Warman
 */
@MappedSuperclass
public class ReferenceEntity implements Serializable {

    /**
     * The default serial version UID.
     */
    private static final long serialVersionUID = 1L;

    /**
     * The primary key identifier.
     */
    @Id
    private Long id;

    /**
     * The unique code value, sometimes used for external reference.
     */
    @NotNull
    private String code;

    /**
     * A brief description of the entity.
     */
    @NotNull
    private String label;

    /**
     * The ordinal value facilitates sorting the entities.
     */
    @NotNull
    private Integer ordinal;

    /**
     * The timestamp at which the entity's values may be applied or used by the system.
     */
    @NotNull
    private Instant effectiveAt;

    /**
     * The timestamp at which the entity's values cease to be used by the system. If null the entity is not
     * expired.
     */
    private Instant expiresAt;

    /**
     * The timestamp when this entity instance was created.
     */
    @NotNull
    private Instant createdAt;

    public Long getId() {
        return id;
    }

    public void setId(final Long id) {
        this.id = id;
    }

    public String getCode() {
        return code;
    }

    public void setCode(final String code) {
        this.code = code;
    }

    public String getLabel() {
        return label;
    }

    public void setLabel(final String label) {
        this.label = label;
    }

    public Integer getOrdinal() {
        return ordinal;
    }

    public void setOrdinal(final Integer ordinal) {
        this.ordinal = ordinal;
    }

    public Instant getEffectiveAt() {
        return effectiveAt;
    }

    public void setEffectiveAt(final Instant effectiveAt) {
        this.effectiveAt = effectiveAt;
    }

    public Instant getExpiresAt() {
        return expiresAt;
    }

    public void setExpiresAt(final Instant expiresAt) {
        this.expiresAt = expiresAt;
    }

    public Instant getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(final Instant createdAt) {
        this.createdAt = createdAt;
    }

}


text:
import Ember from 'ember';
import ApplicationSerializer from 'paypal/serializers/application';

export default ApplicationSerializer.extend({
    /**
     * To tweak the data your sending to the paypal.
     * @param record
     * @param options
     * @returns {*}
     */
    serialize: function(record) {
        Ember.Logger.debug('payment serialize invoked!');
        var serializedPayload = {
            "intent": record.get('intent'),
            "payer":{
                "payment_method": record.get('paymentMethod'),
                "funding_instruments":[
                    {
                        "credit_card":{
                            "number": record.get('number'),
                            "type": record.get('type'),
                            "expire_month": record.get('expireMonth'),
                            "expire_year": record.get('expireYear'),
                            "cvv2": record.get('cvv2'),
                            "first_name": record.get('firstName'),
                            "last_name": record.get('lastName'),
                            "billing_address":{
                                "line1": record.get('address'),
                                "city": record.get('city'),
                                "state": record.get('state'),
                                "postal_code": record.get('postalCode'),
                                "country_code": record.get('countryCode')
                            }
                        }
                    }
                ]
            },
            "transactions":[
                {
                    "amount":{
                        "total": record.get('total'),
                        "currency": record.get('currency'),
                        "details":{
                            "subtotal": record.get('subtotal'),
                            "tax": record.get('tax'),
                            "shipping": record.get('shipping')
                        }
                    },
                    "description": record.get('description')
                }
            ]
        };
        return serializedPayload;
    },

    normalizePayload: function(payload) {
        Ember.Logger.debug('authorization normalizePayload invoked!');
        Ember.Logger.debug('  payload = ' + JSON.stringify(payload));
        var normalizedPayload = {
            authorization: {
                id: payload.id,
                createTime: payload.create_time,
                updateTime: payload.update_time,
                status: payload.state,
                intent: payload.intent,
                paymentMethod: payload.payer.payment_method,
                number: payload.payer.funding_instruments[0].credit_card.number,
                type: payload.payer.funding_instruments[0].credit_card.type,
                expireMonth: payload.payer.funding_instruments[0].credit_card.expire_month,
                expireYear: payload.payer.funding_instruments[0].credit_card.expire_year,
                firstName: payload.payer.funding_instruments[0].credit_card.first_name,
                lastName: payload.payer.funding_instruments[0].credit_card.last_name,
                address: payload.payer.funding_instruments[0].credit_card.billing_address.line1,
                city: payload.payer.funding_instruments[0].credit_card.billing_address.city,
                state: payload.payer.funding_instruments[0].credit_card.billing_address.state,
                postalCode: payload.payer.funding_instruments[0].credit_card.billing_address.postal_code,
                countryCode: payload.payer.funding_instruments[0].credit_card.billing_address.country_code,

                total: payload.transactions[0].amount.total,
                currency: payload.transactions[0].amount.currency,
                subtotal: payload.transactions[0].amount.details.subtotal,
                tax: payload.transactions[0].amount.details.tax,
                shipping: payload.transactions[0].amount.details.shipping,
                description: payload.transactions[0].description,
                authorizationId: payload.transactions[0].related_resources[0].authorization.id
            }
        };
        //Ember.Logger.debug('  normalizedPayload = ' + JSON.stringify(normalizedPayload));
        return this._super(normalizedPayload);
    }
});


text:
package ar.com.larreta.school.business.courses;

import ar.com.larreta.stepper.Step;

public interface CoursesCreateBusiness extends Step {
	public static final String BUSINESS_NAME = "CoursesCreateBusiness";
}


text:
#include "nativeactivity.h"

#include <jni.h>
#include <errno.h>

#include <EGL/egl.h>
#include <GLES/gl.h>

#include <android/sensor.h>
#include <android/log.h>
#include <android_native_app_glue.h>
#include <android/configuration.h>

#include <pthread.h>
#include <chrono>

#include "CCDirector.h"
#include "CCApplication.h"
#include "CCEventType.h"
#include "CCFileUtilsAndroid.h"
#include "jni/JniHelper.h"

#include "CCEGLView.h"
#include "CCDrawingPrimitives.h"
#include "CCShaderCache.h"
#include "CCTextureCache.h"
#include "CCEventDispatcher.h"
#include "CCEventAcceleration.h"
#include "CCEventKeyboard.h"
#include "CCEventCustom.h"

#include "jni/Java_org_cocos2dx_lib_Cocos2dxHelper.h"

#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "cocos2dx/nativeactivity.cpp", __VA_ARGS__))
#define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, "cocos2dx/nativeactivity.cpp", __VA_ARGS__))
#define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, "cocos2dx/nativeactivity.cpp", __VA_ARGS__))

#define LOG_RENDER_DEBUG(...)
// #define LOG_RENDER_DEBUG(...)  ((void)__android_log_print(ANDROID_LOG_INFO, "cocos2dx/nativeactivity.cpp", __VA_ARGS__))

#define LOG_EVENTS_DEBUG(...)
// #define LOG_EVENTS_DEBUG(...)  ((void)__android_log_print(ANDROID_LOG_INFO, "cocos2dx/nativeactivity.cpp", __VA_ARGS__))

/* For debug builds, always enable the debug traces in this library */
#ifndef NDEBUG
#  define LOGV(...)  ((void)__android_log_print(ANDROID_LOG_VERBOSE, "cocos2dx/nativeactivity.cpp", __VA_ARGS__))
#else
#  define LOGV(...)  ((void)0)
#endif

void cocos_android_app_init(struct android_app* app);

/**
 * Our saved state data.
 */
struct saved_state {
    float angle;
    int32_t x;
    int32_t y;
};

/**
 * Shared state for our app.
 */
struct engine {
    struct android_app* app;

    ASensorManager* sensorManager;
    const ASensor* accelerometerSensor;
    ASensorEventQueue* sensorEventQueue;

    int animating;
    EGLDisplay display;
    EGLSurface surface;
    EGLContext context;
    int32_t width;
    int32_t height;
    struct saved_state state;
};

static bool isContentRectChanged = false;
static std::chrono::steady_clock::time_point timeRectChanged;

static struct engine engine;

static char* editboxText = NULL;
extern EditTextCallback s_pfEditTextCallback;
extern void* s_ctx;

extern "C" {
	JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxHelper_nativeSetEditTextDialogResult(JNIEnv * env, jobject obj, jbyteArray text) {
		jsize  size = env->GetArrayLength(text);
		pthread_mutex_lock(&(engine.app->mutex));
		if (size > 0) {

			jbyte * data = (jbyte*)env->GetByteArrayElements(text, 0);
			char* pBuf = (char*)malloc(size+1);
			if (pBuf != NULL) {
				memcpy(pBuf, data, size);
				pBuf[size] = '\0';
				editboxText = pBuf;
			}
			env->ReleaseByteArrayElements(text, data, 0);

		} else {
			char* pBuf = (char*)malloc(1);
			pBuf[0] = '\0';
			editboxText = pBuf;
		}
		pthread_cond_broadcast(&engine.app->cond);
		pthread_mutex_unlock(&(engine.app->mutex));
	}
}

typedef struct cocos_dimensions {
    int w;
    int h;
} cocos_dimensions;

static void cocos_init(cocos_dimensions d, struct android_app* app) {
    LOGI("cocos_init(...)");
    pthread_t thisthread = pthread_self();
    LOGI("pthread_self() = %X", thisthread);

    cocos2d::FileUtilsAndroid::setassetmanager(app->activity->assetManager);

    if (!cocos2d::Director::getInstance()->getOpenGLView())
    {
        cocos2d::EGLView *view = cocos2d::EGLView::getInstance();
        view->setFrameSize(d.w, d.h);

        cocos_android_app_init(app);

        cocos2d::Application::getInstance()->run();
    }
    else
    {
        cocos2d::GL::invalidateStateCache();
        cocos2d::ShaderCache::getInstance()->reloadDefaultShaders();
        cocos2d::DrawPrimitives::init();
        cocos2d::VolatileTextureMgr::reloadAllTextures();
        cocos2d::EventCustom foregroundEvent(EVENT_COME_TO_FOREGROUND);
        cocos2d::Director::getInstance()->getEventDispatcher()->dispatchEvent(&foregroundEvent);
        cocos2d::Director::getInstance()->setGLDefaultValues();
    }
}

/**
 * Initialize an EGL context for the current display.
 */
static cocos_dimensions engine_init_display(struct engine* engine) {
    cocos_dimensions r;
    r.w = -1;
    r.h = -1;

    // initialize OpenGL ES and EGL

    /*
     * Here specify the attributes of the desired configuration.
     * Below, we select an EGLConfig with at least 8 bits per color
     * component compatible with on-screen windows
     */
    const EGLint attribs[] = {
            EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
            EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
            EGL_BLUE_SIZE, 5,
            EGL_GREEN_SIZE, 6,
            EGL_RED_SIZE, 5,
            EGL_DEPTH_SIZE, 16,
            EGL_STENCIL_SIZE, 8,
            EGL_NONE
    };
    EGLint w, h, dummy, format;
    EGLint numConfigs;
    EGLConfig config;
    EGLSurface surface;
    EGLContext context;

    EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);

    eglInitialize(display, 0, 0);

    /* Here, the application chooses the configuration it desires. In this
     * sample, we have a very simplified selection process, where we pick
     * the first EGLConfig that matches our criteria */
    eglChooseConfig(display, attribs, &config, 1, &numConfigs);

    /* EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is
     * guaranteed to be accepted by ANativeWindow_setBuffersGeometry().
     * As soon as we picked a EGLConfig, we can safely reconfigure the
     * ANativeWindow buffers to match, using EGL_NATIVE_VISUAL_ID. */
    eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format);

    ANativeWindow_setBuffersGeometry(engine->app->window, 0, 0, format);

    surface = eglCreateWindowSurface(display, config, engine->app->window, NULL);

    const EGLint eglContextAttrs[] =
    {
        EGL_CONTEXT_CLIENT_VERSION, 2,
        EGL_NONE
    };

    context = eglCreateContext(display, config, NULL, eglContextAttrs);

    if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE) {
        LOGW("Unable to eglMakeCurrent");
        return r;
    }

    eglQuerySurface(display, surface, EGL_WIDTH, &w);
    eglQuerySurface(display, surface, EGL_HEIGHT, &h);

    engine->display = display;
    engine->context = context;
    engine->surface = surface;
    engine->width = w;
    engine->height = h;
    engine->state.angle = 0;

    r.w = w;
    r.h = h;

    return r;
}

/**
 * Invoke the dispatching of the next bunch of Runnables in the Java-Land
 */
static bool s_methodInitialized = false;
static void dispatch_pending_runnables() {
    static cocos2d::JniMethodInfo info;

    if (!s_methodInitialized) {
        s_methodInitialized = cocos2d::JniHelper::getStaticMethodInfo(
            info,
            "org/cocos2dx/lib/Cocos2dxHelper",
            "dispatchPendingRunnables",
            "()V"
        );

        if (!s_methodInitialized) {
            LOGW("Unable to dispatch pending Runnables!");
            return;
        }
    }

    info.env->CallStaticVoidMethod(info.classID, info.methodID);
}

/**
 * Just the current frame in the display.
 */
static void engine_draw_frame(struct engine* engine) {
    LOG_RENDER_DEBUG("engine_draw_frame(...)");
    pthread_t thisthread = pthread_self();
    LOG_RENDER_DEBUG("pthread_self() = %X", thisthread);

    if (engine->display == NULL) {
        // No display.
        LOGW("engine_draw_frame : No display.");
        return;
    }

    dispatch_pending_runnables();
    cocos2d::Director::getInstance()->mainLoop();
    LOG_RENDER_DEBUG("engine_draw_frame : just called cocos' mainLoop()");

    /* // Just fill the screen with a color. */
    /* glClearColor(((float)engine->state.x)/engine->width, engine->state.angle, */
    /*         ((float)engine->state.y)/engine->height, 1); */
    /* glClear(GL_COLOR_BUFFER_BIT); */

	if (s_pfEditTextCallback && editboxText)
	{
		s_pfEditTextCallback(editboxText, s_ctx);
		free(editboxText);
		editboxText = NULL;
	}

    eglSwapBuffers(engine->display, engine->surface);
}

/**
 * Tear down the EGL context currently associated with the display.
 */
static void engine_term_display(struct engine* engine) {
    if (engine->display != EGL_NO_DISPLAY) {
        eglMakeCurrent(engine->display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
        if (engine->context != EGL_NO_CONTEXT) {
            eglDestroyContext(engine->display, engine->context);
        }
        if (engine->surface != EGL_NO_SURFACE) {
            eglDestroySurface(engine->display, engine->surface);
        }
        eglTerminate(engine->display);
    }
    engine->animating = 0;
    engine->display = EGL_NO_DISPLAY;
    engine->context = EGL_NO_CONTEXT;
    engine->surface = EGL_NO_SURFACE;
}

/*
 * Get X, Y positions and ID's for all pointers
 */
static void getTouchPos(AInputEvent *event, int ids[], float xs[], float ys[]) {
    int pointerCount = AMotionEvent_getPointerCount(event);
    for(int i = 0; i < pointerCount; ++i) {
        ids[i] = AMotionEvent_getPointerId(event, i);
        xs[i] = AMotionEvent_getX(event, i);
        ys[i] = AMotionEvent_getY(event, i);
    }
}

/*
 * Handle Touch Inputs
 */
static int32_t handle_touch_input(AInputEvent *event) {

    pthread_t thisthread = pthread_self();
    LOG_EVENTS_DEBUG("handle_touch_input(%X), pthread_self() = %X", event, thisthread);

    switch(AMotionEvent_getAction(event) &
           AMOTION_EVENT_ACTION_MASK) {

    case AMOTION_EVENT_ACTION_DOWN:
        {
            LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_DOWN");
            int pointerId = AMotionEvent_getPointerId(event, 0);
            float xP = AMotionEvent_getX(event,0);
            float yP = AMotionEvent_getY(event,0);

            LOG_EVENTS_DEBUG("Event: Action DOWN x=%f y=%f pointerID=%d\n",
                 xP, yP, pointerId);
            float x = xP;
            float y = yP;

            cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesBegin(1, &pointerId, &x, &y);
            return 1;
        }
        break;

    case AMOTION_EVENT_ACTION_POINTER_DOWN:
        {
            LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_POINTER_DOWN");
            int pointerIndex = AMotionEvent_getAction(event) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
            int pointerId = AMotionEvent_getPointerId(event, pointerIndex);
            float xP = AMotionEvent_getX(event,pointerIndex);
            float yP = AMotionEvent_getY(event,pointerIndex);

            LOG_EVENTS_DEBUG("Event: Action POINTER DOWN x=%f y=%f pointerID=%d\n",
                 xP, yP, pointerId);
            float x = xP;
            float y = yP;

            cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesBegin(1, &pointerId, &x, &y);
            return 1;
        }
        break;

    case AMOTION_EVENT_ACTION_MOVE:
        {
            LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_MOVE");
            int pointerCount = AMotionEvent_getPointerCount(event);
            int ids[pointerCount];
            float xs[pointerCount], ys[pointerCount];
            getTouchPos(event, ids, xs, ys);
			cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesMove(pointerCount, ids, xs, ys);
            return 1;
        }
        break;

    case AMOTION_EVENT_ACTION_UP:
        {
            LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_UP");
            int pointerId = AMotionEvent_getPointerId(event, 0);
            float xP = AMotionEvent_getX(event,0);
            float yP = AMotionEvent_getY(event,0);
            LOG_EVENTS_DEBUG("Event: Action UP x=%f y=%f pointerID=%d\n",
                 xP, yP, pointerId);
            float x = xP;
            float y = yP;

            cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesEnd(1, &pointerId, &x, &y);
            return 1;
        }
        break;

    case AMOTION_EVENT_ACTION_POINTER_UP:
        {
            LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_POINTER_UP");
            int pointerIndex = AMotionEvent_getAction(event) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
            int pointerId = AMotionEvent_getPointerId(event, pointerIndex);
            float xP = AMotionEvent_getX(event,pointerIndex);
            float yP = AMotionEvent_getY(event,pointerIndex);
            LOG_EVENTS_DEBUG("Event: Action POINTER UP x=%f y=%f pointerID=%d\n",
                 xP, yP, pointerIndex);
            float x = xP;
            float y = yP;

            cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesEnd(1, &pointerId, &x, &y);
            return 1;
        }
        break;

    case AMOTION_EVENT_ACTION_CANCEL:
        {
            LOG_EVENTS_DEBUG("AMOTION_EVENT_ACTION_CANCEL");
            int pointerCount = AMotionEvent_getPointerCount(event);
            int ids[pointerCount];
            float xs[pointerCount], ys[pointerCount];
            getTouchPos(event, ids, xs, ys);
			cocos2d::Director::getInstance()->getOpenGLView()->handleTouchesCancel(pointerCount, ids, xs, ys);
            return 1;
        }
        break;

    default:
        LOG_EVENTS_DEBUG("handle_touch_input() default case.... NOT HANDLE");
        return 0;
        break;
    }
}

/*
* Handle Key Inputs
*/
static int32_t handle_key_input(AInputEvent *event)
{
    if (AKeyEvent_getAction(event) == AKEY_EVENT_ACTION_UP)
    {
        auto dispatcher = cocos2d::Director::getInstance()->getEventDispatcher();

        switch (AKeyEvent_getKeyCode(event))
        {
        case AKEYCODE_BACK:
            {
                cocos2d::EventKeyboard event(cocos2d::EventKeyboard::KeyCode::KEY_BACKSPACE, false);
                dispatcher->dispatchEvent(&event);
            }
            return 1;
        case AKEYCODE_MENU:
            {
                cocos2d::EventKeyboard event(cocos2d::EventKeyboard::KeyCode::KEY_MENU, false);
                dispatcher->dispatchEvent(&event);
            }
            return 1;
        default:
            break;
        }
    }
    return 0;
}

/**
 * Process the next input event.
 */
static int32_t engine_handle_input(struct android_app* app, AInputEvent* event) {

    pthread_t thisthread = pthread_self();
    LOG_EVENTS_DEBUG("engine_handle_input(%X, %X), pthread_self() = %X", app, event, thisthread);

    struct engine* engine = (struct engine*)app->userData;

    if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_MOTION) {
        engine->animating = 1;
        engine->state.x = AMotionEvent_getX(event, 0);
        engine->state.y = AMotionEvent_getY(event, 0);

        return handle_touch_input(event);
    }
	else
		return handle_key_input(event);

    return 0;
}

void enableAccelerometerJni(void) {
    LOGI("enableAccelerometerJni()");

    if (engine.accelerometerSensor != NULL) {
        ASensorEventQueue_enableSensor(engine.sensorEventQueue,
                                       engine.accelerometerSensor);

        // Set a default sample rate
        // We'd like to get 60 events per second (in us).
        ASensorEventQueue_setEventRate(engine.sensorEventQueue,
                                       engine.accelerometerSensor, (1000L/60)*1000);
    }
}

void disableAccelerometerJni(void) {
    LOGI("disableAccelerometerJni()");

    if (engine.accelerometerSensor != NULL) {
        ASensorEventQueue_disableSensor(engine.sensorEventQueue,
                                        engine.accelerometerSensor);
    }
}

void setAccelerometerIntervalJni(float interval) {
    LOGI("setAccelerometerIntervalJni(%f)", interval);
        // We'd like to get 60 events per second (in us).
        ASensorEventQueue_setEventRate(engine.sensorEventQueue,
                                       engine.accelerometerSensor, interval * 1000000L);
}

/**
 * Process the next main command.
 */
static void engine_handle_cmd(struct android_app* app, int32_t cmd) {
    struct engine* engine = (struct engine*)app->userData;
    switch (cmd) {
        case APP_CMD_SAVE_STATE:
            // The system has asked us to save our current state.  Do so.
            engine->app->savedState = malloc(sizeof(struct saved_state));
            *((struct saved_state*)engine->app->savedState) = engine->state;
            engine->app->savedStateSize = sizeof(struct saved_state);
            break;
        case APP_CMD_INIT_WINDOW:
            // The window is being shown, get it ready.
            if (engine->app->window != NULL) {
                cocos_dimensions d = engine_init_display(engine);
                if ((d.w > 0) &&
                    (d.h > 0)) {
                    cocos2d::JniHelper::setJavaVM(app->activity->vm);
                    cocos2d::JniHelper::setClassLoaderFrom(app->activity->clazz);

                    // call Cocos2dxHelper.init()
                    cocos2d::JniMethodInfo ccxhelperInit;
                    if (!cocos2d::JniHelper::getStaticMethodInfo(ccxhelperInit,
                                                                 "org/cocos2dx/lib/Cocos2dxHelper",
                                                                 "init",
                                                                 "(Landroid/app/Activity;)V")) {
                        LOGI("cocos2d::JniHelper::getStaticMethodInfo(ccxhelperInit) FAILED");
                    }
                    ccxhelperInit.env->CallStaticVoidMethod(ccxhelperInit.classID,
                                                            ccxhelperInit.methodID,
                                                            app->activity->clazz);

                    cocos_init(d, app);
                }
                engine->animating = 1;
                engine_draw_frame(engine);
            }
            break;
        case APP_CMD_TERM_WINDOW:
            // The window is being hidden or closed, clean it up.
            engine_term_display(engine);
            break;
        case APP_CMD_GAINED_FOCUS:
            if (cocos2d::Director::getInstance()->getOpenGLView()) {
                cocos2d::Application::getInstance()->applicationWillEnterForeground();
				engine->animating = 1;
            }

            break;
        case APP_CMD_LOST_FOCUS:
            {
                cocos2d::Application::getInstance()->applicationDidEnterBackground();
                cocos2d::EventCustom backgroundEvent(EVENT_COME_TO_BACKGROUND);
                cocos2d::Director::getInstance()->getEventDispatcher()->dispatchEvent(&backgroundEvent);
                // Also stop animating.
                engine->animating = 0;
                engine_draw_frame(engine);
            }
            break;
    }
}

static void onContentRectChanged(ANativeActivity* activity, const ARect* rect) {
	timeRectChanged = std::chrono::steady_clock::now();
	isContentRectChanged = true;
}

static void process_input(struct android_app* app, struct android_poll_source* source) {
    AInputEvent* event = NULL;
    int processed = 0;
    while (AInputQueue_hasEvents( app->inputQueue ) && AInputQueue_getEvent(app->inputQueue, &event) >= 0) {
        LOGV("New input event: type=%d\n", AInputEvent_getType(event));
        if (AInputQueue_preDispatchEvent(app->inputQueue, event)) {
            continue;
        }
        int32_t handled = 0;
        if (app->onInputEvent != NULL) handled = app->onInputEvent(app, event);
        AInputQueue_finishEvent(app->inputQueue, event, handled);
        processed = 1;
    }
    if (processed == 0) {
        LOGE("Failure reading next input event: %s\n", strerror(errno));
    }
}
/**
 * This is the main entry point of a native application that is using
 * android_native_app_glue.  It runs in its own thread, with its own
 * event loop for receiving input events and doing other things.
 */
void android_main(struct android_app* state) {

    // Make sure glue isn't stripped.
    app_dummy();

    memset(&engine, 0, sizeof(engine));
    state->userData = &engine;
    state->onAppCmd = engine_handle_cmd;
    state->onInputEvent = engine_handle_input;
    state->inputPollSource.process = process_input;
    engine.app = state;

    // Prepare to monitor accelerometer
    engine.sensorManager = ASensorManager_getInstance();
    engine.accelerometerSensor = ASensorManager_getDefaultSensor(engine.sensorManager,
            ASENSOR_TYPE_ACCELEROMETER);
    engine.sensorEventQueue = ASensorManager_createEventQueue(engine.sensorManager,
            state->looper, LOOPER_ID_USER, NULL, NULL);

    if (state->savedState != NULL) {
        // We are starting with a previous saved state; restore from it.
        engine.state = *(struct saved_state*)state->savedState;
    }

	// Screen size change support
	state->activity->callbacks->onContentRectChanged = onContentRectChanged;

    // loop waiting for stuff to do.

    while (1) {
        // Read all pending events.
        int ident;
        int events;
        struct android_poll_source* source;

        // If not animating, we will block forever waiting for events.
        // If animating, we loop until all events are read, then continue
        // to draw the next frame of animation.
        while ((ident=ALooper_pollAll(engine.animating ? 0 : -1, NULL, &events,
                (void**)&source)) >= 0) {

            // Process this event.
            if (source != NULL) {
                source->process(state, source);
            }

            // If a sensor has data, process it now.
            if (ident == LOOPER_ID_USER) {
                if (engine.accelerometerSensor != NULL) {
                    ASensorEvent event;
                    while (ASensorEventQueue_getEvents(engine.sensorEventQueue,
                            &event, 1) > 0) {

                        LOG_EVENTS_DEBUG("accelerometer: x=%f y=%f z=%f",
                                event.acceleration.x, event.acceleration.y,
                                event.acceleration.z);

                        AConfiguration* _currentconf = AConfiguration_new();
                        AConfiguration_fromAssetManager(_currentconf,
                                                        state->activity->assetManager);
                        static int32_t _orientation = AConfiguration_getOrientation(_currentconf);

                        if (ACONFIGURATION_ORIENTATION_LAND != _orientation) {
                            // ACONFIGURATION_ORIENTATION_ANY
                            // ACONFIGURATION_ORIENTATION_PORT
                            // ACONFIGURATION_ORIENTATION_SQUARE
                            cocos2d::Acceleration acc;
                            acc.x = -event.acceleration.x/10;
                            acc.y = -event.acceleration.y/10;
                            acc.z = event.acceleration.z/10;
                            acc.timestamp = 0;
                            cocos2d::EventAcceleration accEvent(acc);
                            auto dispatcher = cocos2d::Director::getInstance()->getEventDispatcher();
                            dispatcher->dispatchEvent(&accEvent);
                        } else {
                            // ACONFIGURATION_ORIENTATION_LAND
                            // swap x and y parameters
                            cocos2d::Acceleration acc;
                            acc.x = event.acceleration.y/10;
                            acc.y = -event.acceleration.x/10;
                            acc.z = event.acceleration.z/10;
                            acc.timestamp = 0;
                            cocos2d::EventAcceleration accEvent(acc);
                            auto dispatcher = cocos2d::Director::getInstance()->getEventDispatcher();
                            dispatcher->dispatchEvent(&accEvent);
                        }
                    }
                }
            }

            // Check if we are exiting.
            if (state->destroyRequested != 0) {
                engine_term_display(&engine);

                memset(&engine, 0, sizeof(engine));
                s_methodInitialized = false;
                return;
            }
        }

        if (engine.animating) {
            // Done with events; draw next animation frame.
            engine.state.angle += .01f;
            if (engine.state.angle > 1) {
                engine.state.angle = 0;
            }

            // Drawing is throttled to the screen update rate, so there
            // is no need to do timing here.
            LOG_RENDER_DEBUG("android_main : engine.animating");
            engine_draw_frame(&engine);
        } else {
            LOG_RENDER_DEBUG("android_main : !engine.animating");
        }

		// Check if screen size changed
		if (isContentRectChanged) {
			std::chrono::duration<int, std::milli> duration(
					std::chrono::duration_cast<std::chrono::duration<int, std::milli>>(std::chrono::steady_clock::now() - timeRectChanged));

			// Wait about 30 ms to get new width and height. Without waiting we can get old values sometime
			if (duration.count() > 30) {
				isContentRectChanged = false;

				int32_t newWidth = ANativeWindow_getWidth(engine.app->window);
				int32_t newHeight = ANativeWindow_getHeight(engine.app->window);
				cocos2d::Application::getInstance()->applicationScreenSizeChanged(newWidth, newHeight);
			}
		}
    }
}


text:
using Machine.Specifications;
using PlainElastic.Net.Serialization;
using PlainElastic.Net.Utils;

namespace PlainElastic.Net.Tests.Serialization
{
    [Subject(typeof(JsonNetSerializer))]
    class When_range_facets_result_deserialized
    {
        #region Range Facets Json Result
        private static readonly string rangeFacetsJsonResult =
@"{
    'took': 16,
    'timed_out': false,
    '_shards': {
        'total': 5,
        'successful': 5,
        'failed': 0
    },
    'hits': {
        'total': 3000,
        'max_score': 1.0,
        'hits': [ ]
    },
    'facets': {
        'quantity': {
            '_type': 'range',
            'ranges': [
                {
                    'to': 50.0,
                    'count': 1000,
                    'min': 0.0,
                    'max': 10.0,
                    'total_count': 1100,
                    'total': 1200.0,
                    'mean': 15.5
                },
                {
                    'from': 20.0,
                    'to': 70.0,
                    'count': 2000,
                    'min': 20.0,
                    'max': 70.0,
                    'total_count': 2100,
                    'total': 50000.0,
                    'mean': 30.5
                }
            ]
        }
    }
}".AltQuote();
        #endregion

        Establish context = () =>
            jsonSerializer = new JsonNetSerializer();

        Because of = () =>
            result = jsonSerializer.ToSearchResult<object>(rangeFacetsJsonResult);

        It should_contain_correct_hits_count = () =>
            result.hits.total.ShouldEqual(3000);

        It should_contain_quantity_facet_with_filter_type = () =>
            result.facets["quantity"]._type.ShouldEqual("range");

        It should_deserialize_quantity_facet_to_RanfgeFacetResults_type = () =>
            result.facets["quantity"].ShouldBeOfType<RangeFacetResult>();

        It should_contain_quantity_facet_with_correct_from_value = () =>
            result.facets["quantity"].As<RangeFacetResult>().ranges[1].from.ShouldEqual(20);

        It should_contain_quantity_facet_with_correct_to_value = () =>
            result.facets["quantity"].As<RangeFacetResult>().ranges[1].to.ShouldEqual(70);

        It should_contain_quantity_facet_with_correct_count = () =>
            result.facets["quantity"].As<RangeFacetResult>().ranges[1].count.ShouldEqual(2000);

        It should_contain_quantity_facet_with_correct_total_count = () =>
            result.facets["quantity"].As<RangeFacetResult>().ranges[1].total_count.ShouldEqual(2100);

        It should_contain_quantity_facet_with_correct_total = () =>
            result.facets["quantity"].As<RangeFacetResult>().ranges[1].total.ShouldEqual(50000);

        It should_contain_quantity_facet_with_correct_min = () =>
            result.facets["quantity"].As<RangeFacetResult>().ranges[1].min.ShouldEqual(20);

        It should_contain_quantity_facet_with_correct_max = () =>
            result.facets["quantity"].As<RangeFacetResult>().ranges[1].max.ShouldEqual(70);

        It should_contain_quantity_facet_with_correct_mean = () =>
            result.facets["quantity"].As<RangeFacetResult>().ranges[1].mean.ShouldEqual(30.5);

        private static JsonNetSerializer jsonSerializer;
        private static SearchResult<object> result;
    }

}


text:
import Experiments from './experiments/index';
import Experiment from './experiment/index';
import Variant from './variant/index';

export {
    Experiments,
    Experiment,
    Variant,
};


text:
Welcome to Flask-Slack's documentation!
=======================================

.. module:: Flask-Script

**Flask-Slack** is a Flask extension which makes it easy to interact with Slack slash commands.

Quickstart
----------
You can register your Slack slash command to a method as follows.
::

    from flask_slack import Slack

    slack = Slack(app)

    @slack.command('your_command', token='your_token',
                   team_id='your_team_id', methods=['POST'])
    def your_method(**kwargs):
        text = kwargs.get('text')
        return slack.response(text)

All registered methods are dispatched through ``slack.dispatch`` method. You can connect it to an endpoint which you wish Slack robots to request with.
::

    app.add_url_rule('/', view_func=slack.dispatch)

Installation
------------

You can install Flask-Slack with pip::

    $ pip install flask-slack

Or, with setuptools easy_install in case you didn't have pip::

    $ easy_install flask-slack

API Reference
-------------

.. toctree::
   :maxdepth: 2

   slack
   exceptions


text:
<?php
/**
 * Transaction class
 *
 * @author David Vandemaele <david@tigron.be>
 */

abstract class Transaction extends \Skeleton\Transaction\Transaction {
}