text:
/* ###
 * IP: Apache License 2.0
 * NOTE: Based on the simg2img code from The Android Open Source Project
 */
/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ghidra.file.formats.sparseimage;

import java.io.IOException;

import ghidra.app.util.bin.*;
import ghidra.program.model.data.*;
import ghidra.util.exception.DuplicateNameException;

public class ChunkHeader implements StructConverter {

	private short chunk_type;	// See SparseConstants.CHUNK_TYPE_*
	private short reserved1;
	private int chunk_sz;		// number of blocks in output
	private int total_sz;

	public ChunkHeader(ByteProvider provider) throws IOException {
		this(new BinaryReader(provider, true));
	}

	public ChunkHeader(BinaryReader reader) throws IOException {
		chunk_type = reader.readNextShort();
		reserved1 = reader.readNextShort();
		chunk_sz = reader.readNextInt();
		total_sz = reader.readNextInt();
	}

	public short getChunk_type() {
		return chunk_type;
	}

	public short getReserved1() {
		return reserved1;
	}

	public int getChunk_sz() {
		return chunk_sz;
	}

	public int getTotal_sz() {
		return total_sz;
	}

	@Override
	public DataType toDataType() throws DuplicateNameException, IOException {
		Structure structure = new StructureDataType("chunk_header", 0);
		structure.add(WORD, "chunk_type", null);
		structure.add(WORD, "reserved1", null);
		structure.add(DWORD, "chunk_sz", null);
		structure.add(DWORD, "total_sz", null);
		return structure;
	}

}


text:
#if defined(PERL_IN_UTF8_C) || defined(PERL_IN_REGCOMP_C) || defined(PERL_IN_REGEXEC_C)

/* An element is in an inversion list iff its index is even numbered: 0, 2, 4,
 * etc */
#define ELEMENT_RANGE_MATCHES_INVLIST(i) (! ((i) & 1))
#define PREV_RANGE_MATCHES_INVLIST(i) (! ELEMENT_RANGE_MATCHES_INVLIST(i))

/* This converts to/from our UVs to what the SV code is expecting: bytes. */
#define TO_INTERNAL_SIZE(x) ((x) * sizeof(UV))
#define FROM_INTERNAL_SIZE(x) ((x)/ sizeof(UV))

PERL_STATIC_INLINE bool*
S_get_invlist_offset_addr(SV* invlist)
{
    /* Return the address of the field that says whether the inversion list is
     * offset (it contains 1) or not (contains 0) */
    PERL_ARGS_ASSERT_GET_INVLIST_OFFSET_ADDR;

    assert(SvTYPE(invlist) == SVt_INVLIST);

    return &(((XINVLIST*) SvANY(invlist))->is_offset);
}

PERL_STATIC_INLINE UV
S__invlist_len(SV* const invlist)
{
    /* Returns the current number of elements stored in the inversion list's
     * array */

    PERL_ARGS_ASSERT__INVLIST_LEN;

    assert(SvTYPE(invlist) == SVt_INVLIST);

    return (SvCUR(invlist) == 0)
           ? 0
           : FROM_INTERNAL_SIZE(SvCUR(invlist)) - *get_invlist_offset_addr(invlist);
}

PERL_STATIC_INLINE bool
S__invlist_contains_cp(SV* const invlist, const UV cp)
{
    /* Does <invlist> contain code point <cp> as part of the set? */

    IV index = _invlist_search(invlist, cp);

    PERL_ARGS_ASSERT__INVLIST_CONTAINS_CP;

    return index >= 0 && ELEMENT_RANGE_MATCHES_INVLIST(index);
}

PERL_STATIC_INLINE UV*
S_invlist_array(SV* const invlist)
{
    /* Returns the pointer to the inversion list's array.  Every time the
     * length changes, this needs to be called in case malloc or realloc moved
     * it */

    PERL_ARGS_ASSERT_INVLIST_ARRAY;

    /* Must not be empty.  If these fail, you probably didn't check for <len>
     * being non-zero before trying to get the array */
    assert(_invlist_len(invlist));

    /* The very first element always contains zero, The array begins either
     * there, or if the inversion list is offset, at the element after it.
     * The offset header field determines which; it contains 0 or 1 to indicate
     * how much additionally to add */
    assert(0 == *(SvPVX(invlist)));
    return ((UV *) SvPVX(invlist) + *get_invlist_offset_addr(invlist));
}

#   if defined(PERL_IN_UTF8_C) || defined(PERL_IN_REGEXEC_C)

/* These symbols are only needed later in regcomp.c */
#       undef TO_INTERNAL_SIZE
#       undef FROM_INTERNAL_SIZE
#   endif

#endif

redpajama_set_name: RedPajamaGithub


text:
(function (_tf) {

	_tf.module('test', {

		setup: function() {

		},

		teardown: function() {

		}
	});

	test("error message giving inappropriate storage argument", 6, function() {

		try {
			DOMTE.render(function t13 () {});
			ok(true);
		} catch(error) {
			throw new Error('This error should not happen: '+ error.message);
		}

		var definedButUnset;

		var tries = [
			null,
			undefined,
			definedButUnset,
			[],
			1
		];
		for ( var i = 0; i < tries.length; i++ ) {
			try {
				DOMTE.render(null, null, tries[i]);

			} catch(error) {
				equal(error.message, 'InvalidArgumentException: Storage must be an object.');
			}
		}
	});

	test("deep element storing", 6, function() {
		var
			storage = {},
			res = DOMTE.render(function t15 () {
				return div(
					':myDiv',
					'#myId',
					'.myclass seccondclass',
					{'id':'myId2'},

					div(
						':myDiv2',
						'.myclass seccondclass',
						{'id':'myId2'},

						div(
							':myDiv3'

						)
					)

				);
			}, null, storage)
		; // @var

		equal(typeof storage.myDiv, 'object');
		equal(storage.myDiv.nodeType, 1);

		equal(typeof storage.myDiv2, 'object');
		equal(storage.myDiv2.nodeType, 1);

		equal(typeof storage.myDiv3, 'object');
		equal(storage.myDiv3.nodeType, 1);
	});

	test("informative error on storing without storage argument", 1, function() {
		throws(function() {
			DOMTE.render(function t16 () {
				return div(
					':myDiv',

					div(':myDiv')
				);
			});
		},
		/InvalidArgumentException.*myDiv" without given storage argument!/);
	});

	test("informative error on ambiguous storing", 1, function() {
		throws(function() {
			DOMTE.render(function t17 () {
				return div(
					':myDiv',

					div(
						p(':myDiv')
					)
				);
			}, null, {});
		},
		/InvalidArgumentException.*myDiv/);
	});

	test("support any return type", 1, function() {
		var res = DOMTE.render(function t18 () {
			return [
				div(
					'.modal fade'

				),

				div('.modal2 fade2')
			];
		});

		equal(res.length, 2);
	});

	test("can append text nodes", 1, function() {
		var res = DOMTE.render(function t19 () {
			return div(
				'.modal fade',
				document.createTextNode('anyTextNode')
			);
		});

		equal(res.innerHTML, 'anyTextNode');
	});

	test("can append text nodes", 8, function() {
		var attr = {
			htmlFor: 'htmlFor_',
			className: 'className_',
			readOnly: 'readOnly_',
			maxLength: 'maxLength_',
			cellSpacing: 'cellSpacing_',
			rowSpan: 'rowSpan_',
			colSpan: 'colSpan_'
		};

		var res = DOMTE.render(function t20 () {
			return div({
				htmlFor: 'htmlFor_',
				className: 'className_',
				readOnly: 'readOnly_',
				maxLength: 'maxLength_',
				cellSpacing: 'cellSpacing_',
				rowSpan: 'rowSpan_',
				colSpan: 'colSpan_',
			}, {
				tabIndex: 4
			});
		});

		for ( var a in attr ) {
			if ( !attr.hasOwnProperty(a) )
				continue;

			equal(res[a], a+'_');
		}

		equal(res.tabIndex, 4);
	});

	test("reuse registered template", 1, function() {
		var tpl = DOMTE.register(function t21 () {
			return div(
				'.modal fade',
				document.createTextNode('anyTextNode')
			);
		});

		var res = DOMTE.render(tpl);
		equal(res.innerHTML, 'anyTextNode');
	});

	test("setting different data on reused templates", 2, function() {
		var tpl = DOMTE.register(function t22 (_, data) {
			return div(
				document.createTextNode(data.text)
			);
		});

		equal(DOMTE.render(tpl, {text: 'anyTextNode'}).innerHTML, 'anyTextNode');
		equal(DOMTE.render(tpl, {text: 'anyOtherText'}).innerHTML, 'anyOtherText');
	});

	test("reused templates are independent and not referenced", 2, function() {
		var tpl = DOMTE.register(function t23 () {
			return div(
				p(),
				span()
			);
		});

		var tpl1 = DOMTE.render(tpl);
		var tpl2 = DOMTE.render(tpl);

		tpl1.removeChild(tpl1.childNodes[1]);
		equal(tpl1.childNodes.length, 1);
		equal(tpl2.childNodes.length, 2);
	});

	test("render inline function", 1, function() {
		var res = DOMTE.render(function t24 (_, data) {
			return div(
				ul(function() {
					return li(data.content);
				})
			);
		}, {content:'myText'});

		equal(res.innerHTML, '

myText

');

	});

	test("ignore inline function returning no value", 1, function() {
		var res = DOMTE.render(function t25 (_, data) {
			return div(
				ul(function() {
					li(data.content);
				})
			);
		}, {content:'myText'});

		equal(res.innerHTML, '

');

	});

	test("can handle array arguments", 1, function() {
		var res = DOMTE.render(function t26 (_, data) {
			return div(
				[span(), p(), function() {return div();}],
				h1()
			);
		});

		equal(res.innerHTML, '

');
	});

	test("can handle nested inline functions", 1, function() {
		var res = DOMTE.render(function t27 (_, data) {
			return div(
				function() {
					return function() {
						return div();
					}
				},[
					function () {
						return [
							span(),
							function () { return p() }
						];
					},
					function () { return div(
						function() {
							return span();
						}
					)},
				]
			);
		});

		equal(res.innerHTML, '

');
	});

	test("can use templates inside templates", 1, function() {
		var anyTpl = DOMTE.register(function insideTpl28 () {
			return div(
				span()
			);
		});
		var res = DOMTE.render(function t28 (_, data) {
			return div([
				_tpl.insideTpl28(_, data),
				p(),
				_tpl.insideTpl28(_, data),
			]);
		});

		equal(res.innerHTML, '

');
	});

	test("throw error for invalid inline template usage", 1, function() {
		var anyTpl = DOMTE.register(function insideTpl29 () {
			return div(
				span()
			);
		});
		try {
			var res = DOMTE.render(function t29 (_, data) {
				return div(
					_tpl.insideTpl29()
				);
			});
		} catch (error) {
			equal(error.message, 'You have to supply "_" as argument when calling inline template.');
		}

	});

	test("can use elements without paranthesis", 1, function() {
		var res = DOMTE.render(function t30 (_, data) {
			return div([
				div(div),
				p
			]);
		});

		equal(res.innerHTML, '

');
	});

	test("can use templates without paranthesis", 1, function() {
		var anyTpl = DOMTE.register(function insideTpl31 () {
			return div(
				span(p),
				p(data.textp)
			);
		});
		var res = DOMTE.render(function t31 (_, data) {
			return div(
				_tpl.insideTpl31
			);
		}, {textp: 'testText'});

		equal(res.innerHTML, '

testText

');
	});

})(QUnit);


text:
namespace content {

class WebApplicationCacheHostImpl
    : NON_EXPORTED_BASE(public blink::WebApplicationCacheHost) {
 public:
  // Returns the host having given id or NULL if there is no such host.
  static WebApplicationCacheHostImpl* FromId(int id);

  WebApplicationCacheHostImpl(blink::WebApplicationCacheHostClient* client,
                              AppCacheBackend* backend);
  ~WebApplicationCacheHostImpl() override;

  int host_id() const { return host_id_; }
  AppCacheBackend* backend() const { return backend_; }
  blink::WebApplicationCacheHostClient* client() const { return client_; }

  virtual void OnCacheSelected(const AppCacheInfo& info);
  void OnStatusChanged(AppCacheStatus);
  void OnEventRaised(AppCacheEventID);
  void OnProgressEventRaised(const GURL& url, int num_total, int num_complete);
  void OnErrorEventRaised(const AppCacheErrorDetails& details);
  virtual void OnLogMessage(AppCacheLogLevel log_level,
                            const std::string& message) {}
  virtual void OnContentBlocked(const GURL& manifest_url) {}

  // blink::WebApplicationCacheHost:
  void willStartMainResourceRequest(
      blink::WebURLRequest&,
      const blink::WebApplicationCacheHost*) override;
  void willStartSubResourceRequest(blink::WebURLRequest&) override;
  void selectCacheWithoutManifest() override;
  bool selectCacheWithManifest(const blink::WebURL& manifestURL) override;
  void didReceiveResponseForMainResource(const blink::WebURLResponse&) override;
  void didReceiveDataForMainResource(const char* data, unsigned len) override;
  void didFinishLoadingMainResource(bool success) override;
  blink::WebApplicationCacheHost::Status getStatus() override;
  bool startUpdate() override;
  bool swapCache() override;
  void getResourceList(blink::WebVector<ResourceInfo>* resources) override;
  void getAssociatedCacheInfo(CacheInfo* info) override;

 private:
  enum IsNewMasterEntry {
    MAYBE,
    YES,
    NO
  };

  blink::WebApplicationCacheHostClient* client_;
  AppCacheBackend* backend_;
  int host_id_;
  AppCacheStatus status_;
  blink::WebURLResponse document_response_;
  GURL document_url_;
  bool is_scheme_supported_;
  bool is_get_method_;
  IsNewMasterEntry is_new_master_entry_;
  AppCacheInfo cache_info_;
  GURL original_main_resource_url_;  // Used to detect redirection.
  bool was_select_cache_called_;
};

}  // namespace content

#endif  // CONTENT_CHILD_APPCACHE_WEB_APPLICATION_CACHE_HOST_IMPL_H_


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

	<wicket:head>
	</wicket:head>

		<wicket:panel>

				<input class="ow-autocomplete-hidden" type="hidden" wicket:id="autocompleteHidden" />
				<input class="ow-autocomplete-field form-control" type="text" wicket:id="autocompleteField" />

		</wicket:panel>


text:
001
018    package org.apache.hadoop.io.compress;
019
020    /**
021     * Alias class for DefaultCodec to enable codec discovery by 'deflate' name.
022     */
023    public class DeflateCodec extends DefaultCodec {
024    }


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.smsabort.MainActivity" >

	<item
	    android:id="@+id/delete_sms"
	    android:title="删除"/>
</menu>


text:
Register

Create your account

                <input type="text" class="form-control" placeholder="Username">

                  @

                <input type="text" class="form-control" placeholder="Email">

                <input type="password" class="form-control" placeholder="Password">

                <input type="password" class="form-control" placeholder="Repeat password">

              <button type="button" class="btn btn-block btn-success">Create Account</button>

                  <button class="btn btn-block btn-facebook" type="button">facebook</button>

                  <button class="btn btn-block btn-twitter" type="button">twitter</button>


text:
package org.motechproject.mds.annotations.internal.samples;

import org.motechproject.commons.date.model.Time;
import org.motechproject.mds.annotations.Cascade;
import org.motechproject.mds.annotations.CrudEvents;
import org.motechproject.mds.annotations.EnumDisplayName;
import org.motechproject.mds.annotations.Entity;
import org.motechproject.mds.annotations.Field;
import org.motechproject.mds.annotations.Ignore;
import org.motechproject.mds.annotations.InSet;
import org.motechproject.mds.annotations.InstanceLifecycleListener;
import org.motechproject.mds.annotations.Lookup;
import org.motechproject.mds.annotations.NotInSet;
import org.motechproject.mds.annotations.RestOperations;
import org.motechproject.mds.annotations.UIDisplayable;
import org.motechproject.mds.annotations.UIFilterable;
import org.motechproject.mds.annotations.NonEditable;
import org.motechproject.mds.annotations.InstanceLifecycleListenerType;
import org.motechproject.mds.annotations.RestOperation;
import org.motechproject.mds.event.CrudEventType;

import javax.jdo.annotations.Column;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.Unique;
import javax.validation.constraints.DecimalMax;
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Entity(recordHistory = true, maxFetchDepth = 3)
@RestOperations(RestOperation.DELETE)
@CrudEvents(CrudEventType.CREATE)
public class Sample {
    // if you added a new field (and it has no @Ignore annotation) please increase this number.
    public static final long FIELD_COUNT = 23;
    public static final long UI_DISPLAYABLE_FIELD_COUNT = 1;
    public static final long UI_FILTERABLE_FIELD_COUNT = 3;

    public enum TestEnum {
        ONE("one"), TWO("two"), THREE("three");

        private String dispName;

        TestEnum(String dispName){
            this.dispName = dispName;
        }

        public String getDispName(){
            return dispName;
        }
    }

    // test class

    @Field
    @UIFilterable
    private Boolean world;

    @UIFilterable
    @DecimalMin(value = "3")
    @DecimalMax(value = "4")
    @InSet(value = {"3", "3.14", "4"})
    @NotInSet(value = {"1", "2", "5"})
    public Integer pi;

    @DecimalMax(value = "1")
    @DecimalMin(value = "0")
    @InSet(value = {"1", "0.75", "0.5", "0.25", "0"})
    @NotInSet(value = {"-1", "2", "3"})
    public Double epsilon;

    @Min(value = 0)
    @Max(value = 10)
    public Integer random;

    @Max(value = 1)
    @Min(value = 0)
    public Double gaussian;

    @Pattern(regexp = "[A-Z][a-z]{9}")
    @Size(min = 10, max = 20)
    public String poem;

    @DecimalMin(value = "100")
    @DecimalMax(value = "500")
    public String article;

    @Ignore
    public String ignored;

    @UIDisplayable
    @NonEditable
    public Double money;

    @Column(length = 400)
    private String length400;

    private String ignoredPrivate;

    private Date serverDate;

    private Time localTime;

    @Field
    @NonEditable(display = false)
    private boolean primitiveBool;

    @Field
    private int primitiveInt;

    @Field
    private double primitiveDouble;

    @Field
    private long primitiveLong;

    @Field
    @Cascade(delete = true, update = false)
    private Set<RelatedSample> oneToManyUni;

    @Field
    @Persistent(mappedBy = "manyToOneBi")
    private List<RelatedSample> oneToManyBi;

    @Field
    private RelatedSample oneToOneUni;

    @Field
    @Persistent(mappedBy = "oneToOneBi2")
    private RelatedSample oneToOneBi;

    @Field
    @EnumDisplayName(enumField="dispName")
    private Set<TestEnum> enumSet;

    @Field
    @EnumDisplayName(enumField="dispName")
    private TestEnum singleEnum;

    @Field
    private Set<String> stringSet;

    @Field
    @Unique
    private String unique;

    @Lookup
    public void lookupTest() {

    }

    public Boolean getWorld() {
        return world;
    }

    public void setWorld(Boolean world) {
        this.world = world;
    }

    @Field(displayName = "Server Date", placeholder = "yyyy-mm-dd")
    @UIFilterable
    public Date getServerDate() {
        return serverDate;
    }

    public void setServerDate(Date serverDate) {
        this.serverDate = serverDate;
    }

    public Time getLocalTime() {
        return localTime;
    }

    @Field(required = true)
    public void setLocalTime(Time localTime) {
        this.localTime = localTime;
    }

    @Ignore
    public void setIgnoredPrivate(String ignoredPrivate) {
        this.ignoredPrivate = ignoredPrivate;
    }

    @Ignore
    public String getIgnoredPrivate() {
        return ignoredPrivate;
    }

    public String getLength400() {
        return length400;
    }

    public void setLength400(String length400) {
        this.length400 = length400;
    }

    public Set<RelatedSample> getOneToManyUni() {
        return oneToManyUni;
    }

    public void setOneToManyUni(Set<RelatedSample> oneToManyUni) {
        this.oneToManyUni = oneToManyUni;
    }

    @Cascade(persist = false, update = false, delete = true)
    public List<RelatedSample> getOneToManyBi() {
        return oneToManyBi;
    }

    public void setOneToManyBi(List<RelatedSample> oneToManyBi) {
        this.oneToManyBi = oneToManyBi;
    }

    public RelatedSample getOneToOneUni() {
        return oneToOneUni;
    }

    public void setOneToOneUni(RelatedSample oneToOneUni) {
        this.oneToOneUni = oneToOneUni;
    }

    public RelatedSample getOneToOneBi() {
        return oneToOneBi;
    }

    public void setOneToOneBi(RelatedSample oneToOneBi) {
        this.oneToOneBi = oneToOneBi;
    }

    public boolean isPrimitiveBool() {
        return primitiveBool;
    }

    public void setPrimitiveBool(boolean primitiveBool) {
        this.primitiveBool = primitiveBool;
    }

    public int getPrimitiveInt() {
        return primitiveInt;
    }

    public void setPrimitiveInt(int primitiveInt) {
        this.primitiveInt = primitiveInt;
    }

    public double getPrimitiveDouble() {
        return primitiveDouble;
    }

    public void setPrimitiveDouble(double primitiveDouble) {
        this.primitiveDouble = primitiveDouble;
    }

    public long getPrimitiveLong() {
        return primitiveLong;
    }

    public void setPrimitiveLong(long primitiveLong) {
        this.primitiveLong = primitiveLong;
    }

    public String getUnique() {
        return unique;
    }

    public void setUnique(String unique) {
        this.unique = unique;
    }

    @Ignore
    public static int getIgnoredStaticProperty() {
        return 13;
    }

    @InstanceLifecycleListener({InstanceLifecycleListenerType.POST_CREATE, InstanceLifecycleListenerType.POST_DELETE})
    public void correctListener(Sample sample) {
    }

    @InstanceLifecycleListener({})
    public void emptyValues(Sample sample) {
    }

    @InstanceLifecycleListener(InstanceLifecycleListenerType.POST_CREATE)
    public void badNumberOfParameters(Sample sample, String string) {
    }

    @InstanceLifecycleListener(InstanceLifecycleListenerType.POST_DELETE)
    public void badParameterType(String string) {
    }

    @InstanceLifecycleListener(InstanceLifecycleListenerType.POST_DELETE)
    public void correctPostDeleteListener(Sample sample) {
    }

    @InstanceLifecycleListener(value = InstanceLifecycleListenerType.POST_CREATE, packageName = "org.motechproject")
    public void packageListener(Object o) {
    }

    @InstanceLifecycleListener(value = InstanceLifecycleListenerType.POST_CREATE, packageName = "org.motechproject")
    public void invalidParameterTypePackageListener(Sample sample) {
    }
}


text:
package restful

import (
	"fmt"
	"net/http"

	nqmSql "github.com/Cepave/open-falcon-backend/common/db/nqm/testing"
	json "github.com/Cepave/open-falcon-backend/common/json"
	ogko "github.com/Cepave/open-falcon-backend/common/testing/ginkgo"
	tHttp "github.com/Cepave/open-falcon-backend/common/testing/http"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/ginkgo/extensions/table"
	. "github.com/onsi/gomega"
)

func sPtr(v string) *string {
	return &v
}

var _ = Describe("Getting NQM agent by id", itSkipOnPortal.PrependBeforeEach(func() {
	BeforeEach(func() {
		inPortalTx(
			`
			INSERT INTO owl_name_tag(nt_id, nt_value)
			VALUES(407, 'nt-rest-01')
			`,
			`
			INSERT INTO host(id, hostname, agent_version, plugin_version)
			VALUES(25101, 'hs-rest-get-1', '', '')
			`,
			`
			-- IP: 87.90.6.55
			INSERT INTO nqm_agent(
				ag_id, ag_hs_id, ag_name, ag_connection_id, ag_hostname, ag_ip_address, ag_status,
				ag_isp_id, ag_pv_id, ag_ct_id, ag_nt_id
			)
			VALUES(36771, 25101, 'ag-rest-name-1', 'ag-rest-1@87.90.6.55', 'ag-get-1.rest.com', x'575A0637', 1, 3, 3, 5, 407)
			`,
			`
			INSERT INTO owl_group_tag(gt_id, gt_name)
			VALUES(50091, 'BOCC-1'),
				(50092, 'BOCC-2'),
				(50093, 'BOCC-3')
			`,
			`
			INSERT INTO nqm_agent_group_tag(agt_ag_id, agt_gt_id)
			VALUES(36771, 50091), (36771, 50092), (36771, 50093)
			`,
		)
	})

	AfterEach(func() {
		inPortalTx(
			`DELETE FROM nqm_agent WHERE ag_id = 36771`,
			`DELETE FROM host WHERE id = 25101`,
			`DELETE FROM owl_name_tag WHERE nt_id = 407`,
			`
			DELETE FROM owl_group_tag
			WHERE gt_id >= 50091 AND
				gt_id <= 50093
			`,
		)
	})

	It("Get data of a NQM agent", func() {
		resp := tHttp.NewResponseResultBySling(
			httpClientConfig.NewClient().
				Get("api/v1/nqm/agent/36771"),
		)

		jsonBody := resp.GetBodyAsJson()
		GinkgoT().Logf("[Get A Agent] JSON Result: %s", json.MarshalPrettyJSON(jsonBody))

		Expect(resp).To(ogko.MatchHttpStatus(http.StatusOK))
		Expect(jsonBody.Get("id").MustInt()).To(Equal(36771))
		Expect(jsonBody.Get("group_tags").MustArray()).To(HaveLen(3))
	})
}))

var _ = Describe("Adding new NQM agent", itSkipOnPortal.PrependBeforeEach(func() {
	AfterEach(func() {
		inPortalTx(
			"DELETE FROM nqm_agent WHERE ag_connection_id LIKE 'add-agent%'",
			"DELETE FROM host WHERE hostname = 'new-host-cccc'",
			"DELETE FROM owl_name_tag where nt_value LIKE 'add-agent-%'",
			"DELETE FROM owl_group_tag where gt_name LIKE 'pp-rest-tag-%'",
		)
	})

	reqBody := &struct {
		Name         string   `json:"name"`
		Comment      string   `json:"comment"`
		Hostname     string   `json:"hostname"`
		ConnectionId string   `json:"connection_id"`
		Status       bool     `json:status`
		IspId        int      `json:"isp_id"`
		ProvinceId   int      `json:"province_id"`
		CityId       int      `json:"city_id"`
		NameTag      *string  `json:"name_tag"`
		GroupTags    []string `json:"group_tags"`
	}{
		Name:       "ko-name-cc1",
		Comment:    "cc-name-cc1",
		Hostname:   "new-host-cccc",
		Status:     true,
		IspId:      8,
		ProvinceId: 9,
		CityId:     130,
		GroupTags:  []string{"pp-rest-tag-1", "pp-rest-tag-2"},
	}

	callApi := func(jsonBody interface{}) *tHttp.ResponseResult {
		return tHttp.NewResponseResultBySling(
			httpClientConfig.NewClient().Post("api/v1/nqm/agent").
				BodyJSON(reqBody),
		)
	}

	DescribeTable("Success adding",
		func(connectionId string, nameTag *string) {
			reqBody.ConnectionId = "add-agent-" + connectionId
			reqBody.NameTag = nameTag

			respResult := callApi(reqBody)

			jsonBody := respResult.GetBodyAsJson()
			GinkgoT().Logf("[Add Agent] JSON Result: %s", json.MarshalPrettyJSON(jsonBody))

			Expect(jsonBody.Get("name").MustString()).To(Equal(reqBody.Name))
			Expect(jsonBody.Get("comment").MustString()).To(Equal(reqBody.Comment))
			Expect(jsonBody.Get("connection_id").MustString()).To(Equal(reqBody.ConnectionId))
			Expect(jsonBody.Get("ip_address").MustString()).To(Equal("0.0.0.0"))
			Expect(jsonBody.Get("hostname").MustString()).To(Equal(reqBody.Hostname))
			Expect(jsonBody.Get("status").MustBool()).To(Equal(reqBody.Status))
			Expect(jsonBody.Get("isp").Get("id").MustInt()).To(Equal(reqBody.IspId))
			Expect(jsonBody.Get("province").Get("id").MustInt()).To(Equal(reqBody.ProvinceId))
			Expect(jsonBody.Get("city").Get("id").MustInt()).To(Equal(reqBody.CityId))

			if nameTag != nil {
				Expect(jsonBody.Get("name_tag").Get("value").MustString()).To(Equal(*nameTag))
			} else {
				Expect(jsonBody.Get("name_tag").Get("id").MustInt()).To(Equal(-1))
			}

			Expect(jsonBody.Get("group_tags").MustArray()).To(HaveLen(2))
		},
		Entry("Viable name tag", "@192.33.9.1", sPtr("add-agent-nt-1")),
		Entry("Nil name tag", "@192.33.9.2", nil),
	)

	It("Adding error with conflict connection id", func() {
		reqBody.ConnectionId = "add-agent-@existing-gc01"
		reqBody.NameTag = nil

		By("Prepare existing data")
		prepareResult := callApi(reqBody)
		Expect(prepareResult).To(ogko.MatchHttpStatus(http.StatusOK))

		By("Asserts the conflict result")
		conflictResult := callApi(reqBody)
		Expect(conflictResult).To(ogko.MatchHttpStatus(http.StatusConflict))

		jsonBody := conflictResult.GetBodyAsJson()
		GinkgoT().Logf("Conflict body: %s", json.MarshalPrettyJSON(jsonBody))
		Expect(jsonBody.Get("error_code").MustInt()).To(Equal(1))
	})
}))

var _ = Describe("Listing agents", itSkipOnPortal.PrependBeforeEach(func() {
	BeforeEach(func() {
		inPortalTx(
			`
			INSERT INTO host(id, hostname, agent_version, plugin_version)
			VALUES(22091, 'agent-it-01', '', '')
			`,
			`
			INSERT INTO nqm_agent(ag_id, ag_hs_id, ag_name, ag_connection_id, ag_hostname, ag_ip_address, ag_isp_id)
			VALUES(4321, 22091, 'agent-it-01', 'agent-01@28.71.19.22', 'agent-01.fb.com', x'1C471316', 7),
				(4322, 22091, 'agent-it-02', 'agent-02@28.71.19.23', 'agent-02.fb.com', x'1C471317', 7),
				(4323, 22091, 'agent-it-03', 'agent-03@28.71.19.23', 'agent-03.fb.com', x'1C471318', 7)
			`,
		)
	})

	AfterEach(func() {
		inPortalTx(
			"DELETE FROM nqm_agent WHERE ag_id >= 4321 AND ag_id <= 4323",
			"DELETE FROM host WHERE id = 22091",
		)
	})

	It("Listing without any conditions", func() {
		result := tHttp.NewResponseResultBySling(
			httpClientConfig.NewClient().Get("api/v1/nqm/agents"),
		)
		Expect(result).To(ogko.MatchHttpStatus(http.StatusOK))

		jsonBody := result.GetBodyAsJson()
		GinkgoT().Logf("[List Agents] JSON Result: %s", json.MarshalPrettyJSON(jsonBody))

		Expect(jsonBody.MustArray()).To(HaveLen(3))
	})
}))

var _ = Describe("Listing targets of agent(ping list)", itSkipOnPortal.PrependBeforeEach(func() {
	BeforeEach(func() {
		inPortalTx(nqmSql.InitNqmCacheAgentPingList...)
	})

	AfterEach(func() {
		inPortalTx(nqmSql.ClearNqmCacheAgentPingList...)
	})

	pInt64 := func(v int64) *int64 { return &v }
	fetchTargets := func(agentId int) *tHttp.ResponseResult {
		return tHttp.NewResponseResultBySling(
			httpClientConfig.NewClient().Get(
				fmt.Sprintf("api/v1/nqm/agent/%d/targets", agentId),
			),
		)
	}

	DescribeTable("Normal NQM agent(existing)",
		func(agentId int, expectedRefreshTime *int64) {
			respResult := fetchTargets(agentId)

			Expect(respResult).To(ogko.MatchHttpStatus(http.StatusOK))

			jsonBody := respResult.GetBodyAsJson()
			GinkgoT().Logf("List of targets(JSON): %s", json.MarshalPrettyJSON(jsonBody))

			if expectedRefreshTime != nil {
				Expect(jsonBody.Get("cache_refresh_time").MustInt64()).To(Equal(*expectedRefreshTime))
			} else {
				Expect(jsonBody.Get("cache_refresh_time").Interface()).To(BeNil())
			}
		},
		Entry("Has cache", 24021, pInt64(1483200000)),
		Entry("Has cache", 24022, pInt64(1483200000)),
		Entry("Has no cache", 24023, nil),
	)

	It("Not existing NQM agent", func() {
		respResult := fetchTargets(99801)

		Expect(respResult).To(ogko.MatchHttpStatus(http.StatusNotFound))

		jsonBody := respResult.GetBodyAsJson()
		GinkgoT().Logf("Error content: %s", json.MarshalPrettyJSON(jsonBody))
		Expect(jsonBody.Get("error_code").MustInt()).To(Equal(-1))
	})
}))

var _ = Describe("Clearing cache of target(ping list) on a agent", itSkipOnPortal.PrependBeforeEach(func() {
	BeforeEach(func() {
		inPortalTx(nqmSql.InitNqmCacheAgentPingList...)
	})

	AfterEach(func() {
		inPortalTx(nqmSql.ClearNqmCacheAgentPingList...)
	})

	callApi := func(agentId int) *tHttp.ResponseResult {
		return tHttp.NewResponseResultBySling(
			httpClientConfig.NewClient().Post(
				fmt.Sprintf("api/v1/nqm/agent/%d/targets/clear", agentId),
			),
		)
	}

	DescribeTable("Normal agents",
		func(agentId int, expectedRowsAffected int) {
			callAndCheck := func(expectedAffectedRow int) {
				result := callApi(agentId)

				Expect(result).To(ogko.MatchHttpStatus(http.StatusOK))
				jsonBody := result.GetBodyAsJson()
				GinkgoT().Logf("Clear cache: %s", json.MarshalPrettyJSON(jsonBody))
				Expect(jsonBody.Get("rows_affected").MustInt()).To(Equal(expectedAffectedRow))
			}

			By("First time of clearing")
			callAndCheck(expectedRowsAffected)

			By("Second time of clearing")
			callAndCheck(0)
		},
		Entry("Cache has viable targets", 24021, 1),
		Entry("Cache has non-viable target", 24022, 1),
		Entry("No cache for the agent", 24023, 0),
	)

	It("Clear non-existing NQM agent", func() {
		result := callApi(90051)

		Expect(result).To(ogko.MatchHttpStatus(http.StatusNotFound))
		jsonBody := result.GetBodyAsJson()
		GinkgoT().Logf("Error result: %s", json.MarshalPrettyJSON(jsonBody))
		Expect(jsonBody.Get("error_code").MustInt()).To(Equal(-1))
	})
}))

var _ = Describe("Modifying NQM agent", itSkipOnPortal.PrependBeforeEach(func() {
	BeforeEach(func() {
		inPortalTx(
			`
			INSERT INTO owl_name_tag(nt_id, nt_value)
			VALUES(8461, 'rest-nt-1')
			`,
			`
			INSERT INTO owl_group_tag(gt_id, gt_name)
			VALUES(20871, "rest-gt-1"), (20872, "rest-gt-2")
			`,
			`
			INSERT INTO host(id, hostname)
			VALUES(4401, '33.99.44.17')
			`,
			`
			INSERT INTO nqm_agent(ag_id, ag_hs_id, ag_connection_id, ag_hostname, ag_ip_address)
			VALUES(23041, 4401, 'update-agent@33.99.44.17', '33.99.44.17', x'21632C11')
			`,
			`
			INSERT INTO nqm_agent_group_tag(agt_ag_id, agt_gt_id)
			VALUES(23041, 20871),(23041, 20872)
			`,
		)
	})

	AfterEach(func() {
		inPortalTx(
			"DELETE FROM nqm_agent WHERE ag_id = 23041",
			"DELETE FROM host WHERE id = 4401",
			"DELETE FROM owl_name_tag WHERE nt_value LIKE 'rest-nt-%'",
			"DELETE FROM owl_group_tag WHERE gt_name LIKE 'rest-gt-%'",
		)
	})

	reqJson := &struct {
		Name       string   `json:"name"`
		Status     bool     `json:status`
		Comment    string   `json:"comment"`
		IspId      int      `json:"isp_id"`
		ProvinceId int      `json:"province_id"`
		CityId     int      `json:"city_id"`
		NameTag    *string  `json:"name_tag"`
		GroupTags  []string `json:"group_tags"`
	}{
		Name:       "Update-Agent-1",
		Status:     false,
		Comment:    "This is updated comment",
		IspId:      3,
		ProvinceId: 11,
		CityId:     230,
	}

	DescribeTable("",
		func(nameTag *string, groupTags []string) {
			reqJson.NameTag = nameTag
			reqJson.GroupTags = groupTags

			result := tHttp.NewResponseResultBySling(
				httpClientConfig.NewClient().Put(
					fmt.Sprintf("api/v1/nqm/agent/23041"),
				).BodyJSON(reqJson),
			)

			Expect(result).To(ogko.MatchHttpStatus(http.StatusOK))

			jsonBody := result.GetBodyAsJson()
			GinkgoT().Logf("Update agent: %s", json.MarshalPrettyJSON(jsonBody))

			Expect(jsonBody.Get("name").MustString()).To(Equal(reqJson.Name))
			Expect(jsonBody.Get("status").MustBool()).To(Equal(reqJson.Status))
			Expect(jsonBody.Get("isp").Get("id").MustInt()).To(Equal(reqJson.IspId))
			Expect(jsonBody.Get("province").Get("id").MustInt()).To(Equal(reqJson.ProvinceId))
			Expect(jsonBody.Get("city").Get("id").MustInt()).To(Equal(reqJson.CityId))

			if nameTag != nil {
				Expect(jsonBody.Get("name_tag").Get("value").MustString()).To(Equal(*nameTag))
			} else {
				Expect(jsonBody.Get("name_tag").Get("id").MustInt()).To(Equal(-1))
			}

			Expect(jsonBody.Get("group_tags").MustArray()).To(HaveLen(len(groupTags)))
		},
		Entry("Set name tag, group tags to viable value", sPtr("rest-nt-9"), []string{"rest-gt-91", "rest-gt-92", "rest-gt-93"}),
		Entry("Set name tag, group tags to non-viable value", nil, []string{}),
	)
}))


text:
namespace PactNet.Matchers
{
    internal enum MatcherCheckFailureType
    {
        AdditionalItemInArray,
        AdditionalPropertyInObject,
        ValueDoesNotMatch
    }
}


text:
using webkit_glue::ResourceLoaderBridge;

namespace content {

static const char kTestPageUrl[] = "http://www.google.com/";
static const char kTestPageHeaders[] =
  "HTTP/1.1 200 OK\nContent-Type:text/html\n\n";
static const char kTestPageMimeType[] = "text/html";
static const char kTestPageCharset[] = "";
static const char kTestPageContents[] =
  "<title>Google</title>
Google
";
static const char kTestRedirectHeaders[] =
  "HTTP/1.1 302 Found\nLocation:http://www.google.com/\n\n";

// Listens for request response data and stores it so that it can be compared
// to the reference data.
class TestRequestPeer : public RequestPeer {
 public:
  TestRequestPeer(ResourceLoaderBridge* bridge)
      :  follow_redirects_(true),
         defer_on_redirect_(false),
         seen_redirects_(0),
         cancel_on_receive_response_(false),
         received_response_(false),
         total_encoded_data_length_(0),
         total_downloaded_data_length_(0),
         complete_(false),
         bridge_(bridge) {
  }

  virtual void OnUploadProgress(uint64 position, uint64 size) OVERRIDE {
  }

  virtual bool OnReceivedRedirect(const GURL& new_url,
                                  const GURL& new_first_party_for_cookies,
                                  const ResourceResponseInfo& info) OVERRIDE {
    ++seen_redirects_;
    if (defer_on_redirect_)
      bridge_->SetDefersLoading(true);
    return follow_redirects_;
  }

  virtual void OnReceivedResponse(const ResourceResponseInfo& info) OVERRIDE {
    EXPECT_FALSE(received_response_);
    received_response_ = true;
    if (cancel_on_receive_response_)
      bridge_->Cancel();
  }

  virtual void OnDownloadedData(int len, int encoded_data_length) OVERRIDE {
    total_downloaded_data_length_ += len;
    total_encoded_data_length_ += encoded_data_length;
  }

  virtual void OnReceivedData(const char* data,
                              int data_length,
                              int encoded_data_length) OVERRIDE {
    EXPECT_TRUE(received_response_);
    EXPECT_FALSE(complete_);
    data_.append(data, data_length);
    total_encoded_data_length_ += encoded_data_length;
  }

  virtual void OnCompletedRequest(
      int error_code,
      bool was_ignored_by_handler,
      bool stale_copy_in_cache,
      const std::string& security_info,
      const base::TimeTicks& completion_time,
      int64 total_transfer_size) OVERRIDE {
    EXPECT_TRUE(received_response_);
    EXPECT_FALSE(complete_);
    complete_ = true;
  }

  void set_follow_redirects(bool follow_redirects) {
    follow_redirects_ = follow_redirects;
  }

  void set_defer_on_redirect(bool defer_on_redirect) {
    defer_on_redirect_ = defer_on_redirect;
  }

  void set_cancel_on_receive_response(bool cancel_on_receive_response) {
    cancel_on_receive_response_ = cancel_on_receive_response;
  }

  int seen_redirects() const { return seen_redirects_; }

  bool received_response() const { return received_response_; }

  const std::string& data() const {
    return data_;
  }
  int total_encoded_data_length() const {
    return total_encoded_data_length_;
  }
  int total_downloaded_data_length() const {
    return total_downloaded_data_length_;
  }

  bool complete() const { return complete_; }

 private:
  // True if should follow redirects, false if should cancel them.
  bool follow_redirects_;
  // True if the request should be deferred on redirects.
  bool defer_on_redirect_;
  // Number of total redirects seen.
  int seen_redirects_;

  bool cancel_on_receive_response_;
  bool received_response_;

  // Data received.   If downloading to file, remains empty.
  std::string data_;
  // Total encoded data length, regardless of whether downloading to a file or
  // not.
  int total_encoded_data_length_;
  // Total length when downloading to a file.
  int total_downloaded_data_length_;

  bool complete_;

  ResourceLoaderBridge* bridge_;

  DISALLOW_COPY_AND_ASSIGN(TestRequestPeer);
};

// Sets up the message sender override for the unit test.
class ResourceDispatcherTest : public testing::Test, public IPC::Sender {
 public:
  ResourceDispatcherTest() : dispatcher_(this) {}

  virtual ~ResourceDispatcherTest() {
    STLDeleteContainerPairSecondPointers(shared_memory_map_.begin(),
                                         shared_memory_map_.end());
  }

  // Emulates IPC send operations (IPC::Sender) by adding
  // pending messages to the queue.
  virtual bool Send(IPC::Message* msg) OVERRIDE {
    message_queue_.push_back(IPC::Message(*msg));
    delete msg;
    return true;
  }

  size_t queued_messages() const { return message_queue_.size(); }

  // Returns the ID of the consumed request.  Can't make assumptions about the
  // ID, because numbering is based on a global.
  int ConsumeRequestResource() {
    if (message_queue_.empty()) {
      ADD_FAILURE() << "Missing resource request message";
      return -1;
    }

    ResourceHostMsg_RequestResource::Param params;
    if (ResourceHostMsg_RequestResource::ID != message_queue_[0].type() ||
        !ResourceHostMsg_RequestResource::Read(&message_queue_[0], &params)) {
      ADD_FAILURE() << "Expected ResourceHostMsg_RequestResource message";
      return -1;
    }
    ResourceHostMsg_Request request = params.c;
    EXPECT_EQ(kTestPageUrl, request.url.spec());
    message_queue_.erase(message_queue_.begin());
    return params.b;
  }

  void ConsumeFollowRedirect(int expected_request_id) {
    ASSERT_FALSE(message_queue_.empty());
    Tuple1<int> args;
    ASSERT_EQ(ResourceHostMsg_FollowRedirect::ID, message_queue_[0].type());
    ASSERT_TRUE(ResourceHostMsg_FollowRedirect::Read(
        &message_queue_[0], &args));
    EXPECT_EQ(expected_request_id, args.a);
    message_queue_.erase(message_queue_.begin());
  }

  void ConsumeDataReceived_ACK(int expected_request_id) {
    ASSERT_FALSE(message_queue_.empty());
    Tuple1<int> args;
    ASSERT_EQ(ResourceHostMsg_DataReceived_ACK::ID, message_queue_[0].type());
    ASSERT_TRUE(ResourceHostMsg_DataReceived_ACK::Read(
        &message_queue_[0], &args));
    EXPECT_EQ(expected_request_id, args.a);
    message_queue_.erase(message_queue_.begin());
  }

  void ConsumeDataDownloaded_ACK(int expected_request_id) {
    ASSERT_FALSE(message_queue_.empty());
    Tuple1<int> args;
    ASSERT_EQ(ResourceHostMsg_DataDownloaded_ACK::ID, message_queue_[0].type());
    ASSERT_TRUE(ResourceHostMsg_DataDownloaded_ACK::Read(
        &message_queue_[0], &args));
    EXPECT_EQ(expected_request_id, args.a);
    message_queue_.erase(message_queue_.begin());
  }

  void ConsumeReleaseDownloadedFile(int expected_request_id) {
    ASSERT_FALSE(message_queue_.empty());
    Tuple1<int> args;
    ASSERT_EQ(ResourceHostMsg_ReleaseDownloadedFile::ID,
              message_queue_[0].type());
    ASSERT_TRUE(ResourceHostMsg_ReleaseDownloadedFile::Read(
        &message_queue_[0], &args));
    EXPECT_EQ(expected_request_id, args.a);
    message_queue_.erase(message_queue_.begin());
  }

  void ConsumeCancelRequest(int expected_request_id) {
    ASSERT_FALSE(message_queue_.empty());
    Tuple1<int> args;
    ASSERT_EQ(ResourceHostMsg_CancelRequest::ID, message_queue_[0].type());
    ASSERT_TRUE(ResourceHostMsg_CancelRequest::Read(
        &message_queue_[0], &args));
    EXPECT_EQ(expected_request_id, args.a);
    message_queue_.erase(message_queue_.begin());
  }

  void NotifyReceivedRedirect(int request_id) {
    ResourceResponseHead head;
    std::string raw_headers(kTestRedirectHeaders);
    std::replace(raw_headers.begin(), raw_headers.end(), '\n', '\0');
    head.headers = new net::HttpResponseHeaders(raw_headers);
    head.error_code = net::OK;
    EXPECT_EQ(true, dispatcher_.OnMessageReceived(
        ResourceMsg_ReceivedRedirect(request_id, GURL(kTestPageUrl),
                                     GURL(kTestPageUrl), head)));
  }

  void NotifyReceivedResponse(int request_id) {
    ResourceResponseHead head;
    std::string raw_headers(kTestPageHeaders);
    std::replace(raw_headers.begin(), raw_headers.end(), '\n', '\0');
    head.headers = new net::HttpResponseHeaders(raw_headers);
    head.mime_type = kTestPageMimeType;
    head.charset = kTestPageCharset;
    head.error_code = net::OK;
    EXPECT_EQ(true,
              dispatcher_.OnMessageReceived(
                  ResourceMsg_ReceivedResponse(request_id, head)));
  }

  void NotifySetDataBuffer(int request_id, size_t buffer_size) {
    base::SharedMemory* shared_memory = new base::SharedMemory();
    ASSERT_FALSE(shared_memory_map_[request_id]);
    shared_memory_map_[request_id] = shared_memory;
    EXPECT_TRUE(shared_memory->CreateAndMapAnonymous(buffer_size));

    base::SharedMemoryHandle duplicate_handle;
    EXPECT_TRUE(shared_memory->ShareToProcess(
        base::Process::Current().handle(), &duplicate_handle));
    EXPECT_TRUE(dispatcher_.OnMessageReceived(
        ResourceMsg_SetDataBuffer(request_id, duplicate_handle,
                                  shared_memory->requested_size(), 0)));
  }

  void NotifyDataReceived(int request_id, std::string data) {
    ASSERT_LE(data.length(), shared_memory_map_[request_id]->requested_size());
    memcpy(shared_memory_map_[request_id]->memory(), data.c_str(),
           data.length());

    EXPECT_TRUE(dispatcher_.OnMessageReceived(
        ResourceMsg_DataReceived(request_id, 0, data.length(), data.length())));
  }

  void NotifyDataDownloaded(int request_id, int decoded_length,
                            int encoded_length) {
    EXPECT_TRUE(dispatcher_.OnMessageReceived(
        ResourceMsg_DataDownloaded(request_id, decoded_length,
                                   encoded_length)));
  }

  void NotifyRequestComplete(int request_id, size_t total_size) {
    ResourceMsg_RequestCompleteData request_complete_data;
    request_complete_data.error_code = net::OK;
    request_complete_data.was_ignored_by_handler = false;
    request_complete_data.exists_in_cache = false;
    request_complete_data.encoded_data_length = total_size;
    EXPECT_TRUE(dispatcher_.OnMessageReceived(
        ResourceMsg_RequestComplete(request_id, request_complete_data)));
  }

  ResourceLoaderBridge* CreateBridge() {
    return CreateBridgeInternal(false);
  }

  ResourceLoaderBridge* CreateBridgeForDownloadToFile() {
    return CreateBridgeInternal(true);
  }

  ResourceDispatcher* dispatcher() { return &dispatcher_; }

 private:
  ResourceLoaderBridge* CreateBridgeInternal(bool download_to_file) {
    RequestInfo request_info;
    request_info.method = "GET";
    request_info.url = GURL(kTestPageUrl);
    request_info.first_party_for_cookies = GURL(kTestPageUrl);
    request_info.referrer = GURL();
    request_info.headers = std::string();
    request_info.load_flags = 0;
    request_info.requestor_pid = 0;
    request_info.request_type = ResourceType::SUB_RESOURCE;
    request_info.appcache_host_id = appcache::kAppCacheNoHostId;
    request_info.routing_id = 0;
    request_info.download_to_file = download_to_file;
    RequestExtraData extra_data;
    request_info.extra_data = &extra_data;

    return dispatcher_.CreateBridge(request_info);
  }

  // Map of request IDs to shared memory.
  std::map<int, base::SharedMemory*> shared_memory_map_;

  std::vector<IPC::Message> message_queue_;
  ResourceDispatcher dispatcher_;
  base::MessageLoop message_loop_;
};

// Does a simple request and tests that the correct data is received.  Simulates
// two reads.
TEST_F(ResourceDispatcherTest, RoundTrip) {
  // Number of bytes received in the first read.
  const size_t kFirstReceiveSize = 2;
  ASSERT_LT(kFirstReceiveSize, strlen(kTestPageContents));

  scoped_ptr<ResourceLoaderBridge> bridge(CreateBridge());
  TestRequestPeer peer(bridge.get());

  EXPECT_TRUE(bridge->Start(&peer));
  int id = ConsumeRequestResource();
  EXPECT_EQ(0u, queued_messages());

  NotifyReceivedResponse(id);
  EXPECT_EQ(0u, queued_messages());
  EXPECT_TRUE(peer.received_response());

  NotifySetDataBuffer(id, strlen(kTestPageContents));
  NotifyDataReceived(id, std::string(kTestPageContents, kFirstReceiveSize));
  ConsumeDataReceived_ACK(id);
  EXPECT_EQ(0u, queued_messages());

  NotifyDataReceived(id, kTestPageContents + kFirstReceiveSize);
  ConsumeDataReceived_ACK(id);
  EXPECT_EQ(0u, queued_messages());

  NotifyRequestComplete(id, strlen(kTestPageContents));
  EXPECT_EQ(kTestPageContents, peer.data());
  EXPECT_TRUE(peer.complete());
  EXPECT_EQ(0u, queued_messages());
}

// Tests that the request IDs are straight when there are two interleaving
// requests.
TEST_F(ResourceDispatcherTest, MultipleRequests) {
  const char kTestPageContents2[] = "Not kTestPageContents";

  scoped_ptr<ResourceLoaderBridge> bridge1(CreateBridge());
  TestRequestPeer peer1(bridge1.get());
  scoped_ptr<ResourceLoaderBridge> bridge2(CreateBridge());
  TestRequestPeer peer2(bridge2.get());

  EXPECT_TRUE(bridge1->Start(&peer1));
  int id1 = ConsumeRequestResource();
  EXPECT_TRUE(bridge2->Start(&peer2));
  int id2 = ConsumeRequestResource();
  EXPECT_EQ(0u, queued_messages());

  NotifyReceivedResponse(id1);
  EXPECT_TRUE(peer1.received_response());
  EXPECT_FALSE(peer2.received_response());
  NotifyReceivedResponse(id2);
  EXPECT_TRUE(peer2.received_response());
  EXPECT_EQ(0u, queued_messages());

  NotifySetDataBuffer(id2, strlen(kTestPageContents2));
  NotifyDataReceived(id2, kTestPageContents2);
  ConsumeDataReceived_ACK(id2);
  NotifySetDataBuffer(id1, strlen(kTestPageContents));
  NotifyDataReceived(id1, kTestPageContents);
  ConsumeDataReceived_ACK(id1);
  EXPECT_EQ(0u, queued_messages());

  NotifyRequestComplete(id1, strlen(kTestPageContents));
  EXPECT_EQ(kTestPageContents, peer1.data());
  EXPECT_TRUE(peer1.complete());
  EXPECT_FALSE(peer2.complete());

  NotifyRequestComplete(id2, strlen(kTestPageContents2));
  EXPECT_EQ(kTestPageContents2, peer2.data());
  EXPECT_TRUE(peer2.complete());

  EXPECT_EQ(0u, queued_messages());
}

// Tests that the cancel method prevents other messages from being received.
TEST_F(ResourceDispatcherTest, Cancel) {
  scoped_ptr<ResourceLoaderBridge> bridge(CreateBridge());
  TestRequestPeer peer(bridge.get());

  EXPECT_TRUE(bridge->Start(&peer));
  int id = ConsumeRequestResource();
  EXPECT_EQ(0u, queued_messages());

  // Cancel the request.
  bridge->Cancel();
  ConsumeCancelRequest(id);

  // Any future messages related to the request should be ignored.
  NotifyReceivedResponse(id);
  NotifySetDataBuffer(id, strlen(kTestPageContents));
  NotifyDataReceived(id, kTestPageContents);
  NotifyRequestComplete(id, strlen(kTestPageContents));

  EXPECT_EQ(0u, queued_messages());
  EXPECT_EQ("", peer.data());
  EXPECT_FALSE(peer.received_response());
  EXPECT_FALSE(peer.complete());
}

// Tests that calling cancel during a callback works as expected.
TEST_F(ResourceDispatcherTest, CancelDuringCallback) {
  scoped_ptr<ResourceLoaderBridge> bridge(CreateBridge());
  TestRequestPeer peer(bridge.get());
  peer.set_cancel_on_receive_response(true);

  EXPECT_TRUE(bridge->Start(&peer));
  int id = ConsumeRequestResource();
  EXPECT_EQ(0u, queued_messages());

  NotifyReceivedResponse(id);
  EXPECT_TRUE(peer.received_response());
  // Request should have been cancelled.
  ConsumeCancelRequest(id);

  // Any future messages related to the request should be ignored.
  NotifySetDataBuffer(id, strlen(kTestPageContents));
  NotifyDataReceived(id, kTestPageContents);
  NotifyRequestComplete(id, strlen(kTestPageContents));

  EXPECT_EQ(0u, queued_messages());
  EXPECT_EQ("", peer.data());
  EXPECT_FALSE(peer.complete());
}

// Checks that redirects work as expected.
TEST_F(ResourceDispatcherTest, Redirect) {
  scoped_ptr<ResourceLoaderBridge> bridge(CreateBridge());
  TestRequestPeer peer(bridge.get());

  EXPECT_TRUE(bridge->Start(&peer));
  int id = ConsumeRequestResource();

  NotifyReceivedRedirect(id);
  ConsumeFollowRedirect(id);
  EXPECT_EQ(1, peer.seen_redirects());

  NotifyReceivedRedirect(id);
  ConsumeFollowRedirect(id);
  EXPECT_EQ(2, peer.seen_redirects());

  NotifyReceivedResponse(id);
  EXPECT_TRUE(peer.received_response());

  NotifySetDataBuffer(id, strlen(kTestPageContents));
  NotifyDataReceived(id, kTestPageContents);
  ConsumeDataReceived_ACK(id);

  NotifyRequestComplete(id, strlen(kTestPageContents));
  EXPECT_EQ(kTestPageContents, peer.data());
  EXPECT_TRUE(peer.complete());
  EXPECT_EQ(0u, queued_messages());
  EXPECT_EQ(2, peer.seen_redirects());
}

// Tests that that cancelling during a redirect method prevents other messages
// from being received.
TEST_F(ResourceDispatcherTest, CancelDuringRedirect) {
  scoped_ptr<ResourceLoaderBridge> bridge(CreateBridge());
  TestRequestPeer peer(bridge.get());
  peer.set_follow_redirects(false);

  EXPECT_TRUE(bridge->Start(&peer));
  int id = ConsumeRequestResource();
  EXPECT_EQ(0u, queued_messages());

  // Redirect the request, which triggers a cancellation.
  NotifyReceivedRedirect(id);
  ConsumeCancelRequest(id);
  EXPECT_EQ(1, peer.seen_redirects());
  EXPECT_EQ(0u, queued_messages());

  // Any future messages related to the request should be ignored.  In practice,
  // only the NotifyRequestComplete should be received after this point.
  NotifyReceivedRedirect(id);
  NotifyReceivedResponse(id);
  NotifySetDataBuffer(id, strlen(kTestPageContents));
  NotifyDataReceived(id, kTestPageContents);
  NotifyRequestComplete(id, strlen(kTestPageContents));

  EXPECT_EQ(0u, queued_messages());
  EXPECT_EQ("", peer.data());
  EXPECT_FALSE(peer.complete());
  EXPECT_EQ(1, peer.seen_redirects());
}

// Checks that deferring a request delays messages until it's resumed.
TEST_F(ResourceDispatcherTest, Defer) {
  scoped_ptr<ResourceLoaderBridge> bridge(CreateBridge());
  TestRequestPeer peer(bridge.get());

  EXPECT_TRUE(bridge->Start(&peer));
  int id = ConsumeRequestResource();
  EXPECT_EQ(0u, queued_messages());

  bridge->SetDefersLoading(true);
  NotifyReceivedResponse(id);
  NotifySetDataBuffer(id, strlen(kTestPageContents));
  NotifyDataReceived(id, kTestPageContents);
  NotifyRequestComplete(id, strlen(kTestPageContents));

  // None of the messages should have been processed yet, so no queued messages
  // to the browser process, and no data received by the peer.
  EXPECT_EQ(0u, queued_messages());
  EXPECT_EQ("", peer.data());
  EXPECT_FALSE(peer.complete());
  EXPECT_EQ(0, peer.seen_redirects());

  // Resuming the request should asynchronously unleash the deferred messages.
  bridge->SetDefersLoading(false);
  base::RunLoop().RunUntilIdle();

  ConsumeDataReceived_ACK(id);
  EXPECT_EQ(0u, queued_messages());
  EXPECT_TRUE(peer.received_response());
  EXPECT_EQ(kTestPageContents, peer.data());
  EXPECT_TRUE(peer.complete());
}

// Checks that deferring a request during a redirect delays messages until it's
// resumed.
TEST_F(ResourceDispatcherTest, DeferOnRedirect) {
  scoped_ptr<ResourceLoaderBridge> bridge(CreateBridge());
  TestRequestPeer peer(bridge.get());
  peer.set_defer_on_redirect(true);

  EXPECT_TRUE(bridge->Start(&peer));
  int id = ConsumeRequestResource();
  EXPECT_EQ(0u, queued_messages());

  // The request should be deferred during the redirect, including the message
  // to follow the redirect.
  NotifyReceivedRedirect(id);
  NotifyReceivedResponse(id);
  NotifySetDataBuffer(id, strlen(kTestPageContents));
  NotifyDataReceived(id, kTestPageContents);
  NotifyRequestComplete(id, strlen(kTestPageContents));

  // None of the messages should have been processed yet, so no queued messages
  // to the browser process, and no data received by the peer.
  EXPECT_EQ(0u, queued_messages());
  EXPECT_EQ("", peer.data());
  EXPECT_FALSE(peer.complete());
  EXPECT_EQ(1, peer.seen_redirects());

  // Resuming the request should asynchronously unleash the deferred messages.
  bridge->SetDefersLoading(false);
  base::RunLoop().RunUntilIdle();

  ConsumeFollowRedirect(id);
  ConsumeDataReceived_ACK(id);

  EXPECT_EQ(0u, queued_messages());
  EXPECT_TRUE(peer.received_response());
  EXPECT_EQ(kTestPageContents, peer.data());
  EXPECT_TRUE(peer.complete());
  EXPECT_EQ(1, peer.seen_redirects());
}

// Checks that a deferred request that's cancelled doesn't receive any messages.
TEST_F(ResourceDispatcherTest, CancelDeferredRequest) {
  scoped_ptr<ResourceLoaderBridge> bridge(CreateBridge());
  TestRequestPeer peer(bridge.get());

  EXPECT_TRUE(bridge->Start(&peer));
  int id = ConsumeRequestResource();
  EXPECT_EQ(0u, queued_messages());

  bridge->SetDefersLoading(true);
  NotifyReceivedRedirect(id);
  bridge->Cancel();
  ConsumeCancelRequest(id);

  NotifyRequestComplete(id, 0);
  base::RunLoop().RunUntilIdle();

  // None of the messages should have been processed.
  EXPECT_EQ(0u, queued_messages());
  EXPECT_EQ("", peer.data());
  EXPECT_FALSE(peer.complete());
  EXPECT_EQ(0, peer.seen_redirects());
}

TEST_F(ResourceDispatcherTest, DownloadToFile) {
  scoped_ptr<ResourceLoaderBridge> bridge(CreateBridgeForDownloadToFile());
  TestRequestPeer peer(bridge.get());
  const int kDownloadedIncrement = 100;
  const int kEncodedIncrement = 50;

  EXPECT_TRUE(bridge->Start(&peer));
  int id = ConsumeRequestResource();
  EXPECT_EQ(0u, queued_messages());

  NotifyReceivedResponse(id);
  EXPECT_EQ(0u, queued_messages());
  EXPECT_TRUE(peer.received_response());

  int expected_total_downloaded_length = 0;
  int expected_total_encoded_length = 0;
  for (int i = 0; i < 10; ++i) {
    NotifyDataDownloaded(id, kDownloadedIncrement, kEncodedIncrement);
    ConsumeDataDownloaded_ACK(id);
    expected_total_downloaded_length += kDownloadedIncrement;
    expected_total_encoded_length += kEncodedIncrement;
    EXPECT_EQ(expected_total_downloaded_length,
              peer.total_downloaded_data_length());
    EXPECT_EQ(expected_total_encoded_length, peer.total_encoded_data_length());
  }

  NotifyRequestComplete(id, strlen(kTestPageContents));
  EXPECT_EQ("", peer.data());
  EXPECT_TRUE(peer.complete());
  EXPECT_EQ(0u, queued_messages());

  bridge.reset();
  ConsumeReleaseDownloadedFile(id);
  EXPECT_EQ(0u, queued_messages());
  EXPECT_EQ(expected_total_downloaded_length,
            peer.total_downloaded_data_length());
  EXPECT_EQ(expected_total_encoded_length, peer.total_encoded_data_length());
}

// Make sure that when a download to file is cancelled, the file is destroyed.
TEST_F(ResourceDispatcherTest, CancelDownloadToFile) {
  scoped_ptr<ResourceLoaderBridge> bridge(CreateBridgeForDownloadToFile());
  TestRequestPeer peer(bridge.get());

  EXPECT_TRUE(bridge->Start(&peer));
  int id = ConsumeRequestResource();
  EXPECT_EQ(0u, queued_messages());

  NotifyReceivedResponse(id);
  EXPECT_EQ(0u, queued_messages());
  EXPECT_TRUE(peer.received_response());

  // Cancelling the request deletes the file.
  bridge->Cancel();
  ConsumeCancelRequest(id);
  ConsumeReleaseDownloadedFile(id);

  // Deleting the bridge shouldn't send another message to delete the file.
  bridge.reset();
  EXPECT_EQ(0u, queued_messages());
}

TEST_F(ResourceDispatcherTest, Cookies) {
  // FIXME
}

TEST_F(ResourceDispatcherTest, SerializedPostData) {
  // FIXME
}

class TimeConversionTest : public ResourceDispatcherTest,
                           public RequestPeer {
 public:
  virtual bool Send(IPC::Message* msg) OVERRIDE {
    delete msg;
    return true;
  }

  void PerformTest(const ResourceResponseHead& response_head) {
    scoped_ptr<ResourceLoaderBridge> bridge(CreateBridge());
    bridge->Start(this);

    dispatcher()->OnMessageReceived(
        ResourceMsg_ReceivedResponse(0, response_head));
  }

  // RequestPeer methods.
  virtual void OnUploadProgress(uint64 position, uint64 size) OVERRIDE {
  }

  virtual bool OnReceivedRedirect(const GURL& new_url,
                                  const GURL& new_first_party_for_cookies,
                                  const ResourceResponseInfo& info) OVERRIDE {
    return true;
  }

  virtual void OnReceivedResponse(const ResourceResponseInfo& info) OVERRIDE {
    response_info_ = info;
  }

  virtual void OnDownloadedData(int len, int encoded_data_length) OVERRIDE {
  }

  virtual void OnReceivedData(const char* data,
                              int data_length,
                              int encoded_data_length) OVERRIDE {
  }

  virtual void OnCompletedRequest(
      int error_code,
      bool was_ignored_by_handler,
      bool stale_copy_in_cache,
      const std::string& security_info,
      const base::TimeTicks& completion_time,
      int64 total_transfer_size) OVERRIDE {
  }

  const ResourceResponseInfo& response_info() const { return response_info_; }

 private:
  ResourceResponseInfo response_info_;
};

// TODO(simonjam): Enable this when 10829031 lands.
TEST_F(TimeConversionTest, DISABLED_ProperlyInitialized) {
  ResourceResponseHead response_head;
  response_head.error_code = net::OK;
  response_head.request_start = base::TimeTicks::FromInternalValue(5);
  response_head.response_start = base::TimeTicks::FromInternalValue(15);
  response_head.load_timing.request_start_time = base::Time::Now();
  response_head.load_timing.request_start =
      base::TimeTicks::FromInternalValue(10);
  response_head.load_timing.connect_timing.connect_start =
      base::TimeTicks::FromInternalValue(13);

  PerformTest(response_head);

  EXPECT_LT(base::TimeTicks(), response_info().load_timing.request_start);
  EXPECT_EQ(base::TimeTicks(),
            response_info().load_timing.connect_timing.dns_start);
  EXPECT_LE(response_head.load_timing.request_start,
            response_info().load_timing.connect_timing.connect_start);
}

TEST_F(TimeConversionTest, PartiallyInitialized) {
  ResourceResponseHead response_head;
  response_head.error_code = net::OK;
  response_head.request_start = base::TimeTicks::FromInternalValue(5);
  response_head.response_start = base::TimeTicks::FromInternalValue(15);

  PerformTest(response_head);

  EXPECT_EQ(base::TimeTicks(), response_info().load_timing.request_start);
  EXPECT_EQ(base::TimeTicks(),
            response_info().load_timing.connect_timing.dns_start);
}

TEST_F(TimeConversionTest, NotInitialized) {
  ResourceResponseHead response_head;
  response_head.error_code = net::OK;

  PerformTest(response_head);

  EXPECT_EQ(base::TimeTicks(), response_info().load_timing.request_start);
  EXPECT_EQ(base::TimeTicks(),
            response_info().load_timing.connect_timing.dns_start);
}

}  // namespace content


text:
package com.nd.android.rxjavademo.activity.schedulers;

import com.nd.android.rxjavademo.R;
import com.nd.android.rxjavademo.activity.BaseShowActivity;
import com.nd.android.rxjavademo.data.IMainListData;
import com.nd.android.rxjavademo.data.impl.schedulers.MainListData_Schedulers;

/**
 * SubscribeOn
 * <p>
 * Created by HuangYK on 16/9/1.
 */
public class SchedulersActivity extends BaseShowActivity {

    @Override
    protected int getContentViewId() {
        return R.layout.activity_schedulers;
    }

    @Override
    protected IMainListData getMainListData() {
        return new MainListData_Schedulers();
    }
}